diff --git a/ProjectOptika/ProjectOptika.csproj b/ProjectOptika/ProjectOptika.csproj index accbdf0..8d91237 100644 --- a/ProjectOptika/ProjectOptika.csproj +++ b/ProjectOptika/ProjectOptika.csproj @@ -9,7 +9,21 @@ + + + + + + + + + + + + + + diff --git a/ProjectOptika/Scripts/Forms/FormItemOrder.cs b/ProjectOptika/Scripts/Forms/FormItemOrder.cs index ca19e88..0f46faa 100644 --- a/ProjectOptika/Scripts/Forms/FormItemOrder.cs +++ b/ProjectOptika/Scripts/Forms/FormItemOrder.cs @@ -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 { diff --git a/ProjectOptika/Scripts/Program.cs b/ProjectOptika/Scripts/Program.cs index ea58915..2c227e4 100644 --- a/ProjectOptika/Scripts/Program.cs +++ b/ProjectOptika/Scripts/Program.cs @@ -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()); } - private static UnityContainer CreateContainer () { - var container = new UnityContainer (); + private static UnityContainer CreateContainer () { + var container = new UnityContainer(); + + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(); container.RegisterType(); @@ -27,7 +33,21 @@ namespace ProjectOptika.Scripts container.RegisterType(); container.RegisterType(); + container.RegisterType(); + 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; + } } } \ No newline at end of file diff --git a/ProjectOptika/Scripts/Repositories/IConnectionString.cs b/ProjectOptika/Scripts/Repositories/IConnectionString.cs new file mode 100644 index 0000000..3467754 --- /dev/null +++ b/ProjectOptika/Scripts/Repositories/IConnectionString.cs @@ -0,0 +1,8 @@ +namespace ProjectOptika.Scripts.Repositories +{ + public interface IConnectionString + { + public string ConnectionString { get; } + } + +} diff --git a/ProjectOptika/Scripts/Repositories/Implementations/AccessoriesRepository.cs b/ProjectOptika/Scripts/Repositories/Implementations/AccessoriesRepository.cs index e1e3c1c..115b75d 100644 --- a/ProjectOptika/Scripts/Repositories/Implementations/AccessoriesRepository.cs +++ b/ProjectOptika/Scripts/Repositories/Implementations/AccessoriesRepository.cs @@ -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 _logger; + + public AccessoriesRepository(IConnectionString connectionString, ILogger 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 GetAccessories() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Accessories"; + var accessory = connection.Query(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(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; + } } } } diff --git a/ProjectOptika/Scripts/Repositories/Implementations/ClientRepositiory.cs b/ProjectOptika/Scripts/Repositories/Implementations/ClientRepositiory.cs index af70591..b42c0a6 100644 --- a/ProjectOptika/Scripts/Repositories/Implementations/ClientRepositiory.cs +++ b/ProjectOptika/Scripts/Repositories/Implementations/ClientRepositiory.cs @@ -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 _logger; + + public ClientRepositiory(IConnectionString connectionString, ILogger 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(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client)); + return client; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable GetClients() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Client"; + var clients = connection.Query(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; + } } } } diff --git a/ProjectOptika/Scripts/Repositories/Implementations/ConnectionString.cs b/ProjectOptika/Scripts/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..73f4006 --- /dev/null +++ b/ProjectOptika/Scripts/Repositories/Implementations/ConnectionString.cs @@ -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"; + } +} diff --git a/ProjectOptika/Scripts/Repositories/Implementations/EmployeeRepository.cs b/ProjectOptika/Scripts/Repositories/Implementations/EmployeeRepository.cs index 924e738..6ade71a 100644 --- a/ProjectOptika/Scripts/Repositories/Implementations/EmployeeRepository.cs +++ b/ProjectOptika/Scripts/Repositories/Implementations/EmployeeRepository.cs @@ -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 _logger; + + public EmployeeRepository(IConnectionString connectionString, ILogger 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(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(employee)); + return employee; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable GetEmployees() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Employee"; + var employees = connection.Query(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; + } } } } diff --git a/ProjectOptika/Scripts/Repositories/Implementations/OrderRepository.cs b/ProjectOptika/Scripts/Repositories/Implementations/OrderRepository.cs index c979287..e4f49a5 100644 --- a/ProjectOptika/Scripts/Repositories/Implementations/OrderRepository.cs +++ b/ProjectOptika/Scripts/Repositories/Implementations/OrderRepository.cs @@ -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 _logger; + + public OrderRepository(IConnectionString connectionString, ILogger 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(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 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(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(orders)); + return orders; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } } diff --git a/ProjectOptika/Scripts/Repositories/Implementations/SpecificationsRepository.cs b/ProjectOptika/Scripts/Repositories/Implementations/SpecificationsRepository.cs index 32f9ab2..8744851 100644 --- a/ProjectOptika/Scripts/Repositories/Implementations/SpecificationsRepository.cs +++ b/ProjectOptika/Scripts/Repositories/Implementations/SpecificationsRepository.cs @@ -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 _logger; + + public SpecificationsRepository(IConnectionString connectionString, ILogger 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 GetSpecifications() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Specifications"; + var specifications = connection.Query(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(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; + } } } } diff --git a/ProjectOptika/appsettings.json b/ProjectOptika/appsettings.json new file mode 100644 index 0000000..ca3f7ae --- /dev/null +++ b/ProjectOptika/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/optika_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file