diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs index b02a5a2..230cfd5 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs @@ -15,9 +15,9 @@ public class Accessories public int Count { get; private set; } - public double Price { get; private set; } + public float Price { get; private set; } - public static Accessories CreateEntity(int id, AccessoriesType accessoriesType, int count, double price) + public static Accessories CreateEntity(int id, AccessoriesType accessoriesType, int count, float price) { return new Accessories { diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs index 89561d1..24de9bb 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs @@ -23,15 +23,17 @@ public class Order public IEnumerable ServicesOrders { get; private set; } = []; - public static Order CreateElement(int id, string name, string coment, int masterId) + public static Order CreateElement(int id, string name,DateTime date, string coment, int masterId, IEnumerable accessoiresOrders, IEnumerable servicesOrder) { return new Order() { Id = id, Name = name, Coment = coment, - Date = DateTime.Now, - MasterID = masterId + Date = date, + MasterID = masterId, + AccessoiresOrders = accessoiresOrders, + ServicesOrders = servicesOrder }; } diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs index 553d7e3..c622af7 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs @@ -13,9 +13,9 @@ public class Service public ServiceType ServiceType { get; private set; } - public double Price { get; private set; } + public float Price { get; private set; } - public static Service CreateEntity(int id, ServiceType serviceType, double price) + public static Service CreateEntity(int id, ServiceType serviceType, float price) { return new Service { diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessorie.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessorie.cs index 73951d2..8e26b42 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessorie.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessorie.cs @@ -74,15 +74,13 @@ namespace ProjectCompRepair.Forms { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } - + Close(); } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - private Accessories CreateAccessories(int id) - { - return Accessories.CreateEntity(id, (AccessoriesType)comboBoxType.SelectedItem! , (int)numericUpDownCount.Value, (double)numericUpDownPrice.Value); + private Accessories CreateAccessories(int id) => Accessories.CreateEntity(id, (AccessoriesType)comboBoxType.SelectedItem! , (int)numericUpDownCount.Value, (float)numericUpDownPrice.Value); - } + } } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormMaster.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormMaster.cs index e74cc85..2ac736c 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormMaster.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormMaster.cs @@ -69,7 +69,7 @@ public partial class FormMaster : Form { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } - + Close(); } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs index 2aa9ce2..f779905 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs @@ -70,14 +70,14 @@ public partial class FormOrder : Form { throw new Exception("Имеются незаполненые поля"); } - _orderRepository.CreateOrder(Order.CreateElement(0, textBoxName.Text, textBoxComent.Text, (int)comboBoxMaster.SelectedValue!)); + _orderRepository.CreateOrder(Order.CreateElement(0, textBoxName.Text,dateTimePicker.Value, textBoxComent.Text, (int)comboBoxMaster.SelectedValue!, CreateListAccessoiresOrderFromDataGrid(), CreateListServicesOrderFromDataGrid())); Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } - + Close(); } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); @@ -87,13 +87,13 @@ public partial class FormOrder : Form var list = new List(); foreach (DataGridViewRow row in dataGridViewAccessories.Rows) { - if (row.Cells["ColumnAccessoires"].Value == null || + if (row.Cells["ColumnAccessories"].Value == null || row.Cells["ColumnCount"].Value == null) { continue; } list.Add(AccessoiresOrder.CreateElement(0, - Convert.ToInt32(row.Cells["ColumnAccessoires"].Value), + Convert.ToInt32(row.Cells["ColumnAccessories"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); } return list; @@ -102,16 +102,16 @@ public partial class FormOrder : Form private List CreateListServicesOrderFromDataGrid() { var list = new List(); - foreach (DataGridViewRow row in dataGridViewAccessories.Rows) + foreach (DataGridViewRow row in dataGridViewServices.Rows) { - if (row.Cells["ColumnServices"].Value == null || - row.Cells["ColumnCountServices"].Value == null) + if (row.Cells["ColumnService"].Value == null || + row.Cells["ColumnCountServ"].Value == null) { continue; } list.Add(ServicesOrder.CreateElement(0, - Convert.ToInt32(row.Cells["ColumnAccessoires"].Value), - Convert.ToInt32(row.Cells["ColumnCount"].Value))); + Convert.ToInt32(row.Cells["ColumnService"].Value), + Convert.ToInt32(row.Cells["ColumnCountServ"].Value))); } return list; } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.resx b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.resx index 3fa5b7f..ca35006 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.resx +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.resx @@ -123,18 +123,6 @@ True - - True - - - True - - - True - - - True - True diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.Designer.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.Designer.cs index fb0ed62..9c3e00a 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.Designer.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.Designer.cs @@ -29,7 +29,6 @@ private void InitializeComponent() { buttonDel = new Button(); - buttonChange = new Button(); buttonCreate = new Button(); dataGridView = new DataGridView(); panelButtons = new Panel(); @@ -41,24 +40,13 @@ // buttonDel.BackgroundImage = Properties.Resources.pngwing_com__7_; buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(40, 255); + buttonDel.Location = new Point(40, 173); buttonDel.Name = "buttonDel"; buttonDel.Size = new Size(94, 91); buttonDel.TabIndex = 2; buttonDel.UseVisualStyleBackColor = true; buttonDel.Click += ButtonDel_Click; // - // buttonChange - // - buttonChange.BackgroundImage = Properties.Resources.pngwing_com__8_; - buttonChange.BackgroundImageLayout = ImageLayout.Stretch; - buttonChange.Location = new Point(40, 149); - buttonChange.Name = "buttonChange"; - buttonChange.Size = new Size(94, 89); - buttonChange.TabIndex = 1; - buttonChange.UseVisualStyleBackColor = true; - buttonChange.Click += ButtonChange_Click; - // // buttonCreate // buttonCreate.BackgroundImage = Properties.Resources.pngwing_com__6_; @@ -83,7 +71,6 @@ // panelButtons // panelButtons.Controls.Add(buttonDel); - panelButtons.Controls.Add(buttonChange); panelButtons.Controls.Add(buttonCreate); panelButtons.Dock = DockStyle.Right; panelButtons.Location = new Point(545, 0); @@ -109,7 +96,6 @@ #endregion private Button buttonDel; - private Button buttonChange; private Button buttonCreate; private DataGridView dataGridView; private Panel panelButtons; diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormService.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormService.cs index 28d3bf3..b53dade 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormService.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormService.cs @@ -41,6 +41,7 @@ namespace ProjectCompRepair.Forms } _service = value; + numericUpDownPrice.Value = (int)service.Price; } catch (Exception ex) { @@ -100,7 +101,7 @@ namespace ProjectCompRepair.Forms { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } - + Close(); } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); @@ -112,7 +113,7 @@ namespace ProjectCompRepair.Forms { serviceType |= (ServiceType)elem; } - return Service.CreateEntity(id, serviceType, (double)numericUpDownPrice.Value); + return Service.CreateEntity(id, serviceType, (float)numericUpDownPrice.Value); } } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs index 4412c17..afdd8aa 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs @@ -59,7 +59,7 @@ namespace ProjectCompRepair.Forms } try { - var form = _container.Resolve(); + var form = _container.Resolve(); form.Id = findId; form.ShowDialog(); LoadList(); diff --git a/ProjectCompRepair/ProjectCompRepair/Program.cs b/ProjectCompRepair/ProjectCompRepair/Program.cs index 3acb23a..1326170 100644 --- a/ProjectCompRepair/ProjectCompRepair/Program.cs +++ b/ProjectCompRepair/ProjectCompRepair/Program.cs @@ -1,7 +1,14 @@ +using Microsoft.Extensions.Logging; using ProjectCompRepair.Repositories; using ProjectCompRepair.Repositories.Implemantations; +using Serilog; using System; using Unity; +using Microsoft.Extensions.Configuration; +using Unity.Microsoft.Logging; +using Unity.Lifetime; + + namespace ProjectCompRepair { @@ -23,13 +30,29 @@ namespace ProjectCompRepair { var container = new UnityContainer(); - container.RegisterType(); - container.RegisterType(); - container.RegisterType(); - container.RegisterType(); - + 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()); + 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/ProjectCompRepair/ProjectCompRepair/ProjectCompRepair.csproj b/ProjectCompRepair/ProjectCompRepair/ProjectCompRepair.csproj index 2f10b71..0307ec6 100644 --- a/ProjectCompRepair/ProjectCompRepair/ProjectCompRepair.csproj +++ b/ProjectCompRepair/ProjectCompRepair/ProjectCompRepair.csproj @@ -9,8 +9,19 @@ - + + + + + + + + + + + + diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/IAccessoriesOrder.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/IAccessoriesOrder.cs new file mode 100644 index 0000000..c7b61e5 --- /dev/null +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/IAccessoriesOrder.cs @@ -0,0 +1,19 @@ +using ProjectCompRepair.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCompRepair.Repositories; + +public interface IAccessoriesOrder +{ + void CreateAccessoriesOrder(AccessoiresOrder accessoriesOrder); + + void DeleteAccessoriesOrder(int id); + + IEnumerable ReadAccessoiresOrder(int? Id = 0, int? orderId = 0, int? count = 0); + + +} diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/IConnectionString.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/IConnectionString.cs new file mode 100644 index 0000000..c90c50b --- /dev/null +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/IConnectionString.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCompRepair.Repositories; + +public interface IConnectionString +{ + public string ConnectionString {get;} + +} diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs index 863a410..8a02e54 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs @@ -17,8 +17,6 @@ public interface IOrderRepository void CreateOrder(Order order); - void UpdateOrder(Order order); - void DeleteOrder(int id); } diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/AccessoriesRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/AccessoriesRepository.cs index 0df9c6b..6fbab98 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/AccessoriesRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/AccessoriesRepository.cs @@ -4,33 +4,139 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System.Data.SqlClient; +using Dapper; +using Npgsql; +using System.Xml.Linq; namespace ProjectCompRepair.Repositories.Implemantations; public class AccessoriesRepository : IAccessoriesRepository { + 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); + connection.Open(); - public void DeleteAccessories(int id) - { - + var queryInsert = @" +INSERT INTO Accessories (AccessoriesType, Count, Price) +VALUES (@AccessoriesType, @Count, @Price)"; + connection.Execute(queryInsert, accessories); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } - - public IEnumerable ReadAccessories() - { - return []; - } - - public Accessories ReadAccessoriesById(int id) - { - return Accessories.CreateEntity(0, 0, 0, 0); - } - public void UpdateAccessories(Accessories accessories) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект : {json}", JsonConvert.SerializeObject(accessories)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryUpdate = @"UPDATE Accessories +SET + AccessoriesType = @AccessoriesType, + Count = @Count, + Price = @Price +WHERE ID = @Id;"; + connection.Execute(queryUpdate, 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); + connection.Open(); + + var queryDelete = @" +DELETE FROM Accessories +WHERE ID = @id +" +; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public Accessories ReadAccessoriesById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @" +SELECT * FROM Accessories +WHERE ID = @id +"; + var accessories = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(accessories)); + return accessories; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + public IEnumerable ReadAccessories() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @"SELECT * FROM Accessories"; + var accessories = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(accessories)); + return accessories; + } + catch(Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + + + + + } diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ConnectionString.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ConnectionString.cs new file mode 100644 index 0000000..4be1c79 --- /dev/null +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ConnectionString.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCompRepair.Repositories.Implemantations; +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "host=localhost;port=5432;username=postgres;password=123;Database=otp;"; +} + + + diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/MasterRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/MasterRepository.cs index 3bf559a..c8fb445 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/MasterRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/MasterRepository.cs @@ -1,6 +1,11 @@ -using ProjectCompRepair.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectCompRepair.Entities; using System; using System.Collections.Generic; +using System.Diagnostics.Metrics; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,28 +14,123 @@ namespace ProjectCompRepair.Repositories.Implemantations; public class MasterRepository : IMasterRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public MasterRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateMaster(Master master) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект : {json}", JsonConvert.SerializeObject(master)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryInsert = @" +INSERT INTO Master (Name) +VALUES (@Name)"; + connection.Execute(queryInsert, master); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } + public void DeleteMaster(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryDelete = @" +DELETE FROM Master +WHERE ID = @id +" +; + connection.Execute(queryDelete, new { id }); } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } +} public IEnumerable ReadMaster() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @"SELECT * FROM Master"; + var master = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(master)); + return master; } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } +} public Master ReadMasterById(int id) { - return Master.CreateEntity(0, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @" +SELECT * FROM Master +WHERE ID = @id +"; + var master = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(master)); + return master; } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } +} public void UpdateMaster(Master master) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект : {json}", JsonConvert.SerializeObject(master)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryUpdate = @"UPDATE Master +SET + Name = @Name +WHERE ID = @Id;"; + connection.Execute(queryUpdate, master); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; } } +} diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs index 41dad7d..42d1ebe 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs @@ -1,37 +1,148 @@ -using ProjectCompRepair.Entities; -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 ProjectCompRepair.Entities; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; -namespace ProjectCompRepair.Repositories.Implemantations; + namespace ProjectCompRepair.Repositories.Implemantations; -public class OrderRepository : IOrderRepository -{ + 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(); - public void DeleteOrder(int id) - { - - } + var queryInsert = @" + INSERT INTO Orderl (Name, Coment, Date, MasterId) + VALUES (@Name, @Coment, @Date, @MasterId); + SELECT MAX(ID) FROM Orderl"; - public IEnumerable ReadOrder() - { - return []; - } + + var orderId = connection.QueryFirst(queryInsert, order, transaction); - public Order ReadOrderById(int id) - { - return Order.CreateElement(0, string.Empty, string.Empty, 0); - } + var querySubInsertAccessories = @" + INSERT INTO AccessoriesOrder (OrderId, Count) + VALUES (@OrderId, @Count)"; - public void UpdateOrder(Order order) - { - throw new NotImplementedException(); - } + foreach (var elem in order.AccessoiresOrders) + { + connection.Execute(querySubInsertAccessories, new + { + OrderId = orderId, + elem.Count + }, transaction); + } -} + var querySubInsertServices = @" + INSERT INTO ServicesOrder (OrderId, Count) + VALUES (@OrderId, @Count)"; + + foreach (var elem in order.ServicesOrders) + { + connection.Execute(querySubInsertServices, new + { + OrderId = orderId, + 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(); + + var queryDelete = @" + DELETE FROM Orderl + WHERE ID = @id + " + ; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public Order ReadOrderById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @" + SELECT * FROM Orderl + WHERE ID = @id + "; + var order = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(order)); + return order; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadOrder() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @"SELECT * FROM Orderl"; + var order = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(order)); + return order; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + + + + + + } diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ServiceRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ServiceRepository.cs index 5b0e277..94adadd 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ServiceRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/ServiceRepository.cs @@ -1,4 +1,8 @@ -using ProjectCompRepair.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectCompRepair.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,28 +13,124 @@ namespace ProjectCompRepair.Repositories.Implemantations; public class ServiceRepository : IServiceRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public ServiceRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateService(Service service) { - - } + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект : {json}", JsonConvert.SerializeObject(service)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var queryInsert = @" +INSERT INTO Service (ServiceType, Price) +VALUES (@ServiceType, @Price)"; + connection.Execute(queryInsert, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateService(Service service) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект : {json}", JsonConvert.SerializeObject(service)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryUpdate = @"UPDATE Service +SET + ServiceType = @ServiceType, + Price = @Price +WHERE ID = @Id;"; + connection.Execute(queryUpdate, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } + } public void DeleteService(int id) { - - } + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); - public IEnumerable ReadService() - { - return []; + var queryDelete = @" +DELETE FROM Service +WHERE ID = @id +" +; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Service ReadServiceById(int id) { - return Service.CreateEntity(0, Entities.Enums.ServiceType.None, 0); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @" +SELECT * FROM Service +WHERE ID = @id +"; + var service = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(service)); + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + public IEnumerable ReadService() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @"SELECT * FROM Service"; + var service = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(service)); + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } - public void UpdateService(Service service) - { - - } + + + }