From 0daf6ae71560c82aa77df90d56996af90d7defb0 Mon Sep 17 00:00:00 2001 From: Ctepa Date: Fri, 6 Dec 2024 12:01:27 +0400 Subject: [PATCH] labwork2WIP --- Publication/Entites/Materials.cs | 1 + Publication/Entites/PrintingHouses.cs | 3 +- Publication/Forms/FormCustomer.cs | 2 +- Publication/Forms/FormMaterial.Designer.cs | 1 - Publication/Forms/FormMaterial.cs | 15 ++- Publication/Forms/FormMaterials.cs | 4 +- Publication/Forms/FormOrder.cs | 6 +- .../Forms/FormPrintingHouse.Designer.cs | 1 + Publication/Forms/FormPrintingHouse.cs | 7 +- Publication/Forms/FormPublishingHouse.cs | 2 +- Publication/Forms/Publication.cs | 4 + Publication/Program.cs | 18 ++++ Publication/Publication.csproj | 12 +++ .../Repositories/IConnectionRepository.cs | 12 +++ .../Implementations/ConnectionRepository.cs | 12 +++ .../Implementations/CustomerRepository.cs | 97 +++++++++++++++++-- .../Implementations/MaterialRepository.cs | 91 +++++++++++++++-- .../Implementations/OrderRepository.cs | 52 ++++++++-- .../PrintingHouseRepository.cs | 70 ++++++++++++- .../PublishingHouseRepository.cs | 92 ++++++++++++++++-- Publication/application.json | 16 +++ 21 files changed, 468 insertions(+), 50 deletions(-) create mode 100644 Publication/Repositories/IConnectionRepository.cs create mode 100644 Publication/Repositories/Implementations/ConnectionRepository.cs create mode 100644 Publication/application.json diff --git a/Publication/Entites/Materials.cs b/Publication/Entites/Materials.cs index fb3456f..da520c2 100644 --- a/Publication/Entites/Materials.cs +++ b/Publication/Entites/Materials.cs @@ -6,6 +6,7 @@ public class Materials public int Id { get; set; } public DateTime DateMaterials { get; set; } public int Count { get; set; } + public TypeMaterials Material { get; set; } public static Materials CreateEntity(int id, DateTime dateMaterials, int count, TypeMaterials typeMaterials) diff --git a/Publication/Entites/PrintingHouses.cs b/Publication/Entites/PrintingHouses.cs index d71f890..5731021 100644 --- a/Publication/Entites/PrintingHouses.cs +++ b/Publication/Entites/PrintingHouses.cs @@ -11,7 +11,7 @@ public class PrintingHouses public IEnumerable printingHouseOrder { get; set; } = []; - public static PrintingHouses CreateEntity(int id, string title, string phone, string address,IEnumerable printingHouseOrders) + public static PrintingHouses CreateEntity(int id, string title, string phone, string address,int materialsId,IEnumerable printingHouseOrders) { return new PrintingHouses @@ -20,6 +20,7 @@ public class PrintingHouses Title = title, Phone = phone, Address = address, + MaterialsId=materialsId, printingHouseOrder = printingHouseOrders }; } diff --git a/Publication/Forms/FormCustomer.cs b/Publication/Forms/FormCustomer.cs index 834450b..805d718 100644 --- a/Publication/Forms/FormCustomer.cs +++ b/Publication/Forms/FormCustomer.cs @@ -63,7 +63,7 @@ public partial class FormCustomer : Form else { - customerRepository.CreateCustomer(CreateCustomer(0)); + customerRepository.CreateCustomer(CreateCustomer(1)); } Close(); diff --git a/Publication/Forms/FormMaterial.Designer.cs b/Publication/Forms/FormMaterial.Designer.cs index d5462f0..9d04f34 100644 --- a/Publication/Forms/FormMaterial.Designer.cs +++ b/Publication/Forms/FormMaterial.Designer.cs @@ -126,7 +126,6 @@ Name = "FormMaterial"; StartPosition = FormStartPosition.CenterScreen; Text = "FormMaterials"; - Load += FormMaterials_Load; ((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit(); ResumeLayout(false); PerformLayout(); diff --git a/Publication/Forms/FormMaterial.cs b/Publication/Forms/FormMaterial.cs index 69c98a8..bf17ca0 100644 --- a/Publication/Forms/FormMaterial.cs +++ b/Publication/Forms/FormMaterial.cs @@ -40,8 +40,9 @@ public partial class FormMaterial : Form checkedListBox1.SetItemChecked(checkedListBox1.Items.IndexOf(elem), true); } } - material.DateMaterials = dateTimePickerDateMaterial.Value.Date; - material.Count = int.Parse(numericUpDownCount.Value.ToString()); + MessageBox.Show(material.DateMaterials.ToString()); + numericUpDownCount.Value=material.Count; + dateTimePickerDateMaterial.Value = material.DateMaterials; materialId = value; } catch (Exception ex) @@ -62,16 +63,13 @@ public partial class FormMaterial : Form } } - private void FormMaterials_Load(object sender, EventArgs e) - { - } private void ButtonSave_Click(object sender, EventArgs e) { try { - if (int.Parse(numericUpDownCount.Value.ToString()) <= 0 || dateTimePickerDateMaterial.Value.Date < DateTime.Now || checkedListBox1.SelectedItems.Count == 0) + if (int.Parse(numericUpDownCount.Value.ToString()) <= 0 || dateTimePickerDateMaterial.Value.Date <= DateTime.Now || checkedListBox1.SelectedItems.Count == 0) { throw new Exception("Имеются незаполненные поля"); } @@ -84,7 +82,7 @@ public partial class FormMaterial : Form else { - materialRepository.CreateMaterial(CreateMaterials(0)); + materialRepository.CreateMaterial(CreateMaterials(1)); } Close(); @@ -103,6 +101,7 @@ public partial class FormMaterial : Form { typeMaterials |= (TypeMaterials)elem; } - return Materials.CreateEntity(id, dateTimePickerDateMaterial.Value.Date, int.Parse(numericUpDownCount.Value.ToString()), typeMaterials); + MessageBox.Show(dateTimePickerDateMaterial.Value.ToString()); + return Materials.CreateEntity(id, dateTimePickerDateMaterial.Value, (int)numericUpDownCount.Value, typeMaterials); } } diff --git a/Publication/Forms/FormMaterials.cs b/Publication/Forms/FormMaterials.cs index a8851a9..a7cf34e 100644 --- a/Publication/Forms/FormMaterials.cs +++ b/Publication/Forms/FormMaterials.cs @@ -40,6 +40,7 @@ public partial class FormMaterials : Form { if (!TryGetIdentifierFromSelectedRow(out var findId)) { + MessageBox.Show("Привет", "Привет"); return; } try @@ -99,8 +100,7 @@ public partial class FormMaterials : Form return false; } - id = - Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value); + id =Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value); return true; } diff --git a/Publication/Forms/FormOrder.cs b/Publication/Forms/FormOrder.cs index 4e2d0bb..edb177d 100644 --- a/Publication/Forms/FormOrder.cs +++ b/Publication/Forms/FormOrder.cs @@ -40,10 +40,10 @@ public partial class FormOrder : Form throw new Exception("Имеются незаполненные поля"); } orderRepository.CreateOrder(Orders.CreateEntity( - 0, + 1, textBoxDescription.Text, - (int)comboBoxCutomer.SelectedIndex, - (int)comboBoxPublishingHouse.SelectedIndex + (int)comboBoxCutomer.SelectedValue!, + (int)comboBoxPublishingHouse.SelectedValue! )); Close(); } diff --git a/Publication/Forms/FormPrintingHouse.Designer.cs b/Publication/Forms/FormPrintingHouse.Designer.cs index a3d22a9..a62e4e7 100644 --- a/Publication/Forms/FormPrintingHouse.Designer.cs +++ b/Publication/Forms/FormPrintingHouse.Designer.cs @@ -105,6 +105,7 @@ // // comboBoxMaterials // + comboBoxMaterials.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxMaterials.FormattingEnabled = true; comboBoxMaterials.Location = new Point(129, 200); comboBoxMaterials.Name = "comboBoxMaterials"; diff --git a/Publication/Forms/FormPrintingHouse.cs b/Publication/Forms/FormPrintingHouse.cs index 50063a1..5d2f30d 100644 --- a/Publication/Forms/FormPrintingHouse.cs +++ b/Publication/Forms/FormPrintingHouse.cs @@ -45,17 +45,20 @@ public partial class FormPrintingHouse : Form ( PrintingHouses.CreateEntity ( - 0, + 1, textBoxTitle.Text, textBoxPhone.Text, textBoxAddress.Text, + (int)comboBoxMaterials.SelectedValue!, CreateListPrintingHouseOrdersFromDataGrid() ) ); + Close(); } catch (Exception ex) { - + MessageBox.Show(ex.Message, "Ошибка при сохранении", +MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/Publication/Forms/FormPublishingHouse.cs b/Publication/Forms/FormPublishingHouse.cs index 81c0b65..fc9558b 100644 --- a/Publication/Forms/FormPublishingHouse.cs +++ b/Publication/Forms/FormPublishingHouse.cs @@ -72,7 +72,7 @@ public partial class FormPublishingHouse : Form else { - publisingHouseRepository.CreatePublishingHouse(CreatePublishingHouse(0)); + publisingHouseRepository.CreatePublishingHouse(CreatePublishingHouse(1)); } Close(); diff --git a/Publication/Forms/Publication.cs b/Publication/Forms/Publication.cs index 3717845..1840d63 100644 --- a/Publication/Forms/Publication.cs +++ b/Publication/Forms/Publication.cs @@ -1,4 +1,7 @@ +using Dapper; +using Npgsql; using Publication.Forms; +using System.Data.SqlClient; using Unity; namespace Publication; @@ -37,6 +40,7 @@ public partial class Publication : Form MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); } + } private void PublishingHousesToolStripMenuItem_Click(object sender, EventArgs e) diff --git a/Publication/Program.cs b/Publication/Program.cs index cc2855c..f58daf7 100644 --- a/Publication/Program.cs +++ b/Publication/Program.cs @@ -1,7 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using Publication.Repositories; using Publication.Repositories.Implementations; +using Serilog; using Unity; using Unity.Lifetime; +using Unity.Microsoft.Logging; namespace Publication { @@ -23,12 +27,26 @@ namespace Publication private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); + container.RegisterType(new TransientLifetimeManager()); return container; } + + private static LoggerFactory CreateLoggerFactory() + { + var loggerFactory = new LoggerFactory(); + loggerFactory.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("C:\\Users\\Ctepa\\source\\repos\\PIbd-21_Chechevitsyn_S.A_Simple\\Publication\\application.json") + .Build()) + .CreateLogger()); + return loggerFactory; + } } } \ No newline at end of file diff --git a/Publication/Publication.csproj b/Publication/Publication.csproj index accbdf0..0307ec6 100644 --- a/Publication/Publication.csproj +++ b/Publication/Publication.csproj @@ -9,7 +9,19 @@ + + + + + + + + + + + + diff --git a/Publication/Repositories/IConnectionRepository.cs b/Publication/Repositories/IConnectionRepository.cs new file mode 100644 index 0000000..844ec4d --- /dev/null +++ b/Publication/Repositories/IConnectionRepository.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Publication.Repositories; + +public interface IConnectionRepository +{ + public string GetConnection { get; } +} diff --git a/Publication/Repositories/Implementations/ConnectionRepository.cs b/Publication/Repositories/Implementations/ConnectionRepository.cs new file mode 100644 index 0000000..ac4eedd --- /dev/null +++ b/Publication/Repositories/Implementations/ConnectionRepository.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Publication.Repositories.Implementations; + +public class ConnectionRepository : IConnectionRepository +{ + public string GetConnection => "Host=localhost;UserName=postgres;Password=1234;Database=publication"; +} diff --git a/Publication/Repositories/Implementations/CustomerRepository.cs b/Publication/Repositories/Implementations/CustomerRepository.cs index 4e445b8..a43e5af 100644 --- a/Publication/Repositories/Implementations/CustomerRepository.cs +++ b/Publication/Repositories/Implementations/CustomerRepository.cs @@ -1,30 +1,115 @@  +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using Dapper; +using Publication.Entites; +using Serilog.Core; +using System.Data.SqlClient; + namespace Publication.Repositories.Implementations; public class CustomerRepository : ICustomerRepository { - public void CreateCustomer(Customers customer) - { + private readonly IConnectionRepository connectionRepository; + private readonly ILogger logger; + + + public CustomerRepository (IConnectionRepository connectionRepository, ILogger logger) + { + this.connectionRepository = connectionRepository; + this.logger = logger; + } + + public void CreateCustomer(Customers customer) + { + logger.LogInformation("Добавление объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryInsert = @"INSERT INTO customer (FullName, Age, TypeCustomer, Phone, Email) + VALUES (@FullName, @Age, @TypeCustomer, @Phone, @Email)"; + connection.Execute(queryInsert, customer); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteCustomer(int id) { - + logger.LogInformation("Удаление объекта"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryDelete = @"DELETE FROM Customer WHERE id=@Id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Customers ReadCustomerById(int id) { - return Customers.CreateEntity(0, string.Empty, 0, Entites.Enums.TypeCustomers.None, string.Empty, string.Empty); + logger.LogInformation("Получение объекта по идентификатору"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = @"SELECT * FROM Customer WHERE id=@Id"; + var customer = connection.QueryFirst(querySelect, new { id }); + logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer)); + return customer; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadCustomers() { - return []; + logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = "SELECT * FROM Customer"; + var customer = connection.Query(querySelect); + logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customer)); + return customer; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdateCustomer(Customers customer) { - + logger.LogInformation("Редактирование объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryUpdate = @"UPDATE Customer + SET fullName=@FullName, age=@Age, typeCustomer=@TypeCustomer, phone=@Phone, email=@Email + WHERE Id=@Id"; + connection.Execute(queryUpdate, customer); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/Publication/Repositories/Implementations/MaterialRepository.cs b/Publication/Repositories/Implementations/MaterialRepository.cs index 9da4473..46ba86b 100644 --- a/Publication/Repositories/Implementations/MaterialRepository.cs +++ b/Publication/Repositories/Implementations/MaterialRepository.cs @@ -1,31 +1,110 @@ -using Publication.Entites; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using Publication.Entites; +using System.Text.Json.Serialization; namespace Publication.Repositories.Implementations; public class MaterialRepository : IMaterialRepository { + private readonly IConnectionRepository connectionRepository; + private readonly ILogger logger; + + public MaterialRepository(IConnectionRepository connectionRepository, ILogger logger) + { + this.connectionRepository = connectionRepository; + this.logger = logger; + } public void CreateMaterial(Materials material) { - + logger.LogInformation("Добавление объекта"); + logger.LogDebug("Объект: {json}",JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryInsert = @"INSERT INTO Material(datematerials,count,material) VALUES + (@DateMaterials,@Count,@Material)"; + connection.Execute(queryInsert, material); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteMaterial(int id) { - + logger.LogInformation("Удаление объекта"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryDelete = @"DELETE FROM Material WHERE id=@Id"; + connection.Execute(queryDelete, new {id}); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Materials ReadMaterialById(int id) { - return Materials.CreateEntity(0, DateTime.Now, 0, Entites.Enums.TypeMaterials.None); + logger.LogInformation("Получение объекта по идентификатору"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = @"SELECT * FROM Material WHERE id=@Id"; + var material = connection.QueryFirst(querySelect, new { id }); + logger.LogDebug("Найденный объект: {json}",JsonConvert.SerializeObject(material)); + return material; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadMaterials() { - return []; + logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = "SELECT * FROM Material"; + var materials = connection.Query(querySelect); + logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials)); + return materials; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdateMaterial(Materials material) { - + logger.LogInformation("Редактирование объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryUpdate = @"UPDATE Material + SET datematerials=@DateMaterials, count=@Count, material=@Material + WHERE Id=@Id"; + connection.Execute(queryUpdate, material); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/Publication/Repositories/Implementations/OrderRepository.cs b/Publication/Repositories/Implementations/OrderRepository.cs index 00cd2f0..c281185 100644 --- a/Publication/Repositories/Implementations/OrderRepository.cs +++ b/Publication/Repositories/Implementations/OrderRepository.cs @@ -1,23 +1,57 @@ - - +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using Publication.Entites; +using Dapper; +using System.Data.SqlClient; namespace Publication.Repositories.Implementations; public class OrderRepository : IOrderRepository { + private readonly IConnectionRepository connectionRepository; + + private readonly ILogger logger; + + public OrderRepository(IConnectionRepository connectionRepository, ILogger logger) + { + this.connectionRepository = connectionRepository; + this.logger = logger; + } public void CreateOrder(Orders order) { - - } - - public void DeleteOrder(int id) - { - + logger.LogInformation("Добавление объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryInsert = @"INSERT INTO Orders (OrderDate, Description, CustomerId, PublishingHouseId) + VALUES (@OrderDate, @Description, @CustomerId, @PublishingHouseId)"; + connection.Execute(queryInsert, order); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? customerId = null, int? publishingHouseId = null) { - return []; + logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = "SELECT * FROM Orders"; + var orders = connection.Query(querySelect); + logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); + return orders; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } + diff --git a/Publication/Repositories/Implementations/PrintingHouseRepository.cs b/Publication/Repositories/Implementations/PrintingHouseRepository.cs index 5629acf..70d5b2b 100644 --- a/Publication/Repositories/Implementations/PrintingHouseRepository.cs +++ b/Publication/Repositories/Implementations/PrintingHouseRepository.cs @@ -1,21 +1,83 @@ -using Publication.Entites; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using Publication.Entites; +using Dapper; namespace Publication.Repositories.Implementations; public class PrintingHouseRepository : IPrintingHouseRepository { + private readonly IConnectionRepository connectionRepository; + + private readonly ILogger logger; + + public PrintingHouseRepository(IConnectionRepository connectionRepository, ILogger logger) + { + this.connectionRepository = connectionRepository; + this.logger = logger; + } public void CreatePrintingHouse(PrintingHouses printerHouse) { - + logger.LogInformation("Добавление объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(printerHouse)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + connection.Open(); + using var transaction=connection.BeginTransaction(); + var queryInsert = @"INSERT INTO PrintingHouses (Title, Phone, Address, MaterialsId) + VALUES (@Title, @Phone, @Address, @MaterialsId); + SELECT MAX(Id) FROM PrintingHouses"; + var printingHousesId = connection.QueryFirst(queryInsert, printerHouse, transaction); + var querySubInsert = @" + INSERT INTO PrintingHouseOrders (PrintingHouseId,orderid,count) + VALUES (@PrintingHouseId,@OrderId,@Count)"; + foreach (var item in printerHouse.printingHouseOrder) + { + connection.Execute(querySubInsert, new { printingHousesId, item.OrderId, item.Count }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeletePrintingHouse(int id) { - + logger.LogInformation("Удаление объекта"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryDelete = @"DELETE FROM PrintingHouses WHERE Id=@Id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadPrintingHouses(int? printingHouseId = null, string? printingHousePhone = null, string? printingHouseAddress = null, int? materialsId = null) { - return []; + logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = "SELECT * FROM PrintingHouses"; + var printingHouses = connection.Query(querySelect); + logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(printingHouses)); + return printingHouses; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/Publication/Repositories/Implementations/PublishingHouseRepository.cs b/Publication/Repositories/Implementations/PublishingHouseRepository.cs index 14cecb7..760fd67 100644 --- a/Publication/Repositories/Implementations/PublishingHouseRepository.cs +++ b/Publication/Repositories/Implementations/PublishingHouseRepository.cs @@ -1,31 +1,111 @@ -using Publication.Entites; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using Publication.Entites; +using Dapper; namespace Publication.Repositories.Implementations; public class PublishingHouseRepository : IPublisingHouseRepository { + private readonly IConnectionRepository connectionRepository; + + private readonly ILogger logger; + + public PublishingHouseRepository(IConnectionRepository connectionRepository, ILogger logger) + { + this.connectionRepository = connectionRepository; + this.logger = logger; + } + public void CreatePublishingHouse(PublishingHouse publishingHouse) { - + logger.LogInformation("Добавление объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(publishingHouse)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryInsert = @"INSERT INTO PublishingHouse (title,address,workphone) VALUES + (@Title,@Address,@WorkPhone)"; + connection.Execute(queryInsert, publishingHouse); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeletePublishingHouse(int id) { - + logger.LogInformation("Удаление объекта"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryDelete = @"DELETE FROM PublishingHouse WHERE id=@Id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadPublishingHouses() { - return []; + logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = "SELECT * FROM PublishingHouse"; + var publishingHouses = connection.Query(querySelect); + logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(publishingHouses)); + return publishingHouses; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public PublishingHouse ReadPublishingHouseById(int id) { - return PublishingHouse.CreateEntity(0, string.Empty,string.Empty,string.Empty); + logger.LogInformation("Получение объекта по идентификатору"); + logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var querySelect = @"SELECT * FROM PublishingHouse WHERE id=@Id"; + var publishingHouse = connection.QueryFirst(querySelect, new { id }); + logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(publishingHouse)); + return publishingHouse; + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdatePublishingHouse(PublishingHouse publishingHouse) { - + logger.LogInformation("Редактирование объекта"); + logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(publishingHouse)); + try + { + using var connection = new NpgsqlConnection(connectionRepository.GetConnection); + var queryUpdate = @"UPDATE PublishingHouse + SET title=@Title, address=@Address, workphone=@WorkPhone + WHERE Id=@Id"; + connection.Execute(queryUpdate, publishingHouse); + } + catch (Exception ex) + { + logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/Publication/application.json b/Publication/application.json new file mode 100644 index 0000000..a2a2b07 --- /dev/null +++ b/Publication/application.json @@ -0,0 +1,16 @@ +{ + + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "C:\\Users\\Ctepa\\OneDrive\\Рабочий стол\\test.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file