Merge branch 'master' of ssh://git.ddrilling.ru:2221/on.nemtina/persistence
All checks were successful
Unit tests / test (push) Successful in 2m33s

This commit is contained in:
Olga Nemt 2024-12-23 16:51:31 +05:00
commit 234fc2fc74
173 changed files with 1320 additions and 1742 deletions

View File

@ -0,0 +1,38 @@
name: Unit tests
run-name: ${{ gitea.actor }} is testing
on: push
jobs:
test:
runs-on: ubuntu-latest
container: node
# Service containers to run with `runner-job`
services:
# Label used to access the service container
postgres:
# Docker Hub image
image: postgres
# Provide the password for postgres
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps tcp port 5432 on service container to the host
- 5442:5432
steps:
- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Check out repository code
uses: actions/checkout@v4
- name: Run integration tests
run: dotnet test DD.Persistence.IntegrationTests

View File

@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using DD.Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
[ApiController]
[Authorize]

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с временными данными

View File

@ -1,10 +1,10 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с системами

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с уставками

View File

@ -1,11 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using DD.Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с технологическими сообщениями систем автобурения (АБ)

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
[ApiController]
[Authorize]

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using System.Net;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Хранение наборов данных с отметкой времени.

View File

@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Services.Interfaces;
using DD.Persistence.Models;
using DD.Persistence.Services.Interfaces;
using System.Net;
namespace Persistence.API.Controllers;
namespace DD.Persistence.API.Controllers;
/// <summary>
/// Работа с параметрами Wits

View File

@ -1,17 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<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>
<OutputType>Library</OutputType>
</PropertyGroup>
<ItemGroup>
@ -22,9 +23,10 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence.Database.Postgres\Persistence.Database.Postgres.csproj" />
<ProjectReference Include="..\Persistence.Repository\Persistence.Repository.csproj" />
<ProjectReference Include="..\Persistence\Persistence.csproj" />
<ProjectReference Include="..\DD.Persistence.Database.Postgres\DD.Persistence.Database.Postgres.csproj" />
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
<ProjectReference Include="..\DD.Persistence.Repository\DD.Persistence.Repository.csproj" />
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -3,25 +3,25 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Configurations;
using Persistence.Services;
using Persistence.Services.Interfaces;
using DD.Persistence.Models;
using DD.Persistence.Models.Configurations;
using DD.Persistence.Services;
using DD.Persistence.Services.Interfaces;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using System.Text.Json.Nodes;
using DD.Persistence.Database.Entity;
namespace Persistence.API;
namespace DD.Persistence.API;
public static class DependencyInjection
{
public static void MapsterSetup()
{
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<TechMessageDto, TechMessage>()
.Ignore(dest => dest.System, dest => dest.SystemId);
}
//public static void MapsterSetup()
//{
// TypeAdapterConfig.GlobalSettings.Default.Config
// .ForType<TechMessageDto, TechMessage>()
// .Ignore(dest => dest.System, dest => dest.SystemId);
//}
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
{
services.AddSwaggerGen(c =>
@ -74,15 +74,16 @@ public static class DependencyInjection
private static void AddKeyCloakAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var keyCloakHost = configuration["KeyCloakAuthentication:Host"];
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Audience = configuration["Authentication:Audience"];
options.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
options.Audience = configuration["KeyCloakAuthentication:Audience"];
options.MetadataAddress = $"{keyCloakHost}/.well-known/openid-configuration";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = configuration["Authentication:ValidIssuer"],
ValidIssuer = keyCloakHost
};
});
}
@ -143,6 +144,8 @@ public static class DependencyInjection
#region Keycloak
private static void AddKeycloakSecurity(this SwaggerGenOptions options, IConfiguration configuration)
{
var keyCloakHost = configuration["KeyCloakAuthentication:Host"];
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 12345token'",
@ -153,7 +156,7 @@ public static class DependencyInjection
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]!),
AuthorizationUrl = new Uri($"{keyCloakHost}/protocol/openid-connect/auth"),
}
}
});

View File

@ -1,7 +1,7 @@
using System.ComponentModel;
using System.Security.Claims;
namespace Persistence.API;
namespace DD.Persistence.API;
public static class Extensions
{

View File

@ -1,8 +1,8 @@
using Persistence.Database.Model;
using Persistence.Database.Postgres;
using Persistence.Repository;
using DD.Persistence.Database.Model;
using DD.Persistence.Database.Postgres;
using DD.Persistence.Repository;
namespace Persistence.API;
namespace DD.Persistence.API;
public class Startup
{
@ -27,7 +27,7 @@ public class Startup
services.AddMemoryCache();
services.AddServices();
DependencyInjection.MapsterSetup();
//DependencyInjection.MapsterSetup();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

View File

@ -0,0 +1,5 @@
{
"version": 1,
"isRoot": true,
"tools": {}
}

View File

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>8dcdcfed-c959-4eef-9891-ae60b1b136ea</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<_WebToolingArtifacts Remove="Properties\PublishProfiles\LinuxRelease.pubxml" />
<_WebToolingArtifacts Remove="Properties\PublishProfiles\WindowsRelease.pubxml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.3" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.API\DD.Persistence.API.csproj" />
</ItemGroup>
</Project>

View File

@ -4,21 +4,22 @@ FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["Persistence.API/Persistence.API.csproj", "Persistence.API/"]
RUN dotnet restore "./Persistence.API/Persistence.API.csproj"
COPY ["DD.Persistence.App/DD.Persistence.App.csproj", "DD.Persistence.App/"]
RUN dotnet restore "./DD.Persistence.App/DD.Persistence.App.csproj"
COPY . .
WORKDIR "/src/Persistence.API"
RUN dotnet build "./Persistence.API.csproj" -c $BUILD_CONFIGURATION -o /app/build
WORKDIR "/src/DD.Persistence.App"
RUN dotnet build "./DD.Persistence.App.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Persistence.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
RUN dotnet publish "./DD.Persistence.App.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Persistence.API.dll"]
ENTRYPOINT ["dotnet", "DD.Persistence.App.dll"]

View File

@ -1,10 +1,15 @@
namespace Persistence.API;
using DD.Persistence.API;
using System.Globalization;
namespace DD.Persistence.App;
public class Program
{
public static void Main(string[] args)
{
CultureInfo uiCulture = CultureInfo.CurrentUICulture;
CultureInfo.CurrentUICulture = new CultureInfo("en-EN");
var host = CreateHostBuilder(args).Build();
Startup.BeforeRunHandler(host);
host.Run();

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<ProjectGuid>063238bf-e982-43fa-9ddb-7d7d279086d8</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>063238bf-e982-43fa-9ddb-7d7d279086d8</ProjectGuid>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,52 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5266"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7154;http://localhost:5266"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:54958",
"sslPort": 44352
}
}
}

View File

@ -0,0 +1,29 @@
# DD.Persistence.App Readme
## Краткое описание DD.Persistence.App сервиса
DD.Persistence.App - проект исполняемого файла микросервиса
## Настройка DD.Persistence.App (файл appsettings.json)
- `appsettings.json` - файл с настройками проекта.
### Подключение к БД
- Настройки подключения к базе хранятся в свойстве `DefaultConnection` секции `ConnectionStrings`
файла `appsettings.json`, где:
- Host - название или ip хоста;
- Database - название базы данных;
- Username - пользователь базы данных;
- Password - пароль базы данных;
- Больше информации о настройке подключения к postgreSQL можно прочесть по [ссылке](https://www.npgsql.org/doc/connection-string-parameters.html)
### Авторизация
1. В проекте предусмотрены 2 типа авторизации:
- Авторизация через KeyCloak. Используется в продакшен версии.
- Авторизация через Jwt-токен. Используется для разработки и тестирования.
2. Для включения авторизации через KeyCloak необходимо:
- Установить секцию `NeedUseKeyCloak` файла `appsettings.json` в `true`
- По необходимости настроить свойства секции `Authentication` файла `appsettings.json`
### defaultsettings.json
Копия файла `appsettings.json` хранится в файле `defaultsettings.json`

View File

@ -0,0 +1,17 @@
{
"DbConnection": {
"Host": "postgres",
"Port": 5432,
"Database": "persistence",
"Username": "postgres",
"Password": "postgres"
},
"NeedUseKeyCloak": false,
"AuthUser": {
"username": "myuser",
"password": 12345,
"clientId": "webapi",
"grantType": "password"
},
"KeycloakGetTokenUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/token"
}

View File

@ -0,0 +1,24 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=persistence;Username=postgres;Password=postgres;Persist Security Info=True"
},
"AllowedHosts": "*",
"NeedUseKeyCloak": false,
"KeyCloakAuthentication": {
"Audience": "account",
"Host": "http://192.168.0.10:8321/realms/Persistence"
},
"AuthUser": {
"username": "myuser",
"password": 12345,
"clientId": "webapi",
"grantType": "password",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "7d9f3574-6574-4ca3-845a-0276eb4aa8f6"
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"NeedUseKeyCloak": false
}

View File

@ -1,8 +1,8 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Helpers;
using DD.Persistence.Client.Helpers;
using Microsoft.Extensions.Logging;
using Refit;
namespace Persistence.Client.Clients.Base;
namespace DD.Persistence.Client.Clients.Base;
public abstract class BaseClient
{
private readonly ILogger logger;

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class ChangeLogClient : BaseClient, IChangeLogClient
{
private readonly Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient;

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient
{
private readonly IRefitDataSourceSystemClient dataSourceSystemClient;

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с записями ChangeLog

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с системами

View File

@ -1,6 +1,6 @@
using Persistence.Models;
using DD.Persistence.Models;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с уставками

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с технологическими сообщениями

View File

@ -1,6 +1,6 @@
using Persistence.Models;
using DD.Persistence.Models;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с временными данными

View File

@ -1,6 +1,6 @@
using Persistence.Models;
using DD.Persistence.Models;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с репозиторием для хранения разных наборов данных рядов.

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces;
namespace DD.Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с параметрами Wits

View File

@ -1,8 +1,8 @@
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitChangeLogClient : IDisposable
{

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitDataSourceSystemClient : IDisposable
{
private const string BaseRoute = "/api/dataSourceSystem";

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitSetpointClient : IDisposable
{

View File

@ -1,9 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit
namespace DD.Persistence.Client.Clients.Interfaces.Refit
{
public interface IRefitTechMessagesClient : IDisposable
{

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimeSeriesClient<TDto> : IDisposable
where TDto : class, new()
{

View File

@ -1,7 +1,7 @@
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimestampedSetClient : IDisposable
{

View File

@ -1,8 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using DD.Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
namespace DD.Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitWitsDataClient : IDisposable
{
private const string BaseRoute = "/api/witsData";

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class SetpointClient : BaseClient, ISetpointClient
{

View File

@ -1,11 +1,11 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class TechMessagesClient : BaseClient, ITechMessagesClient
{

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where TDto : class, new()
{
private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient;

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class TimestampedSetClient : BaseClient, ITimestampedSetClient
{
private readonly IRefitTimestampedSetClient refitTimestampedSetClient;

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models;
using DD.Persistence.Client.Clients.Base;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Models;
namespace Persistence.Client.Clients;
namespace DD.Persistence.Client.Clients;
public class WitsDataClient : BaseClient, IWitsDataClient
{
private readonly IRefitWitsDataClient refitWitsDataClient;

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Not Acceptable (406)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Bad gateway (502)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Forbidden (403)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Internal Server Error (500)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Locked (423)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Service Unavailable Error (503)

View File

@ -1,4 +1,4 @@
namespace Persistence.Client.CustomExceptions;
namespace DD.Persistence.Client.CustomExceptions;
/// <summary>
/// Too Many Requests (429)

View File

@ -0,0 +1,63 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!--Генерация NuGet пакета при сборке-->
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<!--Наименование-->
<Title>Persistence.Client</Title>
<!--Версия пакета-->
<VersionPrefix>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</VersionPrefix>
<!--Версия сборки-->
<AssemblyVersion>1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH))</AssemblyVersion>
<!--Id пакета-->
<PackageId>Persistence.Client</PackageId>
<!--Автор-->
<Authors>Digital Drilling</Authors>
<!--Компания-->
<Company>Digital Drilling</Company>
<!--Описание-->
<Description>Пакет для получения клиентов для работы с Persistence сервисом</Description>
<!--Url репозитория-->
<RepositoryUrl>https://git.ddrilling.ru/on.nemtina/persistence.git</RepositoryUrl>
<!--тип репозитория-->
<RepositoryType>git</RepositoryType>
<!--Символы отладки-->
<IncludeSymbols>true</IncludeSymbols>
<!--Формат пакета с символами-->
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!--Путь к пакету-->
<PackageOutputPath>C:\Projects\Nuget</PackageOutputPath>
<!--Readme-->
<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>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.2.1" />
<PackageReference Include="Refit" Version="8.0.0" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -1,13 +1,13 @@
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Persistence.Models.Configurations;
using DD.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;
namespace DD.Persistence.Client.Helpers;
public static class ApiTokenHelper
{
public static void Authorize(this HttpClient httpClient, IConfiguration configuration)

View File

@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations;
using Persistence.Client.CustomExceptions;
using DD.Persistence.Client.CustomExceptions;
using Refit;
using System.ComponentModel.DataAnnotations;
namespace Persistence.Client.Helpers;
namespace DD.Persistence.Client.Helpers;
public static class ExceptionsHelper
{
private static readonly Dictionary<System.Net.HttpStatusCode, Exception> ExceptionsDictionary = new Dictionary<System.Net.HttpStatusCode, Exception>()

View File

@ -1,15 +1,15 @@
using Microsoft.Extensions.Configuration;
using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients;
using Persistence.Client.Helpers;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Helpers;
using Refit;
using Persistence.Factories;
using Persistence.Client.Clients.Interfaces.Refit;
using DD.Persistence.Factories;
using DD.Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
namespace Persistence.Client
namespace DD.Persistence.Client
{
/// <summary>
/// Фабрика клиентов для доступа к Persistence - сервису

View File

@ -6,7 +6,7 @@ Persistence сервис отвечает за работу с хранимым
## Описание пакета
Данный пакет предоставляет возможность взаимодействия с
Persistence сервисом посредством обращения к конкретному
клиенту, ответсвенному за работу с одной из областей сервиса.
клиенту, ответственному за работу с одной из областей сервиса.
## Список предоставляемых клиентов
- `ISetpointClient` - Клиент для работы с уставками
@ -31,7 +31,7 @@ Persistence сервисом посредством обращения к кон
4. Обратиться к фабрике Persistence - клиентов и получить требуемого клиента.
## xunit тестирование
При написании интеграционных тестов с ипользованием Persistence - клиентов
При написании интеграционных тестов с использованием Persistence - клиентов
Http - клиент не обязан быть авторизован через передачу токена в `PersistenceClientFactory`.
Для осуществления тестовой авторизации достаточно добавить в `appsettings.Tests.json` :
```json

View File

@ -14,12 +14,12 @@
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.10" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence.Database\Persistence.Database.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
</ItemGroup>
</Project>

View File

@ -2,7 +2,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
public static class DependencyInjection
{

View File

@ -1,9 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Npgsql;
using Persistence.Database.Model;
using DD.Persistence.Database.Model;
namespace Persistence.Database.Postgres;
namespace DD.Persistence.Database.Postgres;
/// <summary>
/// Фабрика контекста для dotnet ef миграций

View File

@ -2,7 +2,7 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Diagnostics;
namespace Persistence.Database.Postgres;
namespace DD.Persistence.Database.Postgres;
public static class EFExtensionsInitialization
{
public static void EnsureCreatedAndMigrated(this DatabaseFacade db)

View File

@ -1,54 +1,52 @@
// <auto-generated />
using System;
using DD.Persistence.Database.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
namespace DD.Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistencePostgresContext))]
[Migration("20241212041758_TechMessageMigration")]
partial class TechMessageMigration
[Migration("20241220062251_Init")]
partial class Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.DataSourceSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id системы автобурения");
.HasComment("Id системы - источника данных");
b.Property<string>("Description")
.HasColumnType("text")
.HasComment("Описание системы автобурения");
.HasComment("Описание системы - источника данных");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Наименование системы автобурения");
.HasComment("Наименование системы - источника данных");
b.HasKey("SystemId");
b.ToTable("DrillingSystem");
b.ToTable("DataSourceSystem");
});
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.ParameterData", b =>
{
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
@ -72,7 +70,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
b.ToTable("ParameterData");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
.ValueGeneratedOnAdd()
@ -107,7 +105,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
b.ToTable("TechMessage");
});
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
@ -130,7 +128,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
});
});
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@ -183,7 +181,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
b.ToTable("ChangeLog");
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
@ -266,7 +264,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
b.ToTable("DataSaub");
});
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
@ -290,9 +288,9 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
b.ToTable("Setpoint");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
b.HasOne("DD.Persistence.Database.Entity.DataSourceSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -0,0 +1,172 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace DD.Persistence.Database.Postgres.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ChangeLog",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ записи"),
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор таблицы"),
IdAuthor = table.Column<Guid>(type: "uuid", nullable: false, comment: "Автор изменения"),
IdEditor = table.Column<Guid>(type: "uuid", nullable: true, comment: "Редактор"),
Creation = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата создания записи"),
Obsolete = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true, comment: "Дата устаревания (например при удалении)"),
IdNext = table.Column<Guid>(type: "uuid", nullable: true, comment: "Id заменяющей записи"),
DepthStart = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина забоя на дату начала интервала"),
DepthEnd = table.Column<double>(type: "double precision", nullable: false, comment: "Глубина забоя на дату окончания интервала"),
IdSection = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ секции"),
Value = table.Column<string>(type: "jsonb", nullable: false, comment: "Значение")
},
constraints: table =>
{
table.PrimaryKey("PK_ChangeLog", x => x.Id);
});
migrationBuilder.CreateTable(
name: "DataSaub",
columns: table => new
{
date = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
mode = table.Column<int>(type: "integer", nullable: true),
user = table.Column<string>(type: "text", nullable: true),
wellDepth = table.Column<double>(type: "double precision", nullable: true),
bitDepth = table.Column<double>(type: "double precision", nullable: true),
blockPosition = table.Column<double>(type: "double precision", nullable: true),
blockSpeed = table.Column<double>(type: "double precision", nullable: true),
pressure = table.Column<double>(type: "double precision", nullable: true),
axialLoad = table.Column<double>(type: "double precision", nullable: true),
hookWeight = table.Column<double>(type: "double precision", nullable: true),
rotorTorque = table.Column<double>(type: "double precision", nullable: true),
rotorSpeed = table.Column<double>(type: "double precision", nullable: true),
flow = table.Column<double>(type: "double precision", nullable: true),
mseState = table.Column<short>(type: "smallint", nullable: false),
idFeedRegulator = table.Column<int>(type: "integer", nullable: false),
mse = table.Column<double>(type: "double precision", nullable: true),
pump0Flow = table.Column<double>(type: "double precision", nullable: true),
pump1Flow = table.Column<double>(type: "double precision", nullable: true),
pump2Flow = table.Column<double>(type: "double precision", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSaub", x => x.date);
});
migrationBuilder.CreateTable(
name: "DataSourceSystem",
columns: table => new
{
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы - источника данных"),
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы - источника данных"),
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы - источника данных")
},
constraints: table =>
{
table.PrimaryKey("PK_DataSourceSystem", x => x.SystemId);
});
migrationBuilder.CreateTable(
name: "ParameterData",
columns: table => new
{
DiscriminatorId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор системы"),
ParameterId = table.Column<int>(type: "integer", nullable: false, comment: "Id параметра"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Временная отметка"),
Value = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Значение параметра в виде строки")
},
constraints: table =>
{
table.PrimaryKey("PK_ParameterData", x => new { x.DiscriminatorId, x.ParameterId, x.Timestamp });
});
migrationBuilder.CreateTable(
name: "Setpoint",
columns: table => new
{
Key = table.Column<Guid>(type: "uuid", nullable: false, comment: "Ключ"),
Created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата создания уставки"),
Value = table.Column<object>(type: "jsonb", nullable: false, comment: "Значение уставки"),
IdUser = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id автора последнего изменения")
},
constraints: table =>
{
table.PrimaryKey("PK_Setpoint", x => new { x.Key, x.Created });
});
migrationBuilder.CreateTable(
name: "TimestampedSets",
columns: table => new
{
IdDiscriminator = table.Column<Guid>(type: "uuid", nullable: false, comment: "Дискриминатор ссылка на тип сохраняемых данных"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Отметка времени, строго в UTC"),
Set = table.Column<string>(type: "jsonb", nullable: false, comment: "Набор сохраняемых данных")
},
constraints: table =>
{
table.PrimaryKey("PK_TimestampedSets", x => new { x.IdDiscriminator, x.Timestamp });
},
comment: "Общая таблица данных временных рядов");
migrationBuilder.CreateTable(
name: "TechMessage",
columns: table => new
{
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
Text = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"),
EventState = table.Column<int>(type: "integer", nullable: false, comment: "Статус события")
},
constraints: table =>
{
table.PrimaryKey("PK_TechMessage", x => x.EventId);
table.ForeignKey(
name: "FK_TechMessage_DataSourceSystem_SystemId",
column: x => x.SystemId,
principalTable: "DataSourceSystem",
principalColumn: "SystemId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_TechMessage_SystemId",
table: "TechMessage",
column: "SystemId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChangeLog");
migrationBuilder.DropTable(
name: "DataSaub");
migrationBuilder.DropTable(
name: "ParameterData");
migrationBuilder.DropTable(
name: "Setpoint");
migrationBuilder.DropTable(
name: "TechMessage");
migrationBuilder.DropTable(
name: "TimestampedSets");
migrationBuilder.DropTable(
name: "DataSourceSystem");
}
}
}

View File

@ -1,14 +1,14 @@
// <auto-generated />
using System;
using DD.Persistence.Database.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
namespace DD.Persistence.Database.Postgres.Migrations
{
[DbContext(typeof(PersistencePostgresContext))]
partial class PersistencePostgresContextModelSnapshot : ModelSnapshot
@ -17,14 +17,12 @@ namespace Persistence.Database.Postgres.Migrations
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Russian_Russia.1251")
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Entity.DataSourceSystem", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.DataSourceSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
@ -45,7 +43,7 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("DataSourceSystem");
});
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.ParameterData", b =>
{
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
@ -69,7 +67,7 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("ParameterData");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
.ValueGeneratedOnAdd()
@ -104,7 +102,7 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("TechMessage");
});
modelBuilder.Entity("Persistence.Database.Entity.TimestampedSet", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TimestampedSet", b =>
{
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
@ -127,7 +125,7 @@ namespace Persistence.Database.Postgres.Migrations
});
});
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
@ -180,7 +178,7 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("ChangeLog");
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")
.HasColumnType("timestamp with time zone")
@ -263,7 +261,7 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("DataSaub");
});
modelBuilder.Entity("Persistence.Database.Model.Setpoint", b =>
modelBuilder.Entity("DD.Persistence.Database.Model.Setpoint", b =>
{
b.Property<Guid>("Key")
.HasColumnType("uuid")
@ -287,9 +285,9 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("Setpoint");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
modelBuilder.Entity("DD.Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("Persistence.Database.Entity.DataSourceSystem", "System")
b.HasOne("DD.Persistence.Database.Entity.DataSourceSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore;
namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
/// <summary>
/// EF êîíòåêñò äëÿ ÁÄ Postgres
@ -13,10 +13,6 @@ public partial class PersistencePostgresContext : PersistenceDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresExtension("adminpack")
.HasAnnotation("Relational:Collation", "Russian_Russia.1251");
base.OnModelCreating(modelBuilder);
}
}

View File

@ -1,11 +1,11 @@
## Создать миграцию
```
dotnet ef migrations add <MigrationName> --project Persistence.Database.Postgres
dotnet ef migrations add <MigrationName> --project DD.Persistence.Database.Postgres
```
## Откатить миграцию
```
dotnet ef migrations remove --project Persistence.Database.Postgres
dotnet ef migrations remove --project DD.Persistence.Database.Postgres
```
Удаляется последняя созданная миграция.

View File

@ -15,7 +15,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence\Persistence.csproj" />
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -2,7 +2,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Persistence.Database;
namespace DD.Persistence.Database;
public static class EFExtensions
{

View File

@ -1,10 +1,10 @@

using Microsoft.EntityFrameworkCore;
using Persistence.Models;
using DD.Persistence.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
/// <summary>
/// Часть записи, описывающая изменение

View File

@ -1,7 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
public class DataSaub : ITimestampedData
{
[Key, Column("date")]

View File

@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
namespace DD.Persistence.Database.Entity;
public class DataSourceSystem
{
[Key, Comment("Id системы - источника данных")]

View File

@ -1,5 +1,5 @@

namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
/// <summary>
/// Часть записи, описывающая изменение

View File

@ -1,4 +1,4 @@
namespace Persistence.Database.Model;
namespace DD.Persistence.Database.Model;
public interface ITimestampedData
{
/// <summary>

View File

@ -2,7 +2,7 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
namespace DD.Persistence.Database.Entity;
[PrimaryKey(nameof(DiscriminatorId), nameof(ParameterId), nameof(Timestamp))]
public class ParameterData

View File

@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Model
namespace DD.Persistence.Database.Model
{
[PrimaryKey(nameof(Key), nameof(Created))]
public class Setpoint

View File

@ -2,7 +2,7 @@ using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity
namespace DD.Persistence.Database.Entity
{
public class TechMessage
{

View File

@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
namespace DD.Persistence.Database.Entity;
[Comment("Общая таблица данных временных рядов")]
[PrimaryKey(nameof(IdDiscriminator), nameof(Timestamp))]

View File

@ -1,8 +1,8 @@
using Microsoft.EntityFrameworkCore;
using Persistence.Database.Entity;
using Persistence.Database.Model;
using DD.Persistence.Database.Entity;
using DD.Persistence.Database.Model;
namespace Persistence.Database;
namespace DD.Persistence.Database;
/// <summary>
/// EF контекст для любых БД поддерживаемых в EF

View File

@ -1,9 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Persistence.Database;
using Persistence.Database.Model;
using DD.Persistence.Database;
using DD.Persistence.Database.Model;
using Xunit;
namespace Persistence.IntegrationTests;
namespace DD.Persistence.IntegrationTests;
public abstract class BaseIntegrationTest : IClassFixture<WebAppFactoryFixture>, IDisposable
{
protected readonly IServiceScope scope;

View File

@ -1,15 +1,14 @@
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Database.Model;
using Persistence.Models;
using Persistence.Models.Requests;
using DD.Persistence.Database.Model;
using DD.Persistence.Models;
using DD.Persistence.Models.Requests;
using Xunit;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client;
namespace Persistence.IntegrationTests.Controllers;
namespace DD.Persistence.IntegrationTests.Controllers;
public class ChangeLogControllerTest : BaseIntegrationTest
{
private readonly IChangeLogClient client;
@ -52,7 +51,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken());
// assert
Assert.Equal(insertedCount*2, result);
Assert.Equal(insertedCount * 2, result);
}
[Fact]

View File

@ -1,8 +1,8 @@
using Persistence.Database.Model;
using Persistence.Models;
using DD.Persistence.Database.Model;
using DD.Persistence.Models;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;
namespace DD.Persistence.IntegrationTests.Controllers;
public class DataSaubControllerTest : TimeSeriesBaseControllerTest<DataSaub, DataSaubDto>
{
private readonly DataSaubDto dto = new()

View File

@ -0,0 +1,82 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using Xunit;
namespace DD.Persistence.IntegrationTests.Controllers
{
public class DataSourceSystemControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly IDataSourceSystemClient dataSourceSystemClient;
private readonly IMemoryCache memoryCache;
public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var scope = factory.Services.CreateScope();
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
dataSourceSystemClient = persistenceClientFactory.GetDataSourceSystemClient();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact]
public async Task Get_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task Get_AfterSave_returns_success()
{
//arrange
await Add();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedSystemCount = 1;
var actualSystemCount = response!.Count();
Assert.Equal(expectedSystemCount, actualSystemCount);
}
[Fact]
public async Task Add_returns_success()
{
await Add();
}
private async Task Add()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
var dto = new DataSourceSystemDto()
{
SystemId = Guid.NewGuid(),
Name = "Test",
Description = "Test"
};
//act
await dataSourceSystemClient.Add(dto, CancellationToken.None);
}
}
}

View File

@ -0,0 +1,227 @@
using Microsoft.Extensions.DependencyInjection;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Model;
using System.Net;
using Xunit;
namespace DD.Persistence.IntegrationTests.Controllers
{
public class SetpointControllerTest : BaseIntegrationTest
{
private readonly ISetpointClient setpointClient;
private class TestObject
{
public string? Value1 { get; set; }
public int? Value2 { get; set; }
}
public SetpointControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var scope = factory.Services.CreateScope();
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
setpointClient = persistenceClientFactory.GetSetpointClient();
}
[Fact]
public async Task GetCurrent_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
//act
var response = await setpointClient.GetCurrent(setpointKeys, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetCurrent_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
//act
var response = await setpointClient.GetCurrent([setpointKey], new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault()?.Key);
}
[Fact]
public async Task GetHistory_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
var historyMoment = DateTimeOffset.UtcNow;
//act
var response = await setpointClient.GetHistory(setpointKeys, historyMoment, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetHistory_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
var historyMoment = DateTimeOffset.UtcNow;
historyMoment = historyMoment.AddDays(1);
//act
var response = await setpointClient.GetHistory([setpointKey], historyMoment, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault()?.Key);
}
[Fact]
public async Task GetLog_returns_success()
{
//arrange
var setpointKeys = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid()
};
//act
var response = await setpointClient.GetLog(setpointKeys, new CancellationToken());
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetLog_AfterSave_returns_success()
{
//arrange
var setpointKey = await Add();
//act
var response = await setpointClient.GetLog([setpointKey], new CancellationToken());
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
Assert.Equal(setpointKey, response.FirstOrDefault().Key);
}
[Fact]
public async Task GetDatesRange_returns_success()
{
//arrange
dbContext.CleanupDbSet<Setpoint>();
//act
var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Equal(DateTimeOffset.MinValue, response!.From);
Assert.Equal(DateTimeOffset.MaxValue, response!.To);
}
[Fact]
public async Task GetDatesRange_AfterSave_returns_success()
{
//arrange
dbContext.CleanupDbSet<Setpoint>();
await Add();
var dateBegin = DateTimeOffset.MinValue;
var take = 1;
var part = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//act
var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedValue = part!
.FirstOrDefault()!.Created
.ToString("dd.MM.yyyy-HH:mm:ss");
var actualValueFrom = response.From
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedValue, actualValueFrom);
var actualValueTo = response.To
.ToString("dd.MM.yyyy-HH:mm:ss");
Assert.Equal(expectedValue, actualValueTo);
}
[Fact]
public async Task GetPart_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 2;
//act
var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetPart_AfterSave_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 1;
await Add();
//act
var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
}
[Fact]
public async Task Save_returns_success()
{
await Add();
}
private async Task<Guid> Add()
{
//arrange
var setpointKey = Guid.NewGuid();
var setpointValue = new TestObject()
{
Value1 = "1",
Value2 = 2
};
//act
await setpointClient.Add(setpointKey, setpointValue, new CancellationToken());
return setpointKey;
}
}
}

View File

@ -1,15 +1,15 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Enumerations;
using Persistence.Models.Requests;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using DD.Persistence.Models.Enumerations;
using DD.Persistence.Models.Requests;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers
namespace DD.Persistence.IntegrationTests.Controllers
{
public class TechMessagesControllerTest : BaseIntegrationTest
{
@ -209,20 +209,20 @@ namespace Persistence.IntegrationTests.Controllers
Assert.NotNull(response?.To);
}
[Fact]
public async Task GetPart_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 2;
// [Fact]
// public async Task GetPart_returns_success()
// {
// //arrange
// var dateBegin = DateTimeOffset.UtcNow;
// var take = 2;
//act
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
// //act
// var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
// //assert
// Assert.NotNull(response);
// Assert.Empty(response);
//}
[Fact]
public async Task GetPart_AfterSave_returns_success()

View File

@ -1,12 +1,12 @@
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Model;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Database.Model;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;
namespace DD.Persistence.IntegrationTests.Controllers;
public abstract class TimeSeriesBaseControllerTest<TEntity, TDto> : BaseIntegrationTest
where TEntity : class, ITimestampedData, new()

View File

@ -1,10 +1,10 @@
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Models;
using DD.Persistence.Client;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Models;
using Xunit;
namespace Persistence.IntegrationTests.Controllers;
namespace DD.Persistence.IntegrationTests.Controllers;
public class TimestampedSetControllerTest : BaseIntegrationTest
{
private readonly ITimestampedSetClient client;

View File

@ -1,13 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Persistence.Client;
using Persistence.Client.Clients;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using DD.Persistence.Database.Entity;
using DD.Persistence.Models;
using System.Net;
using Xunit;
using DD.Persistence.Client.Clients.Interfaces;
using DD.Persistence.Client;
namespace Persistence.IntegrationTests.Controllers;
namespace DD.Persistence.IntegrationTests.Controllers;
public class WitsDataControllerTest : BaseIntegrationTest
{
private IWitsDataClient witsDataClient;

View File

@ -24,9 +24,10 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence.API\Persistence.API.csproj" />
<ProjectReference Include="..\Persistence.Client\Persistence.Client.csproj" />
<ProjectReference Include="..\Persistence.Database.Postgres\Persistence.Database.Postgres.csproj" />
<ProjectReference Include="..\DD.Persistence.App\DD.Persistence.App.csproj" />
<ProjectReference Include="..\DD.Persistence.Client\DD.Persistence.Client.csproj" />
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -1,4 +1,4 @@
namespace Persistence.IntegrationTests;
namespace DD.Persistence.IntegrationTests;
public class DbConnection
{
public string Host { get; set; } = null!;

View File

@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore;
namespace Persistence.IntegrationTests;
namespace DD.Persistence.IntegrationTests;
public static class EFCoreExtensions
{
public static void CleanupDbSet<T>(this DbContext dbContext)

View File

@ -1,4 +1,4 @@
namespace Persistence.IntegrationTests
namespace DD.Persistence.IntegrationTests
{
/// <summary>
/// Фабрика HTTP клиентов для интеграционных тестов

View File

@ -5,14 +5,15 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Persistence.API;
using Persistence.Client;
using Persistence.Database.Model;
using Persistence.Database.Postgres;
using DD.Persistence.API;
using DD.Persistence.Client;
using DD.Persistence.Database.Model;
using DD.Persistence.Database.Postgres;
using RestSharp;
using DD.Persistence.App;
namespace Persistence.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Startup>
namespace DD.Persistence.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Program>
{
private string connectionString = string.Empty;
@ -24,6 +25,7 @@ public class WebAppFactoryFixture : WebApplicationFactory<Startup>
var dbConnection = config.Build().GetSection("DbConnection").Get<DbConnection>()!;
connectionString = dbConnection.GetConnectionString();
//connectionString = "Host=postgres;Port=5442;Username=postgres;Password=postgres;Database=persistence";
});
builder.ConfigureServices(services =>

View File

@ -1,6 +1,6 @@
using System.Collections;
namespace Persistence.Repository;
namespace DD.Persistence.Repository;
/// <summary>
/// Цикличный массив
/// </summary>

View File

@ -12,8 +12,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Persistence.Database\Persistence.Database.csproj" />
<ProjectReference Include="..\Persistence\Persistence.csproj" />
<ProjectReference Include="..\DD.Persistence.Database\DD.Persistence.Database.csproj" />
<ProjectReference Include="..\DD.Persistence\DD.Persistence.csproj" />
</ItemGroup>
</Project>

View File

@ -1,17 +1,22 @@
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Database.Model;
using Persistence.Models;
using Persistence.Repositories;
using Persistence.Repository.Repositories;
using DD.Persistence.Database.Model;
using DD.Persistence.Models;
using DD.Persistence.Repositories;
using DD.Persistence.Repository.Repositories;
using DD.Persistence.Database.Entity;
using System.Reflection;
namespace Persistence.Repository;
namespace DD.Persistence.Repository;
public static class DependencyInjection
{
public static void MapsterSetup()
{
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ChangeLog, ChangeLogDto>()
.ForType<TechMessageDto, TechMessage>()
.Ignore(dest => dest.System, dest => dest.SystemId);
TypeAdapterConfig<ChangeLog, ChangeLogDto>.NewConfig()
.Map(dest => dest.Value, src => new DataWithWellDepthAndSectionDto()
{
DepthEnd = src.DepthEnd,
@ -20,11 +25,14 @@ public static class DependencyInjection
Value = src.Value,
Id = src.Id
});
}
public static IServiceCollection AddInfrastructure(this IServiceCollection services)
{
var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
typeAdapterConfig.RuleMap.Clear();
typeAdapterConfig.Scan(Assembly.GetExecutingAssembly());
MapsterSetup();
services.AddTransient<ITimeSeriesDataRepository<DataSaubDto>, TimeSeriesDataRepository<DataSaub, DataSaubDto>>();

Some files were not shown because too many files have changed in this diff Show More