From bd2e4185e03ab6263dc87fd4f147d7052d742a98 Mon Sep 17 00:00:00 2001 From: alhimek17 Date: Tue, 24 Dec 2024 20:51:36 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=20=E2=84=962?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectShoeShop/FormShoesShop.cs | 2 +- .../ProjectShoeShop/Forms/FormClient.cs | 2 +- .../ProjectShoeShop/Forms/FormOrder.cs | 4 +- .../ProjectShoeShop/Forms/FormSupply.cs | 48 +------- .../Forms/FormSupplys.Designer.cs | 14 --- .../ProjectShoeShop/Forms/FormSupplys.cs | 20 ---- ProjectShoeShop/ProjectShoeShop/Program.cs | 19 +++- .../ProjectShoeShop/ProjectShoeShop.csproj | 11 ++ .../Repositories/IClientRepository.cs | 2 + .../Repositories/IConnectionString.cs | 12 ++ .../Repositories/ISupplyRepository.cs | 3 - .../Implementations/ClientRepository.cs | 106 ++++++++++++++++-- .../Implementations/ConnectionString.cs | 12 ++ .../Implementations/OrderRepository.cs | 70 ++++++++++-- .../Implementations/ShoesRepository.cs | 105 +++++++++++++++-- .../Implementations/SupplyRepository.cs | 100 ++++++++++++++--- .../ProjectShoeShop/appsettings.json | 15 +++ 17 files changed, 424 insertions(+), 121 deletions(-) create mode 100644 ProjectShoeShop/ProjectShoeShop/Repositories/IConnectionString.cs create mode 100644 ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ConnectionString.cs create mode 100644 ProjectShoeShop/ProjectShoeShop/appsettings.json diff --git a/ProjectShoeShop/ProjectShoeShop/FormShoesShop.cs b/ProjectShoeShop/ProjectShoeShop/FormShoesShop.cs index dc3c9fd..bd52301 100644 --- a/ProjectShoeShop/ProjectShoeShop/FormShoesShop.cs +++ b/ProjectShoeShop/ProjectShoeShop/FormShoesShop.cs @@ -65,7 +65,7 @@ namespace ProjectShoeShop { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { diff --git a/ProjectShoeShop/ProjectShoeShop/Forms/FormClient.cs b/ProjectShoeShop/ProjectShoeShop/Forms/FormClient.cs index 7455bbf..d24d947 100644 --- a/ProjectShoeShop/ProjectShoeShop/Forms/FormClient.cs +++ b/ProjectShoeShop/ProjectShoeShop/Forms/FormClient.cs @@ -60,7 +60,7 @@ namespace ProjectShoeShop.Forms if (_clientId.HasValue) { - _clientRepository.CreateClient(CreateClient(_clientId.Value)); + _clientRepository.UpdateClient(CreateClient(_clientId.Value)); } else { diff --git a/ProjectShoeShop/ProjectShoeShop/Forms/FormOrder.cs b/ProjectShoeShop/ProjectShoeShop/Forms/FormOrder.cs index c4927bd..291a7f7 100644 --- a/ProjectShoeShop/ProjectShoeShop/Forms/FormOrder.cs +++ b/ProjectShoeShop/ProjectShoeShop/Forms/FormOrder.cs @@ -51,7 +51,7 @@ namespace ProjectShoeShop.Forms foreach (DataGridViewRow row in dataGridView.Rows) { if (row.Cells["ColumnShoe"].Value == null || - row.Cells["Size"].Value == null || + row.Cells["ColumnSize"].Value == null || row.Cells["ColumnNumberOfPairs"].Value == null) { continue; @@ -59,7 +59,7 @@ namespace ProjectShoeShop.Forms list.Add(OrderItem.CreateElement(0, Convert.ToInt32(row.Cells["ColumnShoe"].Value), Convert.ToInt32(row.Cells["ColumnNumberOfPairs"].Value), - Convert.ToInt32(row.Cells["Size"].Value))); + Convert.ToInt32(row.Cells["ColumnSize"].Value))); } return list; } diff --git a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupply.cs b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupply.cs index accf504..6fdf044 100644 --- a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupply.cs +++ b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupply.cs @@ -7,32 +7,6 @@ namespace ProjectShoeShop.Forms public partial class FormSupply : Form { private readonly ISupplyRepository _supplyRepository; - private readonly IShoesRepository _shoesRepository; - private int? _supplyId; - - public int Id - { - set - { - try - { - var supply = _supplyRepository.ReadSupplyById(value); - if (supply == null) - { - throw new InvalidDataException(nameof(supply)); - } - - comboBox.SelectedItem = supply.SupplyType; - _supplyId = value; - - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - } - } public FormSupply(ISupplyRepository supplyRepository, IShoesRepository shoesRepository) { @@ -41,8 +15,6 @@ namespace ProjectShoeShop.Forms throw new ArgumentNullException(nameof(supplyRepository)); comboBox.DataSource = Enum.GetValues(typeof(SupplyType)); - _shoesRepository = shoesRepository ?? - throw new ArgumentNullException(nameof(shoesRepository)); ColumnShoe.DataSource = shoesRepository.ReadShoes(); ColumnShoe.DisplayMember = "Name"; @@ -57,15 +29,7 @@ namespace ProjectShoeShop.Forms { throw new Exception("Имеется незаполненное поле"); } - - if (_supplyId.HasValue) - { - _supplyRepository.UpdateSupply(CreateSupply(_supplyId.Value)); - } - else - { - _supplyRepository.CreateSupply(CreateSupply(0)); - } + _supplyRepository.CreateSupply(CreateSupply(0)); Close(); } @@ -82,21 +46,21 @@ namespace ProjectShoeShop.Forms private Supply CreateSupply(int id) => Supply.CreateEntity(id,(SupplyType)comboBox.SelectedItem!, DateTime.Now, CreateListSupplyShoesFromDataGrid()); - private List CreateListSupplyShoesFromDataGrid() + private List CreateListSupplyShoesFromDataGrid() { - var list = new List(); + var list = new List(); foreach (DataGridViewRow row in dataGridView.Rows) { if (row.Cells["ColumnShoe"].Value == null || - row.Cells["Size"].Value == null || + row.Cells["ColumnSize"].Value == null || row.Cells["ColumnNumberOfPairs"].Value == null) { continue; } - list.Add(Entities.SupplyShoes.CreateElement(0, + list.Add(SupplyShoes.CreateElement(0, Convert.ToInt32(row.Cells["ColumnShoe"].Value), Convert.ToInt32(row.Cells["ColumnNumberOfPairs"].Value), - Convert.ToInt32(row.Cells["Size"].Value))); + Convert.ToInt32(row.Cells["ColumnSize"].Value))); } return list; } diff --git a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.Designer.cs b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.Designer.cs index e6032f1..da5438d 100644 --- a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.Designer.cs +++ b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.Designer.cs @@ -32,7 +32,6 @@ panel1 = new Panel(); buttonDelete = new Button(); buttonAdd = new Button(); - buttonUpdate = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); panel1.SuspendLayout(); SuspendLayout(); @@ -57,7 +56,6 @@ // // panel1 // - panel1.Controls.Add(buttonUpdate); panel1.Controls.Add(buttonDelete); panel1.Controls.Add(buttonAdd); panel1.Dock = DockStyle.Right; @@ -88,17 +86,6 @@ buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; // - // buttonUpdate - // - buttonUpdate.BackgroundImage = Properties.Resources._0_4348_objects_pencil_png; - buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch; - buttonUpdate.Location = new Point(65, 203); - buttonUpdate.Name = "buttonUpdate"; - buttonUpdate.Size = new Size(75, 67); - buttonUpdate.TabIndex = 2; - buttonUpdate.UseVisualStyleBackColor = true; - buttonUpdate.Click += ButtonUpdate_Click; - // // FormSupplys // AutoScaleDimensions = new SizeF(7F, 15F); @@ -120,6 +107,5 @@ private Panel panel1; private Button buttonDelete; private Button buttonAdd; - private Button buttonUpdate; } } \ No newline at end of file diff --git a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.cs b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.cs index b60547c..6581566 100644 --- a/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.cs +++ b/ProjectShoeShop/ProjectShoeShop/Forms/FormSupplys.cs @@ -92,25 +92,5 @@ namespace ProjectShoeShop.Forms id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); return true; } - - private void ButtonUpdate_Click(object sender, EventArgs e) - { - if (!TryGetIdentifierFromSelectedRow(out var findId)) - { - return; - } - try - { - var form = _container.Resolve(); - form.Id = findId; - form.ShowDialog(); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при изменении", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } } } diff --git a/ProjectShoeShop/ProjectShoeShop/Program.cs b/ProjectShoeShop/ProjectShoeShop/Program.cs index afa8c55..272c33f 100644 --- a/ProjectShoeShop/ProjectShoeShop/Program.cs +++ b/ProjectShoeShop/ProjectShoeShop/Program.cs @@ -1,6 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using ProjectShoeShop.Repositories; using ProjectShoeShop.Repositories.Implementations; +using Serilog; using Unity; +using Unity.Microsoft.Logging; namespace ProjectShoeShop { @@ -21,15 +25,26 @@ namespace ProjectShoeShop private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(); container.RegisterType(); container.RegisterType(); - 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/ProjectShoeShop/ProjectShoeShop/ProjectShoeShop.csproj b/ProjectShoeShop/ProjectShoeShop/ProjectShoeShop.csproj index 6b260fe..740bad0 100644 --- a/ProjectShoeShop/ProjectShoeShop/ProjectShoeShop.csproj +++ b/ProjectShoeShop/ProjectShoeShop/ProjectShoeShop.csproj @@ -9,8 +9,19 @@ + + + + + + + + + + + diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/IClientRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/IClientRepository.cs index fdbf1f4..9b24477 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/IClientRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/IClientRepository.cs @@ -16,4 +16,6 @@ public interface IClientRepository void CreateClient(Client client); void DeleteClient(int id); + + void UpdateClient(Client client); } diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/IConnectionString.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/IConnectionString.cs new file mode 100644 index 0000000..5fd0fe4 --- /dev/null +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/IConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectShoeShop.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/ISupplyRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/ISupplyRepository.cs index 3b9db96..e85f9a2 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/ISupplyRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/ISupplyRepository.cs @@ -10,12 +10,9 @@ namespace ProjectShoeShop.Repositories; public interface ISupplyRepository { IEnumerable ReadSupply(DateTime? dateForm = null, DateTime? dateTo = null); - Supply ReadSupplyById(int id); void CreateSupply(Supply supply); - void UpdateSupply(Supply supply); - void DeleteSupply(int id); } diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ClientRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ClientRepository.cs index 428ffd7..625cd0e 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ClientRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ClientRepository.cs @@ -1,29 +1,121 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using ProjectShoeShop.Entities; namespace ProjectShoeShop.Repositories.Implementations; public class ClientRepository : IClientRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ClientRepository(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 (Name) + VALUES (@Name)"; + 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 IEnumerable ReadClient() { - 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 Client ReadClientById(int id) { - return Client.CreateEntity(0, 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 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 + Name=@Name + WHERE Id=@Id"; + connection.Execute(queryUpdate, client); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ConnectionString.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..e2d2d2e --- /dev/null +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectShoeShop.Repositories.Implementations; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=030405;Database=OTP_shoes"; +} diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/OrderRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/OrderRepository.cs index f20eb71..313bc7b 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/OrderRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/OrderRepository.cs @@ -1,21 +1,77 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using ProjectShoeShop.Entities; namespace ProjectShoeShop.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 ""Order"" (ClientId, OrderDate) + VALUES (@ClientId, @OrderDate); + SELECT MAX(Id) FROM ""Order"""; + var orderId = + connection.QueryFirst(queryInsert, order, transaction); + var querySubInsert = @" + INSERT INTO OrderItem (OrderId, ShoesId, NumberOfPairs, Size) + VALUES (@OrderId, @ShoesId, @NumberOfPairs, @Size)"; + foreach (var elem in order.OrderItems) + { + connection.Execute(querySubInsert, new + { + orderId, + elem.ShoesId, + elem.NumberOfPairs, + elem.Size + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM \"Order\""; + var contractorFuels = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(contractorFuels)); + return contractorFuels; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ShoesRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ShoesRepository.cs index 44f6082..45242bc 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ShoesRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/ShoesRepository.cs @@ -1,36 +1,123 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using ProjectShoeShop.Entities; namespace ProjectShoeShop.Repositories.Implementations; public class ShoesRepository : IShoesRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ShoesRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateShoes(Shoes shoes) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(shoes)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Shoes (Name, Price, ShoesType) + VALUES (@Name, @Price, @ShoesType)"; + connection.Execute(queryInsert, shoes); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteShoes(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Shoes + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadShoes() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Shoes"; + var shoeses = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(shoeses)); + return shoeses; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Shoes ReadShoesById(int id) { - throw new NotImplementedException(); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Shoes + WHERE Id=@id"; + var shoes = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(shoes)); + return shoes; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdateShoes(Shoes shoes) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(shoes)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Shoes + SET + Name=@Name, + Price=@Price, + ShoesType=@ShoesType + WHERE Id=@Id"; + connection.Execute(queryUpdate, shoes); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/SupplyRepository.cs b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/SupplyRepository.cs index 3ac1298..b227c6c 100644 --- a/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/SupplyRepository.cs +++ b/ProjectShoeShop/ProjectShoeShop/Repositories/Implementations/SupplyRepository.cs @@ -1,32 +1,106 @@ -using ProjectShoeShop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectShoeShop.Entities; namespace ProjectShoeShop.Repositories.Implementations; public class SupplyRepository : ISupplyRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public SupplyRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateSupply(Supply supply) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(supply)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO Supply (SupplyType, DateOfReceipt) + VALUES (@SupplyType, @DateOfReceipt); + SELECT MAX(Id) FROM Supply"; + var supplyId = + connection.QueryFirst(queryInsert, supply, transaction); + var querySubInsert = @" + INSERT INTO SupplyShoes (SupplyId, ShoesId, NumberOfPairs, Size) + VALUES (@SupplyId, @ShoesId, @NumberOfPairs, @Size)"; + foreach (var elem in supply.SupplyShoes) + { + connection.Execute(querySubInsert, new + { + supplyId, + elem.ShoesId, + elem.NumberOfPairs, + elem.Size + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadSupply(DateTime? dateForm = null, DateTime? dateTo = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Supply"; + var supplies = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(supplies)); + return supplies; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } - public Supply ReadSupplyById(int id) - { - return Supply.CreateEntity(0, Entities.Enums.SupplyType.None, DateTime.Now, []); - } - - - public void UpdateSupply(Supply supply) - { - - } public void DeleteSupply(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryDeleteSub = @" + DELETE FROM SupplyShoes + WHERE SupplyId = @id"; + connection.Execute(queryDeleteSub, new { id }, transaction); + var queryDelete = @" + DELETE FROM Supply + WHERE Id = @id"; + connection.Execute(queryDelete, new { id }, transaction); + + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } } diff --git a/ProjectShoeShop/ProjectShoeShop/appsettings.json b/ProjectShoeShop/ProjectShoeShop/appsettings.json new file mode 100644 index 0000000..2f734b4 --- /dev/null +++ b/ProjectShoeShop/ProjectShoeShop/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file -- 2.25.1