Лабораторная работа №2

This commit is contained in:
Олег Кудринский 2024-12-18 22:32:11 +04:00
parent c3bdef5739
commit 6a4c42fe23
17 changed files with 726 additions and 97 deletions

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<FormShift>();
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;
}
}
}

View File

@ -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<IAssemblerRepository, AssemblerRepository>();
container.RegisterType<IAssemblerShiftRepository, AssemblerShiftRepository>();
container.RegisterType<IAssemblyRepository, AssemblyRepository>();
@ -29,7 +36,21 @@ namespace ProjectWorkshop
container.RegisterType<IProductRepository, ProductRepository>();
container.RegisterType<IShiftRepository, ShiftRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
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;
}
}
}

View File

@ -9,7 +9,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -31,4 +42,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,7 @@
namespace ProjectWorkshop.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -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<AssemblerRepository> _logger;
public AssemblerRepository(IConnectionString connectionString, ILogger<AssemblerRepository> 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<Assembler> 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<Assembler>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(assembler));
return assembler;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Assembler> ReadAssemblers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Assembler";
var assemblers = connection.Query<Assembler>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(assemblers));
return assemblers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -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<AssemblerShiftRepository> _logger;
public AssemblerShiftRepository(IConnectionString connectionString, ILogger<AssemblerShiftRepository> 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<AssemblerShift> 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<AssemblerShift>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(assemblerShifts));
return assemblerShifts;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -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<AssemblyRepository> _logger;
public AssemblyRepository(IConnectionString connectionString, ILogger<AssemblyRepository> 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<int>(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<Assembly> ReadAssemblies(int? productID = null, int? assemblyID = null, int? count = null)
public IEnumerable<Assembly> 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<Assembly>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(assemblies));
return assemblies;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public IEnumerable<Assembler> GetAssemblers()
{
_logger.LogInformation("Получение всех сборщиков");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT ID, Name FROM Assembler";
var assemblers = connection.Query<Assembler>(query);
_logger.LogDebug("Полученные сборщики: {json}", JsonConvert.SerializeObject(assemblers));
return assemblers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении сборщиков");
throw;
}
}
}

View File

@ -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";
}

View File

@ -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<AssemblerRepository> _logger;
public ProductAssemblyRepository(IConnectionString connectionString, ILogger<AssemblerRepository> 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;
}
}
}

View File

@ -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<ProductRepository> _logger;
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> 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<Product>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> 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<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(products));
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -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<ShiftRepository> _logger;
public ShiftRepository(IConnectionString connectionString, ILogger<ShiftRepository> 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<Shift>(querySelect, new
{
id
});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(shift));
return shift;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Shift> 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<Shift>(querySelect);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении смен");
throw;
}
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs.txt",
"rollingInterval": "Day"
}
}
]
}
}