From 6a4c42fe23c83833a44980ea2b732353ba094a42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9E=D0=BB=D0=B5=D0=B3=20=D0=9A=D1=83=D0=B4=D1=80=D0=B8?= =?UTF-8?q?=D0=BD=D1=81=D0=BA=D0=B8=D0=B9?= Date: Wed, 18 Dec 2024 22:32:11 +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 --- .../Forms/FormAssemblers.Designer.cs | 44 +++--- .../ProjectWorkshop/Forms/FormAssemblers.cs | 6 +- .../Forms/FormProducts.Designer.cs | 68 +++++----- .../ProjectWorkshop/Forms/FormProducts.cs | 6 +- .../Forms/FormShifts.Designer.cs | 29 ++++ .../ProjectWorkshop/Forms/FormShifts.cs | 56 ++++++++ ProjectWorkshop/ProjectWorkshop/Program.cs | 21 +++ .../ProjectWorkshop/ProjectWorkshop.csproj | 17 +++ .../Repositories/IConnectonString.cs | 7 + .../Implementations/AssemblerRepository.cs | 128 ++++++++++++++++-- .../AssemblerShiftRepository.cs | 45 +++++- .../Implementations/AssemblyRepository.cs | 105 +++++++++++++- .../Implementations/ConnectionString.cs | 12 ++ .../ProductAssemblyRepository.cs | 50 ++++++- .../Implementations/ProductRepository.cs | 109 ++++++++++++++- .../Implementations/ShiftRepository.cs | 105 ++++++++++++-- .../ProjectWorkshop/appsettings.json | 15 ++ 17 files changed, 726 insertions(+), 97 deletions(-) create mode 100644 ProjectWorkshop/ProjectWorkshop/Repositories/IConnectonString.cs create mode 100644 ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ConnectionString.cs create mode 100644 ProjectWorkshop/ProjectWorkshop/appsettings.json diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.Designer.cs index 103c281..1abef80 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.Designer.cs @@ -32,9 +32,9 @@ buttonDel = new Button(); buttonUpd = new Button(); buttonAdd = new Button(); - dataGridView = new DataGridView(); + dataGridViewAssemblers = new DataGridView(); panel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataGridViewAssemblers).BeginInit(); SuspendLayout(); // // panel @@ -81,38 +81,38 @@ buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; // - // dataGridView + // dataGridViewAssemblers // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.AllowUserToResizeColumns = false; - dataGridView.AllowUserToResizeRows = false; - dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Dock = DockStyle.Fill; - dataGridView.Location = new Point(0, 0); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersVisible = false; - dataGridView.RowHeadersWidth = 82; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(1279, 850); - dataGridView.TabIndex = 1; + dataGridViewAssemblers.AllowUserToAddRows = false; + dataGridViewAssemblers.AllowUserToDeleteRows = false; + dataGridViewAssemblers.AllowUserToResizeColumns = false; + dataGridViewAssemblers.AllowUserToResizeRows = false; + dataGridViewAssemblers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + dataGridViewAssemblers.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridViewAssemblers.Dock = DockStyle.Fill; + dataGridViewAssemblers.Location = new Point(0, 0); + dataGridViewAssemblers.MultiSelect = false; + dataGridViewAssemblers.Name = "dataGridViewAssemblers"; + dataGridViewAssemblers.ReadOnly = true; + dataGridViewAssemblers.RowHeadersVisible = false; + dataGridViewAssemblers.RowHeadersWidth = 82; + dataGridViewAssemblers.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewAssemblers.Size = new Size(1279, 850); + dataGridViewAssemblers.TabIndex = 1; // // FormAssemblers // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(1592, 850); - Controls.Add(dataGridView); + Controls.Add(dataGridViewAssemblers); Controls.Add(panel); Name = "FormAssemblers"; StartPosition = FormStartPosition.CenterParent; Text = "Сборщики"; Load += FormAssemblers_Load; panel.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)dataGridViewAssemblers).EndInit(); ResumeLayout(false); } @@ -122,6 +122,6 @@ private Button buttonDel; private Button buttonUpd; private Button buttonAdd; - private DataGridView dataGridView; + private DataGridView dataGridViewAssemblers; } } \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.cs index a4ad521..75509fd 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormAssemblers.cs @@ -96,19 +96,19 @@ namespace ProjectWorkshop.Forms } } - private void LoadList() => dataGridView.DataSource = _assemblerRepository.ReadAssemblers(); + private void LoadList() => dataGridViewAssemblers.DataSource = _assemblerRepository.ReadAssemblers(); private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; - if (dataGridView.SelectedRows.Count < 1) + if (dataGridViewAssemblers.SelectedRows.Count < 1) { MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } - id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value); + id = Convert.ToInt32(dataGridViewAssemblers.SelectedRows[0].Cells["ID"].Value); return true; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.Designer.cs index c41838c..9e2e13a 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.Designer.cs @@ -29,12 +29,12 @@ private void InitializeComponent() { panel = new Panel(); + buttonDel = new Button(); buttonUpd = new Button(); buttonAdd = new Button(); - dataGridView = new DataGridView(); - buttonDel = new Button(); + dataGridViewProducts = new DataGridView(); panel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit(); SuspendLayout(); // // panel @@ -48,6 +48,17 @@ panel.Size = new Size(257, 757); panel.TabIndex = 0; // + // buttonDel + // + buttonDel.BackgroundImage = Properties.Resources.minus; + buttonDel.BackgroundImageLayout = ImageLayout.Stretch; + buttonDel.Location = new Point(53, 535); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(150, 151); + buttonDel.TabIndex = 2; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // // buttonUpd // buttonUpd.BackgroundImage = Properties.Resources.pencil; @@ -70,48 +81,37 @@ buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; // - // dataGridView + // dataGridViewProducts // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.AllowUserToResizeColumns = false; - dataGridView.AllowUserToResizeRows = false; - dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Dock = DockStyle.Fill; - dataGridView.Location = new Point(0, 0); - dataGridView.MultiSelect = false; - dataGridView.Name = "dataGridView"; - dataGridView.ReadOnly = true; - dataGridView.RowHeadersVisible = false; - dataGridView.RowHeadersWidth = 82; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(903, 757); - dataGridView.TabIndex = 1; - // - // buttonDel - // - buttonDel.BackgroundImage = Properties.Resources.pencil; - buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(53, 535); - buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(150, 151); - buttonDel.TabIndex = 2; - buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += ButtonDel_Click; + dataGridViewProducts.AllowUserToAddRows = false; + dataGridViewProducts.AllowUserToDeleteRows = false; + dataGridViewProducts.AllowUserToResizeColumns = false; + dataGridViewProducts.AllowUserToResizeRows = false; + dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridViewProducts.Dock = DockStyle.Fill; + dataGridViewProducts.Location = new Point(0, 0); + dataGridViewProducts.MultiSelect = false; + dataGridViewProducts.Name = "dataGridViewProducts"; + dataGridViewProducts.ReadOnly = true; + dataGridViewProducts.RowHeadersVisible = false; + dataGridViewProducts.RowHeadersWidth = 82; + dataGridViewProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewProducts.Size = new Size(903, 757); + dataGridViewProducts.TabIndex = 1; // // FormProducts // AutoScaleDimensions = new SizeF(13F, 32F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(1160, 757); - Controls.Add(dataGridView); + Controls.Add(dataGridViewProducts); Controls.Add(panel); Name = "FormProducts"; Text = "Изделия"; Load += FormProducts_Load; panel.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit(); ResumeLayout(false); } @@ -120,7 +120,7 @@ private Panel panel; private Button buttonUpd; private Button buttonAdd; - private DataGridView dataGridView; + private DataGridView dataGridViewProducts; private Button buttonDel; } } \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.cs index 14aea98..3e6eecd 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormProducts.cs @@ -93,18 +93,18 @@ namespace ProjectWorkshop.Forms } } - private void LoadList() => dataGridView.DataSource = _productRepository.ReadProducts(); + private void LoadList() => dataGridViewProducts.DataSource = _productRepository.ReadProducts(); private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; - if (dataGridView.SelectedRows.Count < 1) + if (dataGridViewProducts.SelectedRows.Count < 1) { MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } id = - Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value); + Convert.ToInt32(dataGridViewProducts.SelectedRows[0].Cells["ID"].Value); return true; } } diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.Designer.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.Designer.cs index 527039e..ea7cec0 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.Designer.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.Designer.cs @@ -29,6 +29,8 @@ private void InitializeComponent() { panel = new Panel(); + buttonDel = new Button(); + buttonUpd = new Button(); buttonAdd = new Button(); dataGridViewShifts = new DataGridView(); panel.SuspendLayout(); @@ -37,6 +39,8 @@ // // panel // + panel.Controls.Add(buttonDel); + panel.Controls.Add(buttonUpd); panel.Controls.Add(buttonAdd); panel.Dock = DockStyle.Right; panel.Location = new Point(962, 0); @@ -44,6 +48,28 @@ panel.Size = new Size(326, 768); panel.TabIndex = 0; // + // buttonDel + // + buttonDel.BackgroundImage = Properties.Resources.minus; + buttonDel.BackgroundImageLayout = ImageLayout.Stretch; + buttonDel.Location = new Point(93, 542); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(150, 151); + buttonDel.TabIndex = 2; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonUpd + // + buttonUpd.BackgroundImage = Properties.Resources.pencil; + buttonUpd.BackgroundImageLayout = ImageLayout.Stretch; + buttonUpd.Location = new Point(93, 294); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(150, 151); + buttonUpd.TabIndex = 1; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // // buttonAdd // buttonAdd.BackgroundImage = Properties.Resources.plus; @@ -68,6 +94,7 @@ dataGridViewShifts.ReadOnly = true; dataGridViewShifts.RowHeadersVisible = false; dataGridViewShifts.RowHeadersWidth = 82; + dataGridViewShifts.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridViewShifts.Size = new Size(962, 768); dataGridViewShifts.TabIndex = 1; // @@ -91,5 +118,7 @@ private Panel panel; private Button buttonAdd; private DataGridView dataGridViewShifts; + private Button buttonDel; + private Button buttonUpd; } } \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.cs b/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.cs index 4e46211..3ba6719 100644 --- a/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.cs +++ b/ProjectWorkshop/ProjectWorkshop/Forms/FormShifts.cs @@ -1,4 +1,5 @@ using ProjectWorkshop.Repositories; +using ProjectWorkshop.Repositories.Implementations; using System; using System.Collections.Generic; using System.ComponentModel; @@ -49,6 +50,61 @@ namespace ProjectWorkshop.Forms } } + private void ButtonUpd_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); + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (!TryGetIdentifierFromSelectedRow(out var findId)) + { + return; + } + if (MessageBox.Show("Удалить запись?", "Удаление", + MessageBoxButtons.YesNo) != DialogResult.Yes) + { + return; + } + try + { + _shiftRepository.DeleteShift(findId); + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при удалении", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void LoadList() => dataGridViewShifts.DataSource = _shiftRepository.ReadShifts(); + + private bool TryGetIdentifierFromSelectedRow(out int id) + { + id = 0; + if (dataGridViewShifts.SelectedRows.Count < 1) + { + MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + id = + Convert.ToInt32(dataGridViewShifts.SelectedRows[0].Cells["ID"].Value); + return true; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Program.cs b/ProjectWorkshop/ProjectWorkshop/Program.cs index b9b1494..3afff63 100644 --- a/ProjectWorkshop/ProjectWorkshop/Program.cs +++ b/ProjectWorkshop/ProjectWorkshop/Program.cs @@ -1,6 +1,11 @@ using ProjectWorkshop.Repositories.Implementations; using ProjectWorkshop.Repositories; using Unity; +using ProjectWorkshop.Repositories.Implementation; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; +using Unity.Microsoft.Logging; namespace ProjectWorkshop { @@ -22,6 +27,8 @@ namespace ProjectWorkshop { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); + container.RegisterType(); container.RegisterType(); container.RegisterType(); @@ -29,7 +36,21 @@ namespace ProjectWorkshop 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/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj b/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj index dd71423..c42d821 100644 --- a/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj +++ b/ProjectWorkshop/ProjectWorkshop/ProjectWorkshop.csproj @@ -9,7 +9,18 @@ + + + + + + + + + + + @@ -31,4 +42,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/IConnectonString.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/IConnectonString.cs new file mode 100644 index 0000000..31a6b10 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/IConnectonString.cs @@ -0,0 +1,7 @@ +namespace ProjectWorkshop.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } + +} diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerRepository.cs index b1cd3d1..11e0373 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,25 +13,123 @@ namespace ProjectWorkshop.Repositories.Implementations; public class AssemblerRepository : IAssemblerRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public AssemblerRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateAssembler(Assembler assembler) { - } + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assembler)); - public void DeleteAssembler(int id) - { - } + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var queryInsert = @" + INSERT INTO Assembler (FullName, AssemblerRank, WorkExperience) + VALUES (@FullName, @AssemblerRank, @WorkExperience)"; + connection.Execute(queryInsert, assembler); - public Assembler ReadAssemblerByID(int id) - { - return Assembler.CreateEntity(0, string.Empty, Entities.Enums.AssemblerRank.None, DateTime.Now); - } - - public IEnumerable ReadAssemblers() - { - return []; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void UpdateAssembler(Assembler assembler) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assembler)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Assembler + SET + FullName=@FullName, + AssemblerRank=@AssemblerRank, + WorkExperience=@WorkExperience + WHERE ID=@id"; + + connection.Execute(queryUpdate, assembler); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } + + public void DeleteAssembler(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Assembler + WHERE ID=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + + public Assembler ReadAssemblerByID(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Assembler + WHERE ID=@id"; + var assembler = connection.QueryFirst(querySelect, new + { + id + }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(assembler)); + return assembler; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadAssemblers() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Assembler"; + var assemblers = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(assemblers)); + return assemblers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs index 70d25ea..c53bab3 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblerShiftRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,12 +13,49 @@ namespace ProjectWorkshop.Repositories.Implementations; public class AssemblerShiftRepository : IAssemblerShiftRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public AssemblerShiftRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateAssemblerShift(AssemblerShift assemblerShift) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assemblerShift)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO AssemblerShift (WorkHours, AssemblerID_Assembler, ShiftID_Shift) + VALUES (@WorkHours, @AssemblerID_Assembler, @ShiftID_Shift)"; + connection.Execute(queryInsert, assemblerShift); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadAssemblerShifts(int? workHours = null, int? assemblerID = null, int? shiftID = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM AssemblerShift"; + var assemblerShifts = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(assemblerShifts)); + return assemblerShifts; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs index 02bc872..abc33b7 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/AssemblyRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,16 +13,111 @@ namespace ProjectWorkshop.Repositories.Implementations; public class AssemblyRepository : IAssemblyRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public AssemblyRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateAssembly(Assembly assembly) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(assembly)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + + var queryInsert = @" + INSERT INTO Assembly (Count, AssemblerID_Assembler) + VALUES (@Count, @AssemblerID_Assembler) + RETURNING ID"; + var assemblyId = connection.QueryFirst(queryInsert, new + { + assembly.Count, + assembly.AssemblerID_Assembler + }, transaction); + + var querySubInsert = @" + INSERT INTO ProductAssembly (ProductID_Product, AssemblyID_Assembly, Count) + VALUES (@ProductID_Product, @AssemblyID_Assembly, @Count)"; + + foreach (var elem in assembly.ProductAssembly) + { + connection.Execute(querySubInsert, new + { + AssemblyID_Assembly = assemblyId, + elem.ProductID_Product, + elem.Count + }, transaction); + } + + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteAssembly(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Assembly + WHERE ID=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } - public IEnumerable ReadAssemblies(int? productID = null, int? assemblyID = null, int? count = null) + public IEnumerable ReadAssemblies(int? id = null, int? assemblyID = null, int? count = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Assembly"; + var assemblies = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(assemblies)); + return assemblies; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } + + public IEnumerable GetAssemblers() + { + _logger.LogInformation("Получение всех сборщиков"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var query = "SELECT ID, Name FROM Assembler"; + var assemblers = connection.Query(query); + _logger.LogDebug("Полученные сборщики: {json}", JsonConvert.SerializeObject(assemblers)); + return assemblers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении сборщиков"); + throw; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ConnectionString.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..7993079 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/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 ProjectWorkshop.Repositories.Implementation; + +internal class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Database=otp;Username=postgres;Password=admin"; +} diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductAssemblyRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductAssemblyRepository.cs index 6042cf2..c7be548 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductAssemblyRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductAssemblyRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -7,13 +11,55 @@ using System.Threading.Tasks; namespace ProjectWorkshop.Repositories.Implementations; -internal class ProductAssemblyRepository : IProductAssemblyRepository +public class ProductAssemblyRepository : IProductAssemblyRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public ProductAssemblyRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateProductAssembly(ProductAssembly productAssembly) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(productAssembly)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Assembly (Count, ProductType) + VALUES (@Count, @ProductType) + RETURNING ID"; + connection.Execute(queryInsert, productAssembly); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteProductAssembly(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Assembly + WHERE ID=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs index fdeb4ee..c8f7af1 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ProductRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using ProjectWorkshop.Entities.Enums; using System; using System.Collections.Generic; @@ -10,25 +14,116 @@ namespace ProjectWorkshop.Repositories.Implementations; public class ProductRepository : IProductRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ProductRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateProduct(Product product) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Product (ProductName, Price, AssemblyDate, ProductType) + VALUES (@ProductName, @Price, @AssemblyDate, @ProductType) + RETURNING ID"; + 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(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Product + SET ProductName=@ProductName, Price=@Price, AssemblyDate=@AssemblyDate, ProductType=@ProductType + 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(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Product + WHERE ID=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Product ReadProductByID(int id) { - return Product.CreateEntity(0, string.Empty, 0, ProductType.None); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Product + 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 ReadProducts() { - return []; - } - - public void UpdateProduct(Product product) - { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Product"; + var products = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(products)); + return products; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ShiftRepository.cs b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ShiftRepository.cs index d0fe5c0..46a50de 100644 --- a/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ShiftRepository.cs +++ b/ProjectWorkshop/ProjectWorkshop/Repositories/Implementations/ShiftRepository.cs @@ -1,4 +1,8 @@ -using ProjectWorkshop.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectWorkshop.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -7,27 +11,112 @@ using System.Threading.Tasks; namespace ProjectWorkshop.Repositories.Implementations; -internal class ShiftRepository : IShiftRepository +public class ShiftRepository : IShiftRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public ShiftRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateShift(Shift shift) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(shift)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Shift (ShiftDate) + VALUES (@ShiftDate)"; + connection.Execute(queryInsert, shift); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateShift(Shift shift) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(shift)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Shift + SET ShiftDate=@ShiftDate + WHERE Id=@Id"; + connection.Execute(queryUpdate, shift); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteShift(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Shift + WHERE ID=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Shift ReadShiftByID(int id) { - return Shift.CreateEntity(0, DateTime.Now); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Shift + WHERE ID=@id"; + var shift = connection.QueryFirst(querySelect, new + { + id + }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(shift)); + return shift; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadShifts() { - return []; - } - - public void UpdateShift(Shift shift) - { + _logger.LogInformation("Получение всех смен"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT ID, ShiftDate FROM Shift"; + return connection.Query(querySelect); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении смен"); + throw; + } } } diff --git a/ProjectWorkshop/ProjectWorkshop/appsettings.json b/ProjectWorkshop/ProjectWorkshop/appsettings.json new file mode 100644 index 0000000..540cd04 --- /dev/null +++ b/ProjectWorkshop/ProjectWorkshop/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file