Merge branch 'master' into DataSourceSystem

This commit is contained in:
Roman Efremov 2024-12-13 09:51:30 +05:00
commit 1d40edb535
95 changed files with 1734 additions and 1614 deletions

273
.editorconfig Normal file
View File

@ -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

View File

@ -12,7 +12,7 @@ namespace Persistence.API.Controllers;
[Route("api/[controller]")]
public class ChangeLogController : ControllerBase, IChangeLogApi
{
private IChangeLogRepository repository;
private readonly IChangeLogRepository repository;
public ChangeLogController(IChangeLogRepository repository)
{

View File

@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using Persistence.Repository.Data;
namespace Persistence.API.Controllers;

View File

@ -1,8 +1,8 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;

View File

@ -1,14 +1,14 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с состояниями систем автобурения (АБ)
/// Работа с технологическими сообщениями систем автобурения (АБ)
/// </summary>
[ApiController]
[Authorize]
@ -16,7 +16,7 @@ namespace Persistence.API.Controllers;
public class TechMessagesController : ControllerBase
{
private readonly ITechMessagesRepository techMessagesRepository;
private static readonly Dictionary<int, string> categories = new Dictionary<int, string>()
private static readonly Dictionary<int, string> categories = new()
{
{ 0, "System" },
{ 1, "Авария" },

View File

@ -11,7 +11,7 @@ namespace Persistence.API.Controllers;
public class TimeSeriesController<TDto> : ControllerBase, ITimeSeriesDataApi<TDto>
where TDto : class, ITimeSeriesAbstractDto, new()
{
private ITimeSeriesDataRepository<TDto> timeSeriesDataRepository;
private readonly ITimeSeriesDataRepository<TDto> timeSeriesDataRepository;
public TimeSeriesController(ITimeSeriesDataRepository<TDto> timeSeriesDataRepository)
{
@ -33,7 +33,7 @@ public class TimeSeriesController<TDto> : ControllerBase, ITimeSeriesDataApi<TDt
}
/// <summary>
/// Получить диапазон дат, для которых есть данные в репозиторие
/// Получить диапазон дат, для которых есть данные в репозитории
/// </summary>
/// <param name="token"></param>
/// <returns></returns>

View File

@ -1,8 +1,8 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Services.Interfaces;
using System.Net;
namespace Persistence.API.Controllers;

View File

@ -30,12 +30,11 @@ public static class DependencyInjection
c.MapType<DateOnly>(() => new OpenApiSchema { Type = "string", Format = "date" });
c.MapType<JsonValue>(() => new OpenApiSchema
{
AnyOf = new OpenApiSchema[]
{
AnyOf = [
new OpenApiSchema {Type = "string", Format = "string" },
new OpenApiSchema {Type = "number", Format = "int32" },
new OpenApiSchema {Type = "number", Format = "float" },
}
new OpenApiSchema {Type = "number", Format = "float" }
]
});
c.CustomOperationIds(e =>
@ -47,8 +46,8 @@ public static class DependencyInjection
var needUseKeyCloak = configuration.GetSection("NeedUseKeyCloak").Get<bool>();
if (needUseKeyCloak)
c.AddKeycloackSecurity(configuration);
else c.AddDefaultSecurity(configuration);
c.AddKeycloakSecurity(configuration);
else c.AddDefaultSecurity();
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
@ -108,7 +107,7 @@ public static class DependencyInjection
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Headers["Authorization"]
var accessToken = context.Request.Headers.Authorization
.ToString()
.Replace(JwtBearerDefaults.AuthenticationScheme, string.Empty)
.Trim();
@ -141,12 +140,12 @@ public static class DependencyInjection
}
#endregion
#region Security (Swagger)
private static void AddKeycloackSecurity(this SwaggerGenOptions options, IConfiguration configuration)
#region Keycloak
private static void AddKeycloakSecurity(this SwaggerGenOptions options, IConfiguration configuration)
{
options.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme
options.AddSecurityDefinition("Keycloak", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345token'",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.OAuth2,
@ -167,7 +166,7 @@ public static class DependencyInjection
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Keycloack"
Id = "Keycloak"
},
Scheme = "Bearer",
Name = "Bearer",
@ -178,11 +177,11 @@ public static class DependencyInjection
});
}
private static void AddDefaultSecurity(this SwaggerGenOptions options, IConfiguration configuration)
private static void AddDefaultSecurity(this SwaggerGenOptions options)
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345token'",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,

View File

@ -7,18 +7,15 @@ public static class Extensions
{
public static T GetUserId<T>(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
ArgumentNullException.ThrowIfNull(principal, nameof(principal));
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (String.IsNullOrEmpty(loggedInUserId))
throw new ArgumentNullException(nameof(loggedInUserId));
ArgumentNullException.ThrowIfNullOrEmpty(loggedInUserId, nameof(loggedInUserId));
var result = TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(loggedInUserId);
if (result is null)
throw new ArgumentNullException(nameof(result));
ArgumentNullException.ThrowIfNull(result, nameof(result));
return (T)result;

View File

@ -9,6 +9,11 @@
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.11" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.2.1" />

View File

@ -1,6 +0,0 @@
@Persistence.API_HostAddress = http://localhost:5032
GET {{Persistence.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -1,6 +1,3 @@
using Persistence.Models;
namespace Persistence.API;
public class Program

View File

@ -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;

View File

@ -1,4 +1,4 @@
using Persistence.Models;
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;

View File

@ -1,11 +1,11 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Persistence.Models.Configurations;
using RestSharp;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
namespace Persistence.Client.Helpers;
public static class ApiTokenHelper
@ -68,10 +68,10 @@ public static class ApiTokenHelper
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 keycloakResponse = restClient.Post(request);
if (keycloakResponse.IsSuccessful && !String.IsNullOrEmpty(keycloakResponse.Content))
{
var token = JsonSerializer.Deserialize<JwtToken>(keyCloackResponse.Content)!;
var token = JsonSerializer.Deserialize<JwtToken>(keycloakResponse.Content)!;
return token.AccessToken;
}

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
@ -38,6 +38,11 @@
<PackageReadmeFile>Readme.md</PackageReadmeFile>
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<None Include="Readme.md" Pack="true" PackagePath="\"/>
</ItemGroup>

View File

@ -1,4 +1,3 @@
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients;
@ -8,6 +7,7 @@ using Persistence.Factories;
using Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
namespace Persistence.Client
{

View File

@ -1,7 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
namespace Persistence.Database.Model;

View File

@ -12,12 +12,14 @@ public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<Persistenc
{
public PersistencePostgresContext CreateDbContext(string[] args)
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder();
connectionStringBuilder.Host = "localhost";
connectionStringBuilder.Database = "persistence";
connectionStringBuilder.Username = "postgres";
connectionStringBuilder.Password = "q";
connectionStringBuilder.PersistSecurityInfo = true;
var connectionStringBuilder = new NpgsqlConnectionStringBuilder
{
Host = "localhost",
Database = "persistence",
Username = "postgres",
Password = "q",
PersistSecurityInfo = true
};
var connectionString = connectionStringBuilder.ToString();
var optionsBuilder = new DbContextOptionsBuilder<PersistencePostgresContext>();

View File

@ -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

View File

@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable

View File

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable

View File

@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable

View File

@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable

View File

@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
namespace Persistence.Database.Model;

View File

@ -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;

View File

@ -1,8 +1,8 @@

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Persistence.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model;

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model;

View File

@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
public class DataSourceSystem

View File

@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Persistence.Database.Entity;

View File

@ -1,5 +1,5 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model
{

View File

@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity
{

View File

@ -1,12 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Database;
using Persistence.Database.Model;
using Xunit;
namespace Persistence.IntegrationTests;
public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>,
IDisposable
public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>, IDisposable
{
protected readonly IServiceScope scope;
@ -23,5 +21,6 @@ public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>,
{
scope.Dispose();
dbContext.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@ -13,7 +13,7 @@ namespace Persistence.IntegrationTests.Controllers;
public class ChangeLogControllerTest : BaseIntegrationTest
{
private readonly IChangeLogClient client;
private static Random generatorRandomDigits = new Random();
private static readonly Random generatorRandomDigits = new();
public ChangeLogControllerTest(WebAppFactoryFixture factory) : base(factory)
{
@ -30,7 +30,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
dbContext.CleanupDbSet<ChangeLog>();
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(2, DateTimeOffset.UtcNow);
var dtos = Generate(2);
// act
var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken());
@ -61,7 +61,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
// arrange
var count = 1;
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(count, DateTimeOffset.UtcNow);
var dtos = Generate(count);
var dto = dtos.FirstOrDefault()!;
// act
@ -77,7 +77,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
// arrange
var count = 3;
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(count, DateTimeOffset.UtcNow);
var dtos = Generate(count);
// act
var result = await client.AddRange(idDiscriminator, dtos, new CancellationToken());
@ -93,7 +93,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
dbContext.CleanupDbSet<ChangeLog>();
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(1, DateTimeOffset.UtcNow);
var dtos = Generate(1);
var dto = dtos.FirstOrDefault()!;
var result = await client.Add(idDiscriminator, dto, new CancellationToken());
@ -101,7 +101,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
.Where(x => x.IdDiscriminator == idDiscriminator)
.FirstOrDefault();
dto = entity.Adapt<DataWithWellDepthAndSectionDto>();
dto.DepthEnd = dto.DepthEnd + 10;
dto.DepthEnd += 10;
// act
result = await client.Update(dto, new CancellationToken());
@ -138,7 +138,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
{
// arrange
var count = 2;
var dtos = Generate(count, DateTimeOffset.UtcNow);
var dtos = Generate(count);
var entities = dtos.Select(d => d.Adapt<ChangeLog>()).ToArray();
dbContext.ChangeLog.AddRange(entities);
dbContext.SaveChanges();
@ -163,7 +163,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
public async Task Delete_returns_success()
{
// arrange
var dtos = Generate(1, DateTimeOffset.UtcNow);
var dtos = Generate(1);
var dto = dtos.FirstOrDefault()!;
var entity = dto.Adapt<ChangeLog>();
dbContext.ChangeLog.Add(entity);
@ -181,7 +181,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
{
// arrange
var count = 10;
var dtos = Generate(count, DateTimeOffset.UtcNow);
var dtos = Generate(count);
var entities = dtos.Select(d => d.Adapt<ChangeLog>()).ToArray();
dbContext.ChangeLog.AddRange(entities);
dbContext.SaveChanges();
@ -288,7 +288,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
foreach (var entity in entities)
{
entity.DepthEnd = entity.DepthEnd + 10;
entity.DepthEnd += 10;
}
var dtos = entities.Select(e => e.Adapt<DataWithWellDepthAndSectionDto>()).ToArray();
await client.UpdateRange(dtos, new CancellationToken());
@ -304,7 +304,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
}
private static IEnumerable<DataWithWellDepthAndSectionDto> Generate(int count, DateTimeOffset from)
private static IEnumerable<DataWithWellDepthAndSectionDto> Generate(int count)
{
for (int i = 0; i < count; i++)
yield return new DataWithWellDepthAndSectionDto()
@ -326,8 +326,8 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var minDayCount = daysRange.Item1;
var maxDayCount = daysRange.Item2;
var idDiscriminator = Guid.NewGuid();
var dtos = Generate(count, DateTimeOffset.UtcNow);
Guid idDiscriminator = Guid.NewGuid();
var dtos = Generate(count);
var entities = dtos.Select(d =>
{
var entity = d.Adapt<ChangeLog>();

View File

@ -1,12 +1,11 @@
using Persistence.Client;
using Persistence.Database.Model;
using Persistence.Repository.Data;
using Persistence.Database.Model;
using Persistence.Models;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;
public class DataSaubControllerTest : TimeSeriesBaseControllerTest<DataSaub, DataSaubDto>
{
private readonly DataSaubDto dto = new DataSaubDto()
private readonly DataSaubDto dto = new()
{
AxialLoad = 1,
BitDepth = 2,
@ -29,7 +28,7 @@ public class DataSaubControllerTest : TimeSeriesBaseControllerTest<DataSaub, Dat
WellDepth = 18,
};
private readonly DataSaub entity = new DataSaub()
private readonly DataSaub entity = new()
{
AxialLoad = 1,
BitDepth = 2,

View File

@ -1,18 +1,19 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Model;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers
{
public class SetpointControllerTest : BaseIntegrationTest
{
private ISetpointClient setpointClient;
private readonly ISetpointClient setpointClient;
private class TestObject
{
public string? value1 { get; set; }
public int? value2 { get; set; }
public string? Value1 { get; set; }
public int? Value2 { get; set; }
}
public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory)
{
@ -213,8 +214,8 @@ namespace Persistence.IntegrationTests.Controllers
var setpointKey = Guid.NewGuid();
var setpointValue = new TestObject()
{
value1 = "1",
value2 = 2
Value1 = "1",
Value2 = 2
};
//act

View File

@ -6,6 +6,7 @@ using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Enumerations;
using Persistence.Models.Requests;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers

View File

@ -1,17 +1,18 @@
using System.Net;
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Model;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;
public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrationTest
where TEntity : class, ITimestampedData, new()
where TDto : class, new()
{
private ITimeSeriesClient<TDto> timeSeriesClient;
private readonly ITimeSeriesClient<TDto> timeSeriesClient;
public TimeSeriesBaseControllerTest(WebAppFactoryFixture factory) : base(factory)
{
@ -100,7 +101,7 @@ public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrat
//assert
Assert.NotNull(response);
var ratio = entities.Count() / approxPointsCount;
var ratio = entities.Count / approxPointsCount;
if (ratio > 1)
{
var expectedResampledCount = entities

View File

@ -1,4 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Models;
@ -25,7 +25,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
IEnumerable<TimestampedSetDto> testSets = Generate(10, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
// act
var response = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
var response = await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
// assert
Assert.Equal(testSets.Count(), response);
@ -38,10 +38,10 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Guid idDiscriminator = Guid.NewGuid();
int count = 10;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
// act
var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue, new CancellationToken());
var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue, CancellationToken.None);
// assert
Assert.NotNull(response);
@ -55,7 +55,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Guid idDiscriminator = Guid.NewGuid();
int count = 10;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
string[] props = ["A"];
// act
@ -81,14 +81,14 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
var dateMin = DateTimeOffset.Now;
var dateMax = DateTimeOffset.Now.AddSeconds(count);
IEnumerable<TimestampedSetDto> testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
var insertResponse = await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
var tail = testSets.OrderBy(t => t.Timestamp).Skip(count / 2).Take(int.MaxValue);
var geDate = tail.First().Timestamp;
var tolerance = TimeSpan.FromSeconds(1);
var expectedCount = tail.Count();
// act
var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue, new CancellationToken());
var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue, CancellationToken.None);
// assert
Assert.NotNull(response);
@ -104,7 +104,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Guid idDiscriminator = Guid.NewGuid();
int count = 10;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
var expectedCount = count / 2;
// act
@ -124,7 +124,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
var expectedCount = 1;
int count = 10 + expectedCount;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
// act
var response = await client.Get(idDiscriminator, null, null, count - expectedCount, count, new CancellationToken());
@ -141,7 +141,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Guid idDiscriminator = Guid.NewGuid();
int count = 10;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
var expectedCount = 8;
// act
@ -161,7 +161,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
var dateMin = DateTimeOffset.Now;
var dateMax = DateTimeOffset.Now.AddSeconds(count - 1);
IEnumerable<TimestampedSetDto> testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
var tolerance = TimeSpan.FromSeconds(1);
// act
@ -180,7 +180,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest
Guid idDiscriminator = Guid.NewGuid();
int count = 144;
IEnumerable<TimestampedSetDto> testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7)));
var insertResponse = await client.AddRange(idDiscriminator, testSets, new CancellationToken());
await client.AddRange(idDiscriminator, testSets, CancellationToken.None);
// act
var response = await client.Count(idDiscriminator, new CancellationToken());

View File

@ -1,9 +1,10 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;

View File

@ -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!;

View File

@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using Persistence.Database.Model;
namespace Persistence.IntegrationTests;
public static class EFCoreExtensions

View File

@ -1,15 +0,0 @@
using Persistence.Database;
using Persistence.Database.Model;
namespace Persistence.IntegrationTests.Extensions;
public static class EFCoreExtensions
{
public static void CleanupDbSet<T>(this PersistenceDbContext dbContext)
where T : class
{
var dbset = dbContext.Set<T>();
dbset.RemoveRange(dbset);
dbContext.SaveChanges();
}
}

View File

@ -64,5 +64,7 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
.Options);
await dbContext.Database.EnsureDeletedAsync();
GC.SuppressFinalize(this);
}
}

View File

@ -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;
/// <summary>
@ -134,20 +129,20 @@ public class CyclicArray<T> : IEnumerable<T>
/// <inheritdoc/>
public IEnumerator<T> GetEnumerator()
=> new CyclycListEnumerator<T>(array, current, used);
=> new CyclicListEnumerator<T>(array, current, used);
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
class CyclycListEnumerator<Te> : IEnumerator<Te>
class CyclicListEnumerator<Te> : IEnumerator<Te>
{
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);

View File

@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection;
using Persistence.Database.Model;
using Persistence.Models;
using Persistence.Repositories;
using Persistence.Repository.Data;
using Persistence.Repository.Repositories;
namespace Persistence.Repository;

View File

@ -44,7 +44,7 @@ public static class EFExtensionsSortBy
var name = propertyInfo.Name.ToLower();
ParameterExpression arg = Expression.Parameter(type, "x");
MemberExpression property = Expression.Property(arg, propertyInfo.Name);
var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
var selector = Expression.Lambda(property, [arg]);
var typeAccessor = new TypeAccessor
{
KeySelector = selector,
@ -200,7 +200,7 @@ public static class EFExtensionsSortBy
: orderByAscending;
var newQuery = (IOrderedQueryable<TSource>)genericMethod
.Invoke(genericMethod, new object[] { query, lambdaExpression })!;
.Invoke(genericMethod, [query, lambdaExpression])!;
return newQuery;
}
@ -226,7 +226,6 @@ public static class EFExtensionsSortBy
LambdaExpression? lambdaExpression = null;
// TODO: Устранить дублирование кода
if (propertyName.Contains('.'))
{
Type type = rootType;
@ -261,7 +260,7 @@ public static class EFExtensionsSortBy
: orderByAscending;
var newQuery = (IOrderedQueryable<TSource>)genericMethod
.Invoke(genericMethod, new object[] { query, lambdaExpression })!;
.Invoke(genericMethod, [query, lambdaExpression])!;
return newQuery;
}
}

View File

@ -9,7 +9,7 @@ using UuidExtensions;
namespace Persistence.Repository.Repositories;
public class ChangeLogRepository : IChangeLogRepository
{
private DbContext db;
private readonly DbContext db;
public ChangeLogRepository(DbContext db)
{
@ -195,7 +195,7 @@ public class ChangeLogRepository : IChangeLogRepository
return datesOnly;
}
private ChangeLog CreateEntityFromDto(Guid idAuthor, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto)
private static ChangeLog CreateEntityFromDto(Guid idAuthor, Guid idDiscriminator, DataWithWellDepthAndSectionDto dto)
{
var entity = new ChangeLog()
{

View File

@ -1,6 +1,5 @@
using Mapster;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Repositories;

View File

@ -8,7 +8,7 @@ namespace Persistence.Repository.Repositories
{
public class SetpointRepository : ISetpointRepository
{
private DbContext db;
private readonly DbContext db;
public SetpointRepository(DbContext db)
{
this.db = db;

View File

@ -1,4 +1,4 @@
using Mapster;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
@ -6,7 +6,7 @@ using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using Persistence.Repository.Extensions;
using UuidExtensions;
namespace Persistence.Repository.Repositories
{
@ -32,10 +32,10 @@ namespace Persistence.Repository.Repositories
var count = await query.CountAsync(token);
var sort = request.SortSettings != string.Empty
? request.SortSettings
? request.SortSettings!
: nameof(TechMessage.Timestamp);
var entities = await query
.SortBy(request.SortSettings!)
.SortBy(sort)
.Skip(request.Skip)
.Take(request.Take)
.ToArrayAsync(token);

View File

@ -1,6 +1,4 @@
using Mapster;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Microsoft.EntityFrameworkCore;
using Persistence.Database.Model;
using Persistence.Models;
@ -36,7 +34,7 @@ public class TimeSeriesDataCachedRepository<TEntity, TDto> : TimeSeriesDataRepos
public override async Task<IEnumerable<TDto>> GetGtDate(DateTimeOffset dateBegin, CancellationToken token)
{
if (LastData.Count() == 0 || LastData[0].Date > dateBegin)
if (LastData.Count == 0 || LastData[0].Date > dateBegin)
{
var dtos = await base.GetGtDate(dateBegin, token);
return dtos;

View File

@ -9,7 +9,7 @@ public class TimeSeriesDataRepository<TEntity, TDto> : ITimeSeriesDataRepository
where TEntity : class, ITimestampedData, new()
where TDto : class, ITimeSeriesAbstractDto, new()
{
private DbContext db;
private readonly DbContext db;
public TimeSeriesDataRepository(DbContext db)
{

View File

@ -1,5 +1,4 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;

View File

@ -1,45 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace Persistence.API;
/// <summary>
/// Интерфейс для API, предназначенного для работы с элементами справочников
/// </summary>
public interface IDictionaryElementApi<TDto> where TDto : class, new()
{
/// <summary>
/// Получить все данные справочника
/// </summary>
/// <param name="dictionaryKey">ключ справочника</param>
/// <param name="token"></param>
/// <returns></returns>
Task<ActionResult<IEnumerable<TDto>>> Get(Guid dictionaryKey, CancellationToken token);
/// <summary>
/// Добавить элемент в справочник
/// </summary>
/// <param name="dictionaryKey">ключ справочника</param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<ActionResult<Guid>> Add(Guid dictionaryKey, TDto dto, CancellationToken token);
/// <summary>
/// Изменить одну запись
/// </summary>
/// <param name="dictionaryKey">ключ справочника</param>
/// <param name="dictionaryElementKey">ключ элемента в справочнике</param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<ActionResult<Guid>> Update(Guid dictionaryKey, Guid dictionaryElementKey, TDto dto, CancellationToken token);
/// <summary>
/// Удалить одну запись
/// </summary>
/// <param name="dictionaryKey">ключ справочника</param>
/// <param name="dictionaryElementKey">ключ элемента в справочнике</param>
/// <param name="token"></param>
/// <returns></returns>
Task<ActionResult<int>> Delete(Guid dictionaryKey, Guid dictionaryElementKey, CancellationToken token);
}

View File

@ -1,19 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.API;
/// Интерфейс для API, предназначенного для работы с табличными данными
public interface ITableDataApi<TDto, TRequest>
where TDto : class, new()
where TRequest : PaginationRequest
{
/// <summary>
/// Получить страницу списка объектов
/// </summary>
/// <param name="request">параметры фильтрации</param>
/// <param name="token"></param>
/// <returns></returns>
Task<ActionResult<PaginationContainer<TDto>>> GetPage(TRequest request, CancellationToken token);
}

View File

@ -1,5 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
namespace Persistence.API;

View File

@ -1,10 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistence.API;

View File

@ -1,16 +1,11 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Persistence;
public static class EFExtensions
{
struct TypeAcessor
struct TypeAccessor
{
public LambdaExpression KeySelector { get; set; }
public MethodInfo OrderBy { get; set; }
@ -25,7 +20,7 @@ public static class EFExtensions
private static readonly MethodInfo methodThenBy = GetExtOrderMethod("ThenBy");
private static readonly MethodInfo methodThenByDescending = GetExtOrderMethod("ThenByDescending");
private static ConcurrentDictionary<Type, Dictionary<string, TypeAcessor>> TypePropSelectors { get; set; } = new();
private static ConcurrentDictionary<Type, Dictionary<string, TypeAccessor>> TypePropSelectors { get; set; } = new();
private static MethodInfo GetExtOrderMethod(string methodName)
=> typeof(System.Linq.Queryable)
@ -35,17 +30,17 @@ public static class EFExtensions
m.GetParameters().Length == 2 &&
m.GetParameters()[1].ParameterType.IsAssignableTo(typeof(LambdaExpression)))
.Single();
private static Dictionary<string, TypeAcessor> MakeTypeAcessors(Type type)
private static Dictionary<string, TypeAccessor> MakeTypeAccessors(Type type)
{
var propContainer = new Dictionary<string, TypeAcessor>();
var propContainer = new Dictionary<string, TypeAccessor>();
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
var name = propertyInfo.Name.ToLower();
ParameterExpression arg = Expression.Parameter(type, "x");
MemberExpression property = Expression.Property(arg, propertyInfo.Name);
var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
var typeAccessor = new TypeAcessor
var selector = Expression.Lambda(property, [arg]);
var typeAccessor = new TypeAccessor
{
KeySelector = selector,
OrderBy = methodOrderBy.MakeGenericMethod(type, propertyInfo.PropertyType),
@ -99,16 +94,16 @@ public static class EFExtensions
string propertyName,
bool isDesc)
{
var typePropSelector = TypePropSelectors.GetOrAdd(typeof(TSource), MakeTypeAcessors);
var propertyNamelower = propertyName.ToLower();
var typeAccessor = typePropSelector[propertyNamelower];
var typePropSelector = TypePropSelectors.GetOrAdd(typeof(TSource), MakeTypeAccessors);
var propertyNameLower = propertyName.ToLower();
var typeAccessor = typePropSelector[propertyNameLower];
var genericMethod = isDesc
? typeAccessor.OrderByDescending
: typeAccessor.OrderBy;
var newQuery = (IOrderedQueryable<TSource>)genericMethod
.Invoke(genericMethod, new object[] { query, typeAccessor.KeySelector })!;
.Invoke(genericMethod, [query, typeAccessor.KeySelector])!;
return newQuery;
}
}

View File

@ -1,5 +1,5 @@
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Persistence.Models.Configurations
{

View File

@ -1,7 +1,4 @@
using Persistence.Models;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Repository.Data;
namespace Persistence.Models;
public class DataSaubDto : ITimeSeriesAbstractDto
{
public DateTimeOffset Date { get; set; } = DateTimeOffset.UtcNow;

View File

@ -1,4 +1,4 @@
namespace Persistence.Models;
namespace Persistence.Models;
/// <summary>
/// Модель системы

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistence.Models;
namespace Persistence.Models;
/// <summary>
/// Dto для хранения записей, содержащих начальную и конечную глубину забоя, а также секцию

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistence.Models;
namespace Persistence.Models;
/// <summary>
/// Диапазон дат

View File

@ -11,7 +11,7 @@ public class PaginationContainer<T>
/// </summary>
public PaginationContainer()
{
Items = Enumerable.Empty<T>();
Items = [];
}
/// <summary>

View File

@ -1,4 +1,4 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using Persistence.Models.Enumerations;
namespace Persistence.Models

View File

@ -1,63 +0,0 @@
namespace Persistence.Models;
/// <summary>
/// Модель, описывающая пользователя
/// </summary>
public class UserDto
{
/// <inheritdoc/>
public int Id { get; set; }
/// <summary>
/// логин
/// </summary>
public string Login { get; set; } = null!;
/// <summary>
/// Имя
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Фамилия
/// </summary>
public string? Surname { get; set; }
/// <summary>
/// Отчество
/// </summary>
public string? Patronymic { get; set; }
/// <summary>
/// Email
/// </summary>
public string Email { get; set; } = null!;
/// <summary>
/// Phone
/// </summary>
public string? Phone { get; set; }
/// <summary>
/// Должность
/// </summary>
public string? Position { get; set; }
/// <summary>
/// Id компании
/// </summary>
public int IdCompany { get; set; }
/// <summary>
/// Id состояния пользователя
/// 0 - не активен,
/// 1 - активен,
/// 2 - заблокирован
/// </summary>
public short IdState { get; set; }
/// <summary>
/// Получение отображаемого имени
/// </summary>
/// <returns></returns>
}

View File

@ -1,6 +1,4 @@
using System.ComponentModel.DataAnnotations;
namespace Persistence.Models;
namespace Persistence.Models;
/// <summary>
/// Группа параметров Wits

View File

@ -1,4 +1,3 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
namespace Persistence.Repositories;

View File

@ -1,19 +0,0 @@
using Persistence.Models.Requests;
namespace Persistence.Repositories;
/// <summary>
/// Интерфейс по работе с табличными данными
/// </summary>
public interface ITableDataRepository<TDto, TRequest>
where TDto : class, new()
where TRequest : PaginationRequest
{
/// <summary>
/// Получить страницу списка объектов
/// </summary>
/// <param name="request">параметры фильтрации</param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<TDto>> Get(TRequest request, CancellationToken token);
}

View File

@ -1,6 +1,4 @@
using Persistence.Models;
namespace Persistence.Repositories;
namespace Persistence.Repositories;
/// <summary>
/// Интерфейс по работе с прореженными данными

View File

@ -1,5 +0,0 @@
namespace Persistence.Services.Interfaces;
public interface ITimeSeriesDataObserverService
{
}

View File

@ -1,4 +0,0 @@
namespace Persistence.Services.Interfaces;
public abstract class TimeSeriesDataObserverService : ITimeSeriesDataObserverService
{
}

View File

@ -1,12 +1,11 @@
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Persistence.Models;
using Persistence.Repositories;
using Persistence.Services.Interfaces;
using Persistence.Models;
using Persistence.Models.Configurations;
using Persistence.Models.Enumerations;
using Persistence.Repositories;
using Persistence.Services.Interfaces;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Persistence.Services;
public class WitsDataService : IWitsDataService

78
exclusion.dic Normal file
View File

@ -0,0 +1,78 @@
appsettings
autohold
Autostart
dd
dtos
HH
Impl
MM
mmss
modbus
noload
Saub
Toolface
yyyy
Автоудержание
макрооперации
Макрооперация
расхаживаний
расхаживания
Соотв
Noload
updatables
штропа
страгивания
updatables
MM
dd
HH
mmss
sqlite
Serializer
Auth
Saub
lightgray
appsettings
AutoScale
Hmmss
pinger
Desc
qwertyuiopasdfghjklzxcvbnm
Deserialize
Deserializer
Deserializers
Impl
Protobuf
сериализацию
param
tcpclient
tcpserver
tcplistener
serialport
bigendianunicode
Middlewares
Referer
бекапов
Encoderless
Безэнкодерный
безэнкодерного
энкодеру
автоудержания
дифф
энкодера
Коэфф
Миним
Проворот
вспом
Extrem
выкл
minidisplay
oauth
sbin
прога
yyyyMMdd_HHmmssfff
Serializers
keycloak
Params
Mapster
dest