log +logic 2.0 for cleaning and athlete

This commit is contained in:
pnevmoslon1 2024-11-25 10:54:16 +04:00
parent c1c71548a4
commit 0b03273946
9 changed files with 206 additions and 18 deletions

View File

@ -24,6 +24,8 @@ public class Athlete
FirstName = first ?? string.Empty,
LastName = last ?? string.Empty,
FatherName = father ?? string.Empty,
Sport = sport,
AthleteClass = athleteClass
};
}

View File

@ -2,6 +2,10 @@ using Unity.Lifetime;
using Unity;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity.Microsoft.Logging;
namespace ProjectHotel
{
@ -22,6 +26,8 @@ namespace ProjectHotel
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType <IConnectionString, ConnectionString> (new SingletonLifetimeManager());
container.RegisterType<IAthleteRepository, AthleteRepository>(new TransientLifetimeManager());
container.RegisterType<ICleaningRoomRepository, CleaningRoomRepository>(new TransientLifetimeManager());
container.RegisterType<IHotelRepository, HotelRepository>(new TransientLifetimeManager());
@ -30,5 +36,16 @@ namespace ProjectHotel
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

@ -28,6 +28,8 @@
<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="Npgsql" Version="9.0.1" />
<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" />
@ -37,4 +39,10 @@
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
internal interface IConnectionString
public interface IConnectionString
{
string ConnectionString { get; }

View File

@ -1,29 +1,128 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ProjectHotel.Repositories.Implementations;
internal class AthleteRepository : IAthleteRepository
public class AthleteRepository : IAthleteRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AthleteRepository> _logger;
public AthleteRepository(IConnectionString connectionString, ILogger<AthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAthlete(Athlete athlete)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Athletes (FirstName, LastName, FatherName, Sport, AthleteClass)
VALUES (@FirstName, @LastName, @FatherName, @Sport, @AthleteClass)";
connection.Execute(queryInsert, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAthlete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Athletes
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Athlete ReadAthleteById(int id)
{
return Athlete.CreateEntity(0, string.Empty, string.Empty,string.Empty, Entities.Enums.Sport.None, Entities.Enums.AthleteClass.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Athletes WHERE Id = @Id;
";
var athlete = connection.QueryFirst<Athlete>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(athlete));
return athlete;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Athlete> ReadAthletes()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Athletes";
var athletes = connection.Query<Athlete>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(athletes));
return athletes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public void UpdateAthlete(Athlete athlete)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Athletes
SET FirstName = @FirstName, LastName = @LastName, FatherName = @FatherName, @Sport = Sport, @AthleteClass = AthleteClass
WHERE Id = @Id;
";
connection.Execute(queryUpdate, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectHotel.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,16 +13,57 @@ namespace ProjectHotel.Repositories.Implementations;
internal class CleaningRoomRepository : ICleaningRoomRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CleaningRoomRepository> _logger;
public CleaningRoomRepository(IConnectionString connectionString, ILogger<CleaningRoomRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<CleaningRoom> ReadCleaningRooms(int? id = null, int? roomId = null)
{
return [];
}
public void CreateCleaningRoom(CleaningRoom cleaningRoom)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO CleaningRoom (RoomId, CleaningDate)
VALUES (@RoomId, @CleaningDate);
";
connection.Execute(queryInsert, cleaningRoom);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public CleaningRoom ReadCleaningRoomById(int id)
{
return CleaningRoom.CreateOperation(0, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM CleaningRoom WHERE Id = @Id;
";
var cleaningRoom = connection.QueryFirst<CleaningRoom>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
return cleaningRoom;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
}

View File

@ -6,7 +6,8 @@ using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations
{
internal class ConnectionString
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=OTP";
}
}

View File

@ -1,4 +1,5 @@
using ProjectHotel.Entities;
using Microsoft.Extensions.Logging;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,6 +10,16 @@ namespace ProjectHotel.Repositories.Implementations;
internal class PlacingAthleteRepository : IPlacingAthleteRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PlacingAthleteRepository> _logger;
public PlacingAthleteRepository(IConnectionString connectionString,
ILogger<PlacingAthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<PlacingAthlete> ReadPlacingAthlete(int? roomId = null, DateTime? placing = null)
{
return [];

View File

@ -1,10 +1,15 @@
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/hotel_log.txt",
"rollingInterval": "Day"
}
}
]
}
}