From e5f63e0d71fc78f91cc83457181064bb2687822a Mon Sep 17 00:00:00 2001 From: kirkorovka <147087189+kirkorovka@users.noreply.github.com> Date: Sun, 8 Dec 2024 00:40:42 +0400 Subject: [PATCH] Lab2 --- .../Entities/Enums/Category.cs | 20 +-- .../ProjectGasStation/Entities/Sale.cs | 4 +- .../ProjectGasStation/Forms/FormSupplier.cs | 10 +- .../Forms/FormSuppliers.resx | 4 +- .../ProjectGasStation/Forms/FormWorkers.cs | 1 + .../ProjectGasStation/Program.cs | 25 ++++ .../ProjectGasStation.csproj | 18 +++ .../Repositories/IConectionString.cs | 12 ++ .../Implementations/ConectionString.cs | 13 ++ .../Implementations/ProductRepository.cs | 135 ++++++++++++++++-- .../Implementations/ReceiptRepository.cs | 79 +++++++++- .../Implementations/SaleRepository.cs | 79 +++++++++- .../Implementations/SupplierRepository.cs | 128 +++++++++++++++-- .../Implementations/WorkerRepository.cs | 133 +++++++++++++++-- .../ProjectGasStation/appsettings.json | 15 ++ 15 files changed, 614 insertions(+), 62 deletions(-) create mode 100644 ProjectGasStation/ProjectGasStation/Repositories/IConectionString.cs create mode 100644 ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConectionString.cs create mode 100644 ProjectGasStation/ProjectGasStation/appsettings.json diff --git a/ProjectGasStation/ProjectGasStation/Entities/Enums/Category.cs b/ProjectGasStation/ProjectGasStation/Entities/Enums/Category.cs index 1189457..abb9639 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Enums/Category.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Enums/Category.cs @@ -9,16 +9,16 @@ namespace ProjectGasStation.Entities.Enums; [Flags] public enum Category { - Fuel = 0, - Gas = 1, - LiquidFuel = 2, + None = 0, + Fuel = 1, + Oils = 2, Chemicals = 4, - Oils = 8, - CareProducts = 16, - CareForInterior = 32, - CareForBody = 64, - MineralOils = 128, - SyntheticOils = 256, - None = 512 + Gas = 8, + LiquidFuel = 16, + CareProducts = 32, + CareForInterior = 64, + CareForBody = 128, + MineralOils = 256, + SyntheticOils = 512 } diff --git a/ProjectGasStation/ProjectGasStation/Entities/Sale.cs b/ProjectGasStation/ProjectGasStation/Entities/Sale.cs index 409b600..0e6bc6b 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Sale.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Sale.cs @@ -11,7 +11,7 @@ public class Sale public int Id { get; set; } public DateTime DateTime { get; set; } public int WorkerId { get; set; } - public IEnumerable SaleProduct { get; set; } = []; + public IEnumerable SaleProducts { get; set; } = []; public static Sale CreateOperation(int id, int workerId, IEnumerable saleProduct) @@ -21,7 +21,7 @@ public class Sale Id = id, DateTime = DateTime.Now, WorkerId = workerId, - SaleProduct = saleProduct + SaleProducts = saleProduct }; } diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormSupplier.cs b/ProjectGasStation/ProjectGasStation/Forms/FormSupplier.cs index 9ef62a3..f0ebcee 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormSupplier.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormSupplier.cs @@ -29,13 +29,12 @@ namespace ProjectGasStation.Forms if (supplier == null) { throw new InvalidDataException(nameof(supplier)); - - textBoxSupplierName.Text = supplier.Name; - textBoxSupplierPhoneNumber.Text = supplier.PhoneNumber; - textBoxSupplierAddress.Text = supplier.Address; - _supplierId = value; } + textBoxSupplierName.Text = supplier.Name; + textBoxSupplierPhoneNumber.Text = supplier.PhoneNumber; + textBoxSupplierAddress.Text = supplier.Address; + _supplierId = value; } catch (Exception ex) { @@ -72,6 +71,7 @@ namespace ProjectGasStation.Forms { _supplierRepository.CreateSupplier(CreateSupplier(0)); } + Close(); } catch (Exception ex) { diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.resx b/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.resx index 280b274..93e6054 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.resx +++ b/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.resx @@ -163,7 +163,7 @@ iVBORw0KGgoAAAANSUhEUgAAA8cAAAPHCAIAAACKbawNAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAA/7JJREFUeF7s/Ql4ZOt+1/euKql773OOz9nn7Km7NXX33ufYgA0hiQEn12DDg3nM + vAAADrwBlbxySQAA/7JJREFUeF7s/Ql4ZOt+1/euKql773OOz9nn7Km7NXX33ufYgA0hiQEn12DDg3nM BYNvgHuBSwiEJAQIMeMDgQuX4fgBEgMhNpAbB4whDPZzc9m71ZpnqVtSd6sndbfUk8aaJNWwqmrVXCXp /tb6v3vt1SWpJ01V6/19ntflpWq1TquqtNZXa7/1LmOXiIiIiIgOh1VNRERERHRYrGoiIiIiosNiVRMR ERERHRarmoiIiIjosFjVRERERESHxaomIiIiIjosVjURERER0WGxqomIiIiIDotVTURERER0WKxqIiIi @@ -1468,7 +1468,7 @@ iVBORw0KGgoAAAANSUhEUgAAA80AAAPNCAIAAAA81B+iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO - vQAADr0BR/uQrQAA/7JJREFUeF7s/fd/G9l+5wk//8f+MOGGzt0SM5X62p6d3Z2d2ZmdxzvPeHftfd17 + vAAADrwBlbxySQAA/7JJREFUeF7s/fd/G9l+5wk//8f+MOGGzt0SM5X62p6d3Z2d2ZmdxzvPeHftfd17 u1stiQkg1X3X9ozDBPuOfce+yel67HG6HudpBYoSJVIkAVQVSIpUoCiKyoERoSIyxedb9S3VhUBSTYoA AdT5vF+fV+mgCIJAhVNvHJ065/+zDgAAAAAAACg38GwAAAAAAADKDzwbAAAAAACA8gPPBgAAAAAAoPzA swEAAAAAACg/8GwAAAAAAADKDzwbAAAAAACA8gPPBgAAAAAAoPzAswEAAAAAACg/8GwAAAAAAADKDzwb diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs b/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs index b0ac134..1f95782 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs @@ -89,6 +89,7 @@ namespace ProjectGasStation.Forms form.ShowDialog(); LoadList(); } + catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error); diff --git a/ProjectGasStation/ProjectGasStation/Program.cs b/ProjectGasStation/ProjectGasStation/Program.cs index da0df98..252e182 100644 --- a/ProjectGasStation/ProjectGasStation/Program.cs +++ b/ProjectGasStation/ProjectGasStation/Program.cs @@ -1,6 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using ProjectGasStation.Repositories; using ProjectGasStation.Repositories.Implementations; +using Serilog; using Unity; +using Unity.Lifetime; +using Unity.Microsoft.Logging; namespace ProjectGasStation { @@ -22,14 +27,34 @@ namespace ProjectGasStation { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); + container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); + container.RegisterType(new SingletonLifetimeManager()); + + + 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/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj b/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj index accbdf0..17c594d 100644 --- a/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj +++ b/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj @@ -9,7 +9,19 @@ + + + + + + + + + + + + @@ -27,4 +39,10 @@ + + + Always + + + \ No newline at end of file diff --git a/ProjectGasStation/ProjectGasStation/Repositories/IConectionString.cs b/ProjectGasStation/ProjectGasStation/Repositories/IConectionString.cs new file mode 100644 index 0000000..755c1d9 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/Repositories/IConectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGasStation.Repositories; + +public interface IConectionString +{ + public string ConectionString { get; } +} diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConectionString.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConectionString.cs new file mode 100644 index 0000000..bd5c8d0 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConectionString.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGasStation.Repositories.Implementations; + +internal class ConectionString : IConectionString +{ + string IConectionString.ConectionString => "Server=localhost, 5432;Database=gas_station;Uid=postgres;Pwd=13081306"; + +} diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ProductRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ProductRepository.cs index a5b2190..aa50b4d 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ProductRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ProductRepository.cs @@ -1,6 +1,11 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,27 +14,127 @@ namespace ProjectGasStation.Repositories.Implementations; internal class ProductRepository : IProductRepository { + + public readonly IConectionString _conectionString; + private readonly ILogger _logger; + + public ProductRepository(IConectionString conectionString, ILogger logger) + { + _conectionString = conectionString; + _logger = logger; + } + public void CreateProduct(Product product) { - - } + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); - public void DeleteProduct(int id) - { - } + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); - public IEnumerable ReadProduct() - { - return []; - } - - public Product ReadProductById(int id) - { - return Product.CreatEntity(0, string.Empty, 0, Entities.Enums.Category.None); + var queryInsert = @" INSERT INTO Products (Name, Price, Category) +VALUES (@Name, @Price, @Category)"; + connection.Execute(queryInsert, product); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void UpdateProduct(Product product) { - + _logger.LogInformation("Редакитрование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryUpdate = @" UPDATE Products +SET + Name = @Name, + Price = @Price, + Category = @Category +WHERE ID = @Id"; + connection.Execute(queryUpdate, product); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } + } + + public void DeleteProduct(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Products +WHERE ID = @id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + + public Product ReadProductById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + + + var querySelect = @" SELECT * FROM Products +WHERE ID = @id"; + var product = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product)); + + return product; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + + public IEnumerable ReadProduct() + { + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var querySelect = @" SELECT * FROM Products"; + var products = connection.Query(querySelect); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(products)); + + return products; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs index 659be76..dcff6f9 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs @@ -1,7 +1,12 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; using System; using System.Collections.Generic; using System.Linq; +using System.Net.WebSockets; using System.Text; using System.Threading.Tasks; @@ -9,16 +14,86 @@ namespace ProjectGasStation.Repositories.Implementations; internal class ReceiptRepository : IReceiptRepository { + public readonly IConectionString _conectionString; + private readonly ILogger _logger; + + public ReceiptRepository(IConectionString conectionString, ILogger logger) + { + _conectionString = conectionString; + _logger = logger; + } + public void CreateReceipt(Receipt receipt) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(receipt)); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" +INSERT INTO Receipt (DateTime, SupplierID) +VALUES (@DateTime, @SupplierID); +SELECT MAX(Id) FROM Receipt"; + var receiptId = connection.QueryFirst(queryInsert, receipt, transaction); + + var querySubInsert = @" +INSERT INTO ReceiptProducts(ProductID, ReceiptID, Quantity) +VALUES (@ProductID, @ReceiptID, @Quantity)"; + foreach (var elem in receipt.ReceiptProducts) + { + connection.Execute(querySubInsert, new { elem.ProductId, receiptId, elem.Quantity }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteReceipt(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Receipt +WHERE ID = @id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadReceipt(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? supplierId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + var querySelect = @" SELECT * FROM Receipt"; + var receipt = connection.Query(querySelect); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(receipt)); + + return receipt; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs index 4cc7bc8..aa7df96 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs @@ -1,4 +1,8 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,16 +13,87 @@ namespace ProjectGasStation.Repositories.Implementations; internal class SaleRepository : ISaleRepository { + + public readonly IConectionString _conectionString; + private readonly ILogger _logger; + + public SaleRepository(IConectionString conectionString, ILogger logger) + { + _conectionString = conectionString; + _logger = logger; + } + public void CreateSale(Sale sale) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(sale)); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" +INSERT INTO Sale (DateTime, WorkerID) +VALUES (@DateTime, @WorkerID); +SELECT MAX(Id) FROM Sale"; + var saleId = connection.QueryFirst(queryInsert, sale, transaction); + + var querySubInsert = @" +INSERT INTO SaleProducts(SaleID, ProductID, Quantity) +VALUES (@SaleID, @ProductID, @Quantity)"; + foreach (var elem in sale.SaleProducts) + { + connection.Execute(querySubInsert, new { saleId, elem.ProductId, elem.Quantity }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteSale(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Sale +WHERE ID = @id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadSale(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? workerId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + var querySelect = @" SELECT * FROM Sale"; + var sale = connection.Query(querySelect); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(sale)); + + return sale; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs index 5c6b1f9..462ef80 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs @@ -1,6 +1,11 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,26 +14,125 @@ namespace ProjectGasStation.Repositories.Implementations; public class SupplierRepository : ISupplierRepository { + + public readonly IConectionString _conectionString; + private readonly ILogger _logger; + + public SupplierRepository(IConectionString conectionString, ILogger logger) + { + _conectionString = conectionString; + _logger = logger; + } + public void CreateSupplier(Supplier supplier) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supplier)); - } - public void DeleteSupplier(int id) - { + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); - } - public Supplier ReadSupplierById(int id) - { - return Supplier.CreateEntity(0, string.Empty, string.Empty, string.Empty); - } - public IEnumerable ReadSupplier() - { - return []; + var queryInsert = @" INSERT INTO Suppliers (Name, PhoneNumber, Address) +VALUES (@Name, @PhoneNumber, @Address)"; + connection.Execute(queryInsert, supplier); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void UpdateSupplier(Supplier supplier) { + _logger.LogInformation("Редакитрование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supplier)); + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryUpdate = @" UPDATE Suppliers +SET + Name = @SupplierName, + PhoneNumber = @PhoneNumber, + Address = @Address +WHERE ID = @Id"; + connection.Execute(queryUpdate, supplier); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } + public void DeleteSupplier(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Suppliers +WHERE ID = @id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public Supplier ReadSupplierById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + + + var querySelect = @" SELECT * FROM Suppliers WHERE ID = @id"; + var supplier = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(supplier)); + + return supplier; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + public IEnumerable ReadSupplier() + { + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var querySelect = @" SELECT * FROM Suppliers"; + var suppliers = connection.Query(querySelect); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(suppliers)); + + return suppliers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + + } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/WorkerRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/WorkerRepository.cs index 4ad483b..ebe0c8a 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/WorkerRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/WorkerRepository.cs @@ -1,4 +1,8 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; using ProjectGasStation.Entities.Enums; using System; using System.Collections.Generic; @@ -10,25 +14,130 @@ namespace ProjectGasStation.Repositories.Implementations; public class WorkerRepository : IWorkerRepository { + + public readonly IConectionString _conectionString; + private readonly ILogger _logger; + + public WorkerRepository(IConectionString conectionString, ILogger logger) + { + _conectionString = conectionString; + _logger = logger; + } + public void CreateWorker(Worker worker) { - } + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(worker)); - public void DeleteWorker(int id) - { - } + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); - public IEnumerable ReadWorker() - { - return []; - } + var queryInsert = @" INSERT INTO Workers (Name, JobTitle) +VALUES (@Name, @JobTitle)"; + connection.Execute(queryInsert, worker); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } - public Worker ReadWorkerById(int id) - { - return Worker.CreateEntity(0, string.Empty, JobTitle.None); } public void UpdateWorker(Worker worker) { + _logger.LogInformation("Редакитрование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(worker)); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryUpdate = @" UPDATE Workers +SET + Name = @Name, + JobTitle = @JobTitle +WHERE ID = @Id"; + connection.Execute(queryUpdate, worker); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } + + + public void DeleteWorker(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Workers +WHERE ID = @id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + + public Worker ReadWorkerById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + + + var querySelect = @" SELECT * FROM Workers WHERE ID = @id"; + var worker = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(worker)); + + return worker; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadWorker() + { + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); + connection.Open(); + + var querySelect = @" SELECT * FROM Workers"; + var workers = connection.Query(querySelect); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(workers)); + + return workers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + + + + } diff --git a/ProjectGasStation/ProjectGasStation/appsettings.json b/ProjectGasStation/ProjectGasStation/appsettings.json new file mode 100644 index 0000000..37f7ac1 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/gs_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file -- 2.25.1