Лабораторная работа №2

This commit is contained in:
ENDORFIT 2024-12-18 23:54:52 +04:00
parent 37900bdff3
commit a766d80c77
11 changed files with 549 additions and 22 deletions

View File

@ -9,7 +9,21 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<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.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<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>

View File

@ -1,7 +1,5 @@

using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Repositories;
using ProjectOptika.Scripts.Repositories.Implementations;
namespace ProjectOptika.Scripts.Forms
{

View File

@ -1,6 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectOptika.Scripts.Repositories;
using ProjectOptika.Scripts.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectOptika.Scripts
{
@ -18,8 +22,10 @@ namespace ProjectOptika.Scripts
Application.Run(CreateContainer().Resolve<FormOptika>());
}
private static UnityContainer CreateContainer () {
var container = new UnityContainer ();
private static UnityContainer CreateContainer () {
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IAccessoriesRepository, AccessoriesRepository>();
container.RegisterType<IClientRepositiory, ClientRepositiory>();
@ -27,7 +33,21 @@ namespace ProjectOptika.Scripts
container.RegisterType<ISpecificationsRepository, SpecificationsRepository>();
container.RegisterType<IOrderRepository, OrderRepository>();
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

@ -0,0 +1,8 @@
namespace ProjectOptika.Scripts.Repositories
{
public interface IConnectionString
{
public string ConnectionString { get; }
}
}

View File

@ -1,29 +1,126 @@
using ProjectOptika.Scripts.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class AccessoriesRepository : IAccessoriesRepository
{
public void CreateAccessories(Accessories order)
private readonly IConnectionString _connectionString;
private readonly ILogger<AccessoriesRepository> _logger;
public AccessoriesRepository(IConnectionString connectionString, ILogger<AccessoriesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAccessories(Accessories accessories)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(accessories));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Accessories (Name, Brand, Cost, StockAvailability, AvailabilityStore, DeliveryDate, CategoryName)
VALUES (@Name, @Brand, @Cost, @StockAvailability, @AvailabilityStore, @DeliveryDate, @CategoryName)";
connection.Execute(queryInsert, accessories);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAccessories(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Accessories
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Accessories> GetAccessories()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Accessories";
var accessory = connection.Query<Accessories>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(accessory));
return accessory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Accessories GetAccessoriesByID(int id)
{
return Accessories.CreateEntity(0, string.Empty, string.Empty, 0, 0, 0, DateTime.Now, 0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Accessories
WHERE ID=@id";
var accessory = connection.QueryFirst<Accessories>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(accessory));
return accessory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateAccessories(Accessories order)
public void UpdateAccessories(Accessories accessories)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(accessories));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Accessories
SET
Name=@Name,
Brand=@Brand,
Cost=@Cost,
StockAvailability=@StockAvailability,
AvailabilityStore=@AvailabilityStore,
DeliveryDate=@DeliveryDate,
CategoryName=@CategoryName
WHERE ID=@ID";
connection.Execute(queryUpdate, accessories);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -1,29 +1,124 @@
using ProjectOptika.Scripts.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
using Dapper;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class ClientRepositiory : IClientRepositiory
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepositiory> _logger;
public ClientRepositiory(IConnectionString connectionString, ILogger<ClientRepositiory> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Client (ClientType, FirstName, SecondName, Surname, PhoneNumber)
VALUES (@ClientType, @FirstName, @SecondName, @Surname, @PhoneNumber)";
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 NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Client
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Client GetClientById(int id)
{
return Client.CreateEntity(0, Entities.Enums.ClientType.Corporate, string.Empty, string.Empty, string.Empty, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Client
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> GetClients()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Client";
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 NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Client
SET
ClientType=@ClientType,
FirstName=@FirstName,
SecondName=@SecondName,
Surname=@Surname,
PhoneNumber=@PhoneNumber
WHERE ID=@ID";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,7 @@
namespace ProjectOptika.Scripts.Repositories.Implementations
{
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Database=dboptika;Username=postgres;Password=admin";
}
}

View File

@ -1,29 +1,123 @@
using ProjectOptika.Scripts.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<EmployeeRepository> _logger;
public EmployeeRepository(IConnectionString connectionString, ILogger<EmployeeRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateEmployee(Employee employee)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Employee (PositionEmployee, FirstName, SecondName, Surname)
VALUES (@PositionEmployee, @FirstName, @SecondName, @Surname)";
connection.Execute(queryInsert, employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteEmployee(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Employee
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Employee GetEmployeerByID(int id)
{
return Employee.CreateEntity(0, Entities.Enums.PositionEmployee.None, string.Empty, string.Empty, string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Employee
WHERE ID=@id";
var employee = connection.QueryFirst<Employee>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(employee));
return employee;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Employee> GetEmployees()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Employee";
var employees = connection.Query<Employee>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(employees));
return employees;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateEmployee(Employee employee)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Employee
SET
PositionEmployee=@PositionEmployee,
FirstName=@FirstName,
SecondName=@SecondName,
Surname=@Surname
WHERE ID=@ID";
connection.Execute(queryUpdate, employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -1,20 +1,103 @@
using ProjectOptika.Scripts.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class OrderRepository : IOrderRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateOrder(Order order)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Zakaz (EmployeeID, ClientID, OrderDate, TotalCost)
VALUES (@EmployeeID, @ClientID, @OrderDate, @TotalCost);
SELECT MAX(Id) FROM Zakaz";
var orderID = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @"
INSERT INTO AccessoriesOrder (ZakazID, AccessoriesID, Count)
VALUES (@orderID, @AccesoryId, @Count)";
foreach (var elem in order.AccesoriesOrders)
{
connection.Execute(querySubInsert, new
{
orderID,
elem.AccesoryId,
elem.Count
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteOrder(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDelete = @"
DELETE FROM AccessoriesOrder
WHERE ZakazID = @id";
var queryDeleteReceptions = @"
DELETE FROM Zakaz
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
connection.Execute(queryDeleteReceptions, new { id });
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Order> GetOrders(DateTime? startDate = null, DateTime? endDate = null, double? totalCost = null, int? id = null, int? employeeID = null, int? clientID = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Zakaz";
var orders =
connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -1,29 +1,125 @@
using ProjectOptika.Scripts.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class SpecificationsRepository : ISpecificationsRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SpecificationsRepository> _logger;
public SpecificationsRepository(IConnectionString connectionString, ILogger<SpecificationsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSpecifications(Specifications specification)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(specification));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Specifications (AccessoriesID, Material, Astigmatism, Dioptericity, OriginCountry, TimeProduction)
VALUES (@AccessoriesID, @Material, @Astigmatism, @Dioptericity, @OriginCountry, @TimeProduction)";
connection.Execute(queryInsert, specification);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSpecifications(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Specifications
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Specifications> GetSpecifications()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Specifications";
var specifications = connection.Query<Specifications>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(specifications));
return specifications;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Specifications GetSpecificationsByID(int id)
{
return Specifications.CreateEntity(0, 0, string.Empty, string.Empty, string.Empty, string.Empty, 0.0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Specifications
WHERE ID=@id";
var specifications = connection.QueryFirst<Specifications>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(specifications));
return specifications;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateSpecifications(Specifications specification)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(specification));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Specifications
SET
AccessoriesID=@AccessoriesID,
Material=@Material,
Astigmatism=@Astigmatism,
Dioptericity=@Dioptericity,
OriginCountry=@OriginCountry,
TimeProduction=@TimeProduction
WHERE ID=@ID";
connection.Execute(queryUpdate, specification);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

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