Подключили библиотеки, настроили логеер, реализовали логику для CLientRepository

This commit is contained in:
Tonb73 2024-11-14 16:13:13 +04:00
parent 083f7761ae
commit 4102f2cb32
6 changed files with 175 additions and 3 deletions

View File

@ -1,34 +1,129 @@
using ProjectTourAgency.Enities;
using Microsoft.Extensions.Logging;
using ProjectTourAgency.Enities;
using ProjectTourAgency.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Dapper;
namespace ProjectTourAgency.Implementations;
public class ClientRepository : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepository> _logger;
public ClientRepository(IConnectionString connectionString, ILogger<ClientRepository> logger )
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {jspn}", JsonConvert.SerializeObject(client));
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Clients (FullName, BirthDate, PhoneNumber, Money)
VALUES (@FullName, @BirthDate, @PhoneNumber, @Money)";
connection.Execute(queryInsert, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteClient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM CLients
WHERE Id = @Id";
connection.Execute(queryDelete, new {id});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при ужалении объекта");
throw;
}
}
public Client ReadClientById(int id)
{
return Client.CreateEntity(0, string.Empty, DateTime.Now, string.Empty, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM CLients
WHERE [Id] = @Id";
var client = connection.QueryFirst<Client>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Client> ReadClients()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM CLients";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateClient(Client client)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE CLients
SET
FullName = @FullName,
BirthDate = @BirthDate,
PhoneNumber = @PhoneNumber,
Money = @Money
WHERE Id = @Id";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редкатировании объекта");
throw;
}
}
}

View File

@ -0,0 +1,13 @@
using ProjectTourAgency.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTourAgency.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "";
}

View File

@ -1,8 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectEmployeeAgency.Repositories;
using ProjectRouteAgency.Repositories;
using ProjectTourAgency.Implementations;
using ProjectTourAgency.Repositories;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectTourAgency
{
@ -24,6 +28,8 @@ namespace ProjectTourAgency
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ITourRepository, TourRepository>();
container.RegisterType<IAddMoneyRepository, AddMoneyRepository>();
container.RegisterType<IClientRepository, ClientRepository>();
@ -31,7 +37,21 @@ namespace ProjectTourAgency
container.RegisterType<IEmployeeRepository, EmployeeRepository>();
container.RegisterType<ITourRepository, TourRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@ -9,7 +9,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -27,4 +38,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectTourAgency.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/zoo_log.txt",
"rollingInterval": "Day"
}
}
]
}
}