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/SetpointController.cs b/Persistence.API/Controllers/SetpointController.cs
index 42a5ff5..c374d9e 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.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
+using System.Net;
namespace Persistence.API.Controllers;
@@ -14,99 +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 d2691c1..f19f428 100644
--- a/Persistence.API/Controllers/TechMessagesController.cs
+++ b/Persistence.API/Controllers/TechMessagesController.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.Repositories;
+using System.Net;
namespace Persistence.API.Controllers;
@@ -14,115 +14,115 @@ namespace Persistence.API.Controllers;
[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 Dictionary()
+ {
+ { 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] RequestDto request, CancellationToken token)
- {
- var result = await techMessagesRepository.GetPage(request, token);
+ ///
+ /// Получить список технологических сообщений в виде страницы
+ ///
+ ///
+ ///
+ ///
+ [HttpGet]
+ public async Task>> GetPage([FromQuery] RequestDto 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/DependencyInjection.cs b/Persistence.API/DependencyInjection.cs
index 19cedc9..953565e 100644
--- a/Persistence.API/DependencyInjection.cs
+++ b/Persistence.API/DependencyInjection.cs
@@ -1,5 +1,3 @@
-using System.Reflection;
-using System.Text.Json.Nodes;
using Mapster;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
@@ -9,17 +7,19 @@ using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Configurations;
using Swashbuckle.AspNetCore.SwaggerGen;
+using System.Reflection;
+using System.Text.Json.Nodes;
namespace Persistence.API;
public static class DependencyInjection
{
- public static void MapsterSetup()
- {
- TypeAdapterConfig.GlobalSettings.Default.Config
- .ForType()
- .Ignore(dest => dest.System, dest => dest.SystemId);
- }
+ public static void MapsterSetup()
+ {
+ TypeAdapterConfig.GlobalSettings.Default.Config
+ .ForType()
+ .Ignore(dest => dest.System, dest => dest.SystemId);
+ }
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
{
services.AddSwaggerGen(c =>
@@ -28,12 +28,12 @@ public static class DependencyInjection
c.MapType(() => new OpenApiSchema { Type = "string", Format = "date" });
c.MapType(() => new OpenApiSchema
{
- AnyOf = new OpenApiSchema[]
- {
- new OpenApiSchema {Type = "string", Format = "string" },
- new OpenApiSchema {Type = "number", Format = "int32" },
- new OpenApiSchema {Type = "number", Format = "float" },
- }
+ AnyOf =
+ [
+ new() {Type = "string", Format = "string" },
+ new() {Type = "number", Format = "int32" },
+ new() {Type = "number", Format = "float" },
+ ]
});
c.CustomOperationIds(e =>
@@ -43,162 +43,163 @@ public static class DependencyInjection
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" });
- var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get();
- if (needUseKeyCloak)
- c.AddKeycloackSecurity(configuration);
- else c.AddDefaultSecurity(configuration);
+ var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get();
+ if (needUseKeyCloak)
+ c.AddKeycloakSecurity(configuration);
+ else c.AddDefaultSecurity();
- var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
- var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
- var includeControllerXmlComment = true;
- c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
- });
+ var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
+ var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
+ var includeControllerXmlComment = true;
+ c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
+ });
}
- #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")
- .Get();
- if (needUseKeyCloak)
- services.AddKeyCloakAuthentication(configuration);
- else services.AddDefaultAuthentication(configuration);
- }
+ .GetSection("NeedUseKeyCloak")
+ .Get();
+ if (needUseKeyCloak)
+ services.AddKeyCloakAuthentication(configuration);
+ else services.AddDefaultAuthentication(configuration);
+ }
- private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.RequireHttpsMetadata = false;
- options.Audience = configuration["Authentication:Audience"];
- options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ValidIssuer = configuration["Authentication:ValidIssuer"],
- };
- });
- }
+ private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
+ {
+ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+ .AddJwtBearer(options =>
+ {
+ options.RequireHttpsMetadata = false;
+ options.Audience = configuration["Authentication:Audience"];
+ options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ValidIssuer = configuration["Authentication:ValidIssuer"],
+ };
+ });
+ }
- private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration)
- {
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.RequireHttpsMetadata = false;
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = true,
- ValidIssuer = JwtParams.Issuer,
- ValidateAudience = true,
- ValidAudience = JwtParams.Audience,
- ValidateLifetime = true,
- IssuerSigningKey = JwtParams.SecurityKey,
- ValidateIssuerSigningKey = false
- };
- options.Events = new JwtBearerEvents
- {
- OnMessageReceived = context =>
- {
- var accessToken = context.Request.Headers["Authorization"]
- .ToString()
- .Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
- .Trim();
+ private static void AddDefaultAuthentication(this IServiceCollection services, IConfiguration configuration)
+ {
+ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+ .AddJwtBearer(options =>
+ {
+ options.RequireHttpsMetadata = false;
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ValidateIssuer = true,
+ ValidIssuer = JwtParams.Issuer,
+ ValidateAudience = true,
+ ValidAudience = JwtParams.Audience,
+ ValidateLifetime = true,
+ IssuerSigningKey = JwtParams.SecurityKey,
+ ValidateIssuerSigningKey = false
+ };
+ options.Events = new JwtBearerEvents
+ {
+ OnMessageReceived = context =>
+ {
+ var accessToken = context.Request.Headers["Authorization"]
+ .ToString()
+ .Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
+ .Trim();
- context.Token = accessToken;
+ context.Token = accessToken;
- return Task.CompletedTask;
- },
- OnTokenValidated = context =>
- {
- var username = context.Principal?.Claims
- .FirstOrDefault(e => e.Type == "username")?.Value;
+ return Task.CompletedTask;
+ },
+ OnTokenValidated = context =>
+ {
+ var username = context.Principal?.Claims
+ .FirstOrDefault(e => e.Type == "username")?.Value;
- var password = context.Principal?.Claims
- .FirstOrDefault(e => e.Type == "password")?.Value;
+ var password = context.Principal?.Claims
+ .FirstOrDefault(e => e.Type == "password")?.Value;
- var keyCloakUser = configuration
- .GetSection(nameof(AuthUser))
- .Get()!;
+ var keyCloakUser = configuration
+ .GetSection(nameof(AuthUser))
+ .Get()!;
- if (username != keyCloakUser.Username || password != keyCloakUser.Password)
- {
- context.Fail("username or password did not match");
- }
+ if (username != keyCloakUser.Username || password != keyCloakUser.Password)
+ {
+ context.Fail("username or password did not match");
+ }
- return Task.CompletedTask;
- }
- };
- });
- }
- #endregion
+ return Task.CompletedTask;
+ }
+ };
+ });
+ }
+ #endregion
- #region Security (Swagger)
- private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration)
- {
- options.AddSecurityDefinition("Keycloack", 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'",
- Name = "Authorization",
- In = ParameterLocation.Header,
- Type = SecuritySchemeType.OAuth2,
- Flows = new OpenApiOAuthFlows
- {
- Implicit = new OpenApiOAuthFlow
- {
- AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]),
- }
- }
- });
+ #region Security (Swagger)
+ private static void AddKeycloakSecurity(this SwaggerGenOptions options, IConfiguration configuration)
+ {
+ 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'",
+ Name = "Authorization",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.OAuth2,
+ Flows = new OpenApiOAuthFlows
+ {
+ Implicit = new OpenApiOAuthFlow
+ {
+
+ AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]!),
+ }
+ }
+ });
- options.AddSecurityRequirement(new OpenApiSecurityRequirement()
- {
- {
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type = ReferenceType.SecurityScheme,
- Id = "Keycloack"
- },
- Scheme = "Bearer",
- Name = "Bearer",
- In = ParameterLocation.Header,
- },
- new List()
- }
- });
- }
+ options.AddSecurityRequirement(new OpenApiSecurityRequirement()
+ {
+ {
+ new OpenApiSecurityScheme
+ {
+ Reference = new OpenApiReference
+ {
+ Type = ReferenceType.SecurityScheme,
+ Id = "Keycloak"
+ },
+ Scheme = "Bearer",
+ Name = "Bearer",
+ In = ParameterLocation.Header,
+ },
+ new List()
+ }
+ });
+ }
- private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration)
- {
- 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'",
- Name = "Authorization",
- In = ParameterLocation.Header,
- Type = SecuritySchemeType.ApiKey,
- Scheme = "Bearer",
- });
+ 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'",
+ Name = "Authorization",
+ In = ParameterLocation.Header,
+ Type = SecuritySchemeType.ApiKey,
+ Scheme = "Bearer",
+ });
- options.AddSecurityRequirement(new OpenApiSecurityRequirement()
- {
- {
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type = ReferenceType.SecurityScheme,
- Id = "Bearer"
- },
- Scheme = "oauth2",
- Name = "Bearer",
- In = ParameterLocation.Header,
- },
- new List()
- }
- });
- }
- #endregion
+ options.AddSecurityRequirement(new OpenApiSecurityRequirement()
+ {
+ {
+ new OpenApiSecurityScheme
+ {
+ Reference = new OpenApiReference
+ {
+ Type = ReferenceType.SecurityScheme,
+ Id = "Bearer"
+ },
+ Scheme = "oauth2",
+ Name = "Bearer",
+ In = ParameterLocation.Header,
+ },
+ new List()
+ }
+ });
+ }
+ #endregion
}
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 98ad4aa..2255664 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/ISetpointClient.cs b/Persistence.Client/Clients/ISetpointClient.cs
index 0b81ffa..47c4352 100644
--- a/Persistence.Client/Clients/ISetpointClient.cs
+++ b/Persistence.Client/Clients/ISetpointClient.cs
@@ -8,23 +8,23 @@ namespace Persistence.Client.Clients;
///
public interface ISetpointClient
{
- private const string BaseRoute = "/api/setpoint";
+ private const string BaseRoute = "/api/setpoint";
- [Get($"{BaseRoute}/current")]
- Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys);
-
- [Get($"{BaseRoute}/history")]
- Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment);
+ [Get($"{BaseRoute}/current")]
+ Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys);
- [Get($"{BaseRoute}/log")]
- Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys);
+ [Get($"{BaseRoute}/history")]
+ Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment);
- [Get($"{BaseRoute}/range")]
- Task> GetDatesRangeAsync(CancellationToken token);
+ [Get($"{BaseRoute}/log")]
+ Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys);
- [Get($"{BaseRoute}/part")]
- Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
+ [Get($"{BaseRoute}/range")]
+ Task> GetDatesRangeAsync(CancellationToken token);
- [Post($"{BaseRoute}/")]
- Task Add(Guid setpointKey, object newValue);
+ [Get($"{BaseRoute}/part")]
+ Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
+
+ [Post($"{BaseRoute}/")]
+ Task Add(Guid setpointKey, object newValue);
}
diff --git a/Persistence.Client/Clients/ITechMessagesClient.cs b/Persistence.Client/Clients/ITechMessagesClient.cs
index 878c6cf..f3f37fe 100644
--- a/Persistence.Client/Clients/ITechMessagesClient.cs
+++ b/Persistence.Client/Clients/ITechMessagesClient.cs
@@ -3,29 +3,29 @@ using Refit;
namespace Persistence.Client.Clients
{
- ///
- /// Интерфейс клиента для хранения технологических сообщений
- ///
- public interface ITechMessagesClient
- {
- private const string BaseRoute = "/api/techMessages";
+ ///
+ /// Интерфейс клиента для хранения технологических сообщений
+ ///
+ public interface ITechMessagesClient
+ {
+ private const string BaseRoute = "/api/techMessages";
- [Get($"{BaseRoute}")]
- Task>> GetPage([Query] RequestDto request, CancellationToken token);
+ [Get($"{BaseRoute}")]
+ Task>> GetPage([Query] RequestDto request, CancellationToken token);
- [Post($"{BaseRoute}")]
- Task> AddRange([Body] IEnumerable dtos, CancellationToken token);
+ [Post($"{BaseRoute}")]
+ Task> AddRange([Body] IEnumerable dtos, CancellationToken token);
- [Get($"{BaseRoute}/systems")]
- Task>> GetSystems(CancellationToken token);
+ [Get($"{BaseRoute}/systems")]
+ Task>> GetSystems(CancellationToken token);
- [Get($"{BaseRoute}/range")]
- Task> GetDatesRangeAsync(CancellationToken token);
+ [Get($"{BaseRoute}/range")]
+ Task> GetDatesRangeAsync(CancellationToken token);
- [Get($"{BaseRoute}/part")]
- Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
+ [Get($"{BaseRoute}/part")]
+ Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
- [Get($"{BaseRoute}/statistics")]
- Task>> GetStatistics([Query] string autoDrillingSystem, [Query] int categoryId, CancellationToken token);
- }
+ [Get($"{BaseRoute}/statistics")]
+ Task>> GetStatistics([Query] string autoDrillingSystem, [Query] int categoryId, CancellationToken token);
+ }
}
diff --git a/Persistence.Client/Clients/ITimeSeriesClient.cs b/Persistence.Client/Clients/ITimeSeriesClient.cs
index 8e97836..c2cbf91 100644
--- a/Persistence.Client/Clients/ITimeSeriesClient.cs
+++ b/Persistence.Client/Clients/ITimeSeriesClient.cs
@@ -15,7 +15,7 @@ public interface ITimeSeriesClient
[Get($"{BaseRoute}/resampled")]
Task>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024);
-
+
[Get($"{BaseRoute}/datesRange")]
Task> GetDatesRange();
}
diff --git a/Persistence.Client/Helpers/ApiTokenHelper.cs b/Persistence.Client/Helpers/ApiTokenHelper.cs
index 5eed66e..f0249d0 100644
--- a/Persistence.Client/Helpers/ApiTokenHelper.cs
+++ b/Persistence.Client/Helpers/ApiTokenHelper.cs
@@ -1,74 +1,74 @@
-using System.IdentityModel.Tokens.Jwt;
-using System.Net.Http.Headers;
-using System.Security.Claims;
-using System.Text.Json;
-using Microsoft.Extensions.Configuration;
+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);
+ }
- private static string CreateDefaultJwtToken(this AuthUser authUser)
- {
- var nameIdetifier = Guid.NewGuid().ToString();
- var claims = new List()
- {
- new(ClaimTypes.NameIdentifier, nameIdetifier),
- new("client_id", authUser.ClientId),
- new("username", authUser.Username),
- new("password", authUser.Password),
- new("grant_type", authUser.GrantType)
- };
+ private static string CreateDefaultJwtToken(this AuthUser authUser)
+ {
+ var nameIdentifier = Guid.NewGuid().ToString();
+ var claims = new List()
+ {
+ new(ClaimTypes.NameIdentifier, nameIdentifier),
+ new("client_id", authUser.ClientId),
+ new("username", authUser.Username),
+ new("password", authUser.Password),
+ new("grant_type", authUser.GrantType)
+ };
- 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/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs
index e84327d..77f59d4 100644
--- a/Persistence.Client/PersistenceClientFactory.cs
+++ b/Persistence.Client/PersistenceClientFactory.cs
@@ -1,32 +1,32 @@
-using System.Text.Json;
-using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Configuration;
using Persistence.Client.Helpers;
using Refit;
+using System.Text.Json;
namespace Persistence.Client
{
- ///
- /// Фабрика клиентов для доступа к Persistence - сервису
- ///
- public class PersistenceClientFactory
- {
- private static readonly JsonSerializerOptions JsonSerializerOptions = new()
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
- PropertyNameCaseInsensitive = true
- };
- private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
- private HttpClient httpClient;
- public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IConfiguration configuration)
- {
- this.httpClient = httpClientFactory.CreateClient();
+ ///
+ /// Фабрика клиентов для доступа к Persistence - сервису
+ ///
+ public class PersistenceClientFactory
+ {
+ private static readonly JsonSerializerOptions JsonSerializerOptions = new()
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ PropertyNameCaseInsensitive = true
+ };
+ private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
+ private HttpClient httpClient;
+ public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IConfiguration configuration)
+ {
+ this.httpClient = httpClientFactory.CreateClient();
- httpClient.Authorize(configuration);
- }
+ httpClient.Authorize(configuration);
+ }
- public T GetClient()
- {
- return RestService.For(httpClient, RefitSettings);
- }
- }
+ public T GetClient()
+ {
+ return RestService.For(httpClient, RefitSettings);
+ }
+ }
}
diff --git a/Persistence.Database.Postgres/EFExtensionsInitialization.cs b/Persistence.Database.Postgres/EFExtensionsInitialization.cs
index 3d2752f..1872628 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/PersistenceDbContext.cs b/Persistence.Database.Postgres/PersistenceDbContext.cs
index 89b09db..4d0218b 100644
--- a/Persistence.Database.Postgres/PersistenceDbContext.cs
+++ b/Persistence.Database.Postgres/PersistenceDbContext.cs
@@ -1,23 +1,21 @@
using Microsoft.EntityFrameworkCore;
-using Npgsql;
using Persistence.Database.Entity;
-using System.Data.Common;
namespace Persistence.Database.Model;
public partial class PersistenceDbContext : DbContext
{
public DbSet DataSaub => Set();
- public DbSet Setpoint => Set();
+ public DbSet Setpoint => Set();
- public DbSet TechMessage => Set();
+ public DbSet TechMessage => Set();
- public DbSet TimestampedSets => Set();
+ public DbSet TimestampedSets => Set();
public PersistenceDbContext()
: base()
{
-
+
}
public PersistenceDbContext(DbContextOptions options)
@@ -49,7 +47,7 @@ public partial class PersistenceDbContext : DbContext
.WithMany()
.HasForeignKey(t => t.SystemId)
.OnDelete(DeleteBehavior.Cascade)
- .IsRequired();
- });
- }
+ .IsRequired();
+ });
+ }
}
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/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/ITimestampedData.cs b/Persistence.Database/Entity/ITimestampedData.cs
index 9241ca5..ce21da5 100644
--- a/Persistence.Database/Entity/ITimestampedData.cs
+++ b/Persistence.Database/Entity/ITimestampedData.cs
@@ -1,10 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Persistence.Database.Model;
+namespace Persistence.Database.Model;
public interface ITimestampedData
{
///
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.IntegrationTests/BaseIntegrationTest.cs b/Persistence.IntegrationTests/BaseIntegrationTest.cs
index 8a8f764..e2f333e 100644
--- a/Persistence.IntegrationTests/BaseIntegrationTest.cs
+++ b/Persistence.IntegrationTests/BaseIntegrationTest.cs
@@ -1,10 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using Persistence.Database.Model;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
using Xunit;
namespace Persistence.IntegrationTests;
diff --git a/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs b/Persistence.IntegrationTests/Controllers/DataSaubControllerTest.cs
index 9febbb5..cdb2381 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.Database.Model;
using Persistence.Repository.Data;
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,
@@ -76,7 +75,7 @@ public class DataSaubControllerTest : TimeSeriesBaseControllerTest();
+ public class SetpointControllerTest : BaseIntegrationTest
+ {
+ private 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.GetClient();
- }
+ setpointClient = persistenceClientFactory.GetClient();
+ }
- [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);
+ //act
+ var response = await setpointClient.GetCurrent(setpointKeys);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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]);
+ //act
+ var response = await setpointClient.GetCurrent([setpointKey]);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotEmpty(response.Content);
- Assert.Equal(setpointKey, response.Content.FirstOrDefault()?.Key);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotEmpty(response.Content);
+ Assert.Equal(setpointKey, response.Content.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);
+ //act
+ var response = await setpointClient.GetHistory(setpointKeys, historyMoment);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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);
+ //act
+ var response = await setpointClient.GetHistory([setpointKey], historyMoment);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotEmpty(response.Content);
- Assert.Equal(setpointKey, response.Content.FirstOrDefault()?.Key);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotEmpty(response.Content);
+ Assert.Equal(setpointKey, response.Content.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);
+ //act
+ var response = await setpointClient.GetLog(setpointKeys);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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]);
+ //act
+ var response = await setpointClient.GetLog([setpointKey]);
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotEmpty(response.Content);
- Assert.Equal(setpointKey, response.Content.FirstOrDefault().Key);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotEmpty(response.Content);
+ Assert.Equal(setpointKey, response.Content.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(new CancellationToken());
+ //act
+ var response = await setpointClient.GetDatesRangeAsync(new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Equal(DateTimeOffset.MinValue, response.Content!.From);
- Assert.Equal(DateTimeOffset.MaxValue, response.Content!.To);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Equal(DateTimeOffset.MinValue, response.Content!.From);
+ Assert.Equal(DateTimeOffset.MaxValue, response.Content!.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();
- var dateBegin = DateTimeOffset.MinValue;
- var take = 1;
- var part = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
+ await Add();
- //act
- var response = await setpointClient.GetDatesRangeAsync(new CancellationToken());
+ var dateBegin = DateTimeOffset.MinValue;
+ var take = 1;
+ var part = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
+ //act
+ var response = await setpointClient.GetDatesRangeAsync(new CancellationToken());
- var expectedValue = part.Content!
- .FirstOrDefault()!.Created
- .ToString("dd.MM.yyyy-HH:mm:ss");
- var actualValueFrom = response.Content.From
- .ToString("dd.MM.yyyy-HH:mm:ss");
- Assert.Equal(expectedValue, actualValueFrom);
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
- var actualValueTo = response.Content.To
- .ToString("dd.MM.yyyy-HH:mm:ss");
- Assert.Equal(expectedValue, actualValueTo);
- }
+ var expectedValue = part.Content!
+ .FirstOrDefault()!.Created
+ .ToString("dd.MM.yyyy-HH:mm:ss");
+ var actualValueFrom = response.Content.From
+ .ToString("dd.MM.yyyy-HH:mm:ss");
+ Assert.Equal(expectedValue, actualValueFrom);
- [Fact]
- public async Task GetPart_returns_success()
- {
- //arrange
- var dateBegin = DateTimeOffset.UtcNow;
- var take = 2;
+ var actualValueTo = response.Content.To
+ .ToString("dd.MM.yyyy-HH:mm:ss");
+ Assert.Equal(expectedValue, actualValueTo);
+ }
- //act
- var response = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
+ [Fact]
+ public async Task GetPart_returns_success()
+ {
+ //arrange
+ var dateBegin = DateTimeOffset.UtcNow;
+ var take = 2;
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //act
+ var response = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
- [Fact]
- public async Task GetPart_AfterSave_returns_success()
- {
- //arrange
- var dateBegin = DateTimeOffset.UtcNow;
- var take = 1;
- await Add();
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- //act
- var response = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
+ [Fact]
+ public async Task GetPart_AfterSave_returns_success()
+ {
+ //arrange
+ var dateBegin = DateTimeOffset.UtcNow;
+ var take = 1;
+ await Add();
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotEmpty(response.Content);
- }
+ //act
+ var response = await setpointClient.GetPart(dateBegin, take, new CancellationToken());
- [Fact]
- public async Task Save_returns_success()
- {
- await Add();
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotEmpty(response.Content);
+ }
- private async Task Add()
- {
- //arrange
- var setpointKey = Guid.NewGuid();
- var setpointValue = new TestObject()
- {
- value1 = "1",
- value2 = 2
- };
+ [Fact]
+ public async Task Save_returns_success()
+ {
+ await Add();
+ }
- //act
- var response = await setpointClient.Add(setpointKey, setpointValue);
+ private async Task Add()
+ {
+ //arrange
+ var setpointKey = Guid.NewGuid();
+ var setpointValue = new TestObject()
+ {
+ value1 = "1",
+ value2 = 2
+ };
- //assert
- Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ //act
+ var response = await setpointClient.Add(setpointKey, setpointValue);
- return setpointKey;
- }
- }
+ //assert
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+
+ return setpointKey;
+ }
+ }
}
diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs
index 1f194ad..63f5171 100644
--- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs
+++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs
@@ -1,288 +1,288 @@
-using System.Net;
-using Microsoft.Extensions.Caching.Memory;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients;
using Persistence.Database.Entity;
using Persistence.Models;
+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.GetClient();
- memoryCache = scope.ServiceProvider.GetRequiredService();
- }
+ techMessagesClient = persistenceClientFactory.GetClient();
+ 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 RequestDto()
- {
- Skip = 1,
- Take = 2,
- SortSettings = nameof(TechMessage.CategoryId)
- };
+ var requestDto = new RequestDto()
+ {
+ Skip = 1,
+ Take = 2,
+ SortSettings = nameof(TechMessage.CategoryId)
+ };
- //act
- var response = await techMessagesClient.GetPage(requestDto, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetPage(requestDto, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content.Items);
- Assert.Equal(requestDto.Skip, response.Content.Skip);
- Assert.Equal(requestDto.Take, response.Content.Take);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content.Items);
+ Assert.Equal(requestDto.Skip, response.Content.Skip);
+ Assert.Equal(requestDto.Take, response.Content.Take);
+ }
- [Fact]
- public async Task GetPage_AfterSave_returns_success()
- {
- //arrange
- var dtos = await InsertRange();
- var dtosCount = dtos.Count();
- var requestDto = new RequestDto()
- {
- 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 RequestDto()
+ {
+ Skip = 0,
+ Take = 2,
+ SortSettings = nameof(TechMessage.CategoryId)
+ };
- //act
- var response = await techMessagesClient.GetPage(requestDto, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetPage(requestDto, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Equal(dtosCount, response.Content.Count);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Equal(dtosCount, response.Content.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()
- {
- //arrange
- var dtos = new List()
- {
- new TechMessageDto()
- {
- EventId = Guid.NewGuid(),
- CategoryId = -1, // < 0
+ [Fact]
+ public async Task InsertRange_returns_BadRequest()
+ {
+ //arrange
+ var dtos = new List()
+ {
+ new()
+ {
+ 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()
- }
- };
+ }
+ };
- //act
- var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
+ //act
+ var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ }
- [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(new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetSystems(new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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(new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetSystems(new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- string?[]? content = response.Content?.ToArray();
- Assert.Equal(systems, content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ string?[]? content = response.Content?.ToArray();
+ 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 imortantId = 1;
+ var autoDrillingSystem = nameof(TechMessageDto.System);
- //act
- var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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 imortantId = 0;
+ var autoDrillingSystem = nameof(TechMessageDto.System);
+ var dtos = await InsertRange();
+ var filteredDtos = dtos.Where(e => e.CategoryId == imortantId && e.System == autoDrillingSystem);
- //act
- var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- var categories = response.Content
- .FirstOrDefault()?.Categories
- .FirstOrDefault(e => e.Key == 0).Value;
- Assert.Equal(filteredDtos.Count(), categories);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ var categories = response.Content
+ .FirstOrDefault()?.Categories
+ .FirstOrDefault(e => e.Key == 0).Value;
+ Assert.Equal(filteredDtos.Count(), categories);
+ }
- [Fact]
- public async Task GetDatesRange_returns_success()
- {
- //act
- var response = await techMessagesClient.GetDatesRangeAsync(new CancellationToken());
+ [Fact]
+ public async Task GetDatesRange_returns_success()
+ {
+ //act
+ var response = await techMessagesClient.GetDatesRangeAsync(new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- //Assert.Equal(DateTimeOffset.MinValue, response.Content?.From);
- //Assert.Equal(DateTimeOffset.MaxValue, response.Content?.To);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ //Assert.Equal(DateTimeOffset.MinValue, response.Content?.From);
+ //Assert.Equal(DateTimeOffset.MaxValue, response.Content?.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(new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetDatesRangeAsync(new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotNull(response.Content?.From);
- Assert.NotNull(response.Content?.To);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotNull(response.Content?.From);
+ Assert.NotNull(response.Content?.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, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetPart(dateBegin, take, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.Empty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.Empty(response.Content);
+ }
- [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, new CancellationToken());
+ //act
+ var response = await techMessagesClient.GetPart(dateBegin, take, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.NotNull(response.Content);
- Assert.NotEmpty(response.Content);
- }
+ //assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.NotNull(response.Content);
+ Assert.NotEmpty(response.Content);
+ }
- 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, new CancellationToken());
+ //act
+ var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
- //assert
- Assert.Equal(HttpStatusCode.Created, response.StatusCode);
- Assert.Equal(dtos.Count, response.Content);
+ //assert
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ Assert.Equal(dtos.Count, response.Content);
- return dtos;
- }
- }
+ return dtos;
+ }
+ }
}
diff --git a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs
index 08bb11e..f5cb591 100644
--- a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs
+++ b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs
@@ -1,12 +1,13 @@
-using System.Net;
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients;
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()
@@ -17,11 +18,11 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat
{
dbContext.CleanupDbSet();
- var scope = factory.Services.CreateScope();
- var persistenceClientFactory = scope.ServiceProvider
- .GetRequiredService();
+ var scope = factory.Services.CreateScope();
+ var persistenceClientFactory = scope.ServiceProvider
+ .GetRequiredService();
- timeSeriesClient = persistenceClientFactory.GetClient>();
+ timeSeriesClient = persistenceClientFactory.GetClient>();
}
public async Task InsertRangeSuccess(TDto dto)
@@ -104,7 +105,7 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
- 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 3fc7dff..296c7b6 100644
--- a/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs
+++ b/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs
@@ -39,7 +39,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);
+ await client.AddRange(idDiscriminator, testSets);
// act
var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue);
@@ -58,7 +58,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);
+ await client.AddRange(idDiscriminator, testSets);
string[] props = ["A"];
// act
@@ -69,12 +69,12 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Assert.NotNull(response.Content);
var items = response.Content!;
Assert.Equal(count, items.Count());
- foreach ( var item in items )
+ foreach (var item in items)
{
Assert.Single(item.Set);
var kv = item.Set.First();
Assert.Equal("A", kv.Key);
- }
+ }
}
[Fact]
@@ -85,7 +85,7 @@ 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)));
+ IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets);
var tail = testSets.OrderBy(t => t.Timestamp).Skip(count / 2).Take(int.MaxValue);
var geDate = tail.First().Timestamp;
@@ -152,7 +152,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);
+ await client.AddRange(idDiscriminator, testSets);
var expectedCount = 8;
// act
@@ -172,7 +172,7 @@ 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);
var tolerance = TimeSpan.FromSeconds(1);
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
index 6b09587..260284a 100644
--- a/Persistence.IntegrationTests/Extensions/EFCoreExtensions.cs
+++ b/Persistence.IntegrationTests/Extensions/EFCoreExtensions.cs
@@ -4,11 +4,11 @@ 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();
- }
+ 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 7b12362..0092c06 100644
--- a/Persistence.IntegrationTests/WebAppFactoryFixture.cs
+++ b/Persistence.IntegrationTests/WebAppFactoryFixture.cs
@@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Persistence.API;
-using Persistence.Database;
using Persistence.Client;
using Persistence.Database.Model;
using Persistence.Database.Postgres;
@@ -17,32 +16,32 @@ 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)
services.Remove(descriptor);
- services.AddDbContext(options =>
+ services.AddDbContext(options =>
options.UseNpgsql(connectionString));
- services.RemoveAll();
- services.AddSingleton(provider =>
- {
- return new TestHttpClientFactory(this);
- });
+ services.RemoveAll();
+ services.AddSingleton(provider =>
+ {
+ return new TestHttpClientFactory(this);
+ });
services.AddSingleton();
- var serviceProvider = services.BuildServiceProvider();
+ var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var scopedServices = scope.ServiceProvider;
@@ -50,7 +49,7 @@ public class WebAppFactoryFixture : WebApplicationFactory
var dbContext = scopedServices.GetRequiredService();
dbContext.Database.EnsureCreatedAndMigrated();
dbContext.SaveChanges();
- });
+ });
}
public override async ValueTask DisposeAsync()
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/Data/DataSaubDto.cs b/Persistence.Repository/Data/DataSaubDto.cs
index 518380b..3cd0344 100644
--- a/Persistence.Repository/Data/DataSaubDto.cs
+++ b/Persistence.Repository/Data/DataSaubDto.cs
@@ -1,5 +1,4 @@
using Persistence.Models;
-using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Repository.Data;
public class DataSaubDto : ITimeSeriesAbstractDto
diff --git a/Persistence.Repository/DependencyInjection.cs b/Persistence.Repository/DependencyInjection.cs
index e353d30..e61d126 100644
--- a/Persistence.Repository/DependencyInjection.cs
+++ b/Persistence.Repository/DependencyInjection.cs
@@ -19,7 +19,7 @@ public static class DependencyInjection
services.AddTransient();
services.AddTransient, TimeSeriesDataCachedRepository>();
services.AddTransient();
- services.AddTransient();
+ services.AddTransient();
return services;
}
diff --git a/Persistence.Repository/Extensions/EFExtensionsSortBy.cs b/Persistence.Repository/Extensions/EFExtensionsSortBy.cs
index 03b9c65..e2bbee8 100644
--- a/Persistence.Repository/Extensions/EFExtensionsSortBy.cs
+++ b/Persistence.Repository/Extensions/EFExtensionsSortBy.cs
@@ -261,7 +261,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/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