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

This commit is contained in:
H0llowVoid 2024-12-25 14:17:04 +04:00
parent ab5e73553b
commit 113cd58d30
23 changed files with 547 additions and 87 deletions

View File

@ -7,24 +7,24 @@ using ProjectOpticsSalon.Entites.Enums;
namespace ProjectOpticsSalon.Entites;
public class Order
public class MakeOrder
{
public int Id { get; private set; }
public double Price { get; private set; } = 0;
public DateTime Date { get; private set; }
public DateTime OrderDate { get; private set; }
public int ClientId { get; private set; }
public OrderStatus OrderStatus { get; private set; }
public IEnumerable<Product> Products { get; private set; } = [];
public static Order CreateOrder(int id, double price, int client, OrderStatus orderStatus, IEnumerable<Product> products)
public IEnumerable<Order_Product> Products { get; private set; } = [];
public static MakeOrder CreateOrder(int id, double price, int client, OrderStatus orderStatus, IEnumerable<Order_Product> products)
{
return new Order
return new MakeOrder
{
Id = id,
Price = price,
Date = DateTime.Now,
OrderDate = DateTime.Now,
ClientId = client,
OrderStatus = orderStatus,
Products = products

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectOpticsSalon.Entites;
public class Order_Product
{
public int OrderId { get; private set; }
public int ProductId { get; private set;}
public static Order_Product CreateElement(int orderId, int productId)
{
return new Order_Product { OrderId = orderId, ProductId = productId };
}
}

View File

@ -11,16 +11,16 @@ public class Production
public int Id { get; private set; }
public double ComponentsPrice { get; private set; }
public double WorkPrice { get; private set; }
public Product Product { get; private set; }
public int ProductId { get; private set; }
public DateTime Date { get; private set; }
public static Production CreateProduction(int id, double componentsPrice, double workPrice, Product product)
public static Production CreateProduction(int id, double componentsPrice, double workPrice, int productId)
{
return new Production
{
Id = id,
ComponentsPrice = componentsPrice,
WorkPrice = workPrice,
Product = product,
ProductId = productId,
Date = DateTime.Now
};
}

View File

@ -23,7 +23,7 @@ public partial class FormClient : Form
try
{
var client = _clientRepository.ReadClientById(value);
if (client != null)
if (client == null)
{
throw new InvalidDataException(nameof(client));
}

View File

@ -25,7 +25,7 @@ namespace ProjectOpticsSalon.Forms
try
{
var lens = _lensRepository.ReadLensById(value);
if (lens != null)
if (lens == null)
{
throw new InvalidDataException(nameof(lens));
}

View File

@ -31,8 +31,6 @@
label1 = new Label();
groupBox1 = new GroupBox();
dataGridViewData = new DataGridView();
ColumnProduct = new DataGridViewComboBoxColumn();
ColumnMaterial = new DataGridViewTextBoxColumn();
comboBoxClient = new ComboBox();
buttonCancel = new Button();
buttonSave = new Button();
@ -40,6 +38,7 @@
comboBoxStatus = new ComboBox();
maskedTextBoxPrice = new MaskedTextBox();
label3 = new Label();
ColumnProduct = new DataGridViewComboBoxColumn();
groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
@ -69,7 +68,7 @@
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Columns.AddRange(new DataGridViewColumn[] { ColumnProduct, ColumnMaterial });
dataGridViewData.Columns.AddRange(new DataGridViewColumn[] { ColumnProduct });
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(3, 23);
dataGridViewData.MultiSelect = false;
@ -80,20 +79,6 @@
dataGridViewData.Size = new Size(270, 288);
dataGridViewData.TabIndex = 0;
//
// ColumnProduct
//
ColumnProduct.HeaderText = "Продукт";
ColumnProduct.MinimumWidth = 6;
ColumnProduct.Name = "ColumnProduct";
ColumnProduct.Width = 125;
//
// ColumnMaterial
//
ColumnMaterial.HeaderText = "Материал";
ColumnMaterial.MinimumWidth = 6;
ColumnMaterial.Name = "ColumnMaterial";
ColumnMaterial.Width = 125;
//
// comboBoxClient
//
comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList;
@ -159,6 +144,13 @@
label3.TabIndex = 11;
label3.Text = "Статус";
//
// ColumnProduct
//
ColumnProduct.HeaderText = "Продукт";
ColumnProduct.MinimumWidth = 6;
ColumnProduct.Name = "ColumnProduct";
ColumnProduct.Width = 125;
//
// FormOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -189,11 +181,10 @@
private ComboBox comboBoxClient;
private Button buttonCancel;
private Button buttonSave;
private DataGridViewComboBoxColumn ColumnProduct;
private DataGridViewTextBoxColumn ColumnMaterial;
private Label label2;
private ComboBox comboBoxStatus;
private MaskedTextBox maskedTextBoxPrice;
private Label label3;
private DataGridViewComboBoxColumn ColumnProduct;
}
}

View File

@ -40,27 +40,29 @@ namespace ProjectOpticsSalon.Forms
private void buttonSave_Click(object sender, EventArgs e)
{
if (dataGridViewData.Rows.Count < 1 || comboBoxClient.SelectedIndex < 0)
if (dataGridViewData.Rows.Count < 1 || comboBoxClient.SelectedIndex < 0 ||
string.IsNullOrWhiteSpace(maskedTextBoxPrice.Text))
{
throw new Exception("Имеются незаполненные поля");
}
_orderRepository.CreateOrder(Order.CreateOrder(0, Convert.ToDouble(maskedTextBoxPrice.Text), (int)comboBoxClient.SelectedItem!,(OrderStatus)comboBoxStatus.SelectedItem!, CreateListProducts()));
_orderRepository.CreateOrder(MakeOrder.CreateOrder(0, Convert.ToDouble(maskedTextBoxPrice.Text), (int)comboBoxClient.SelectedValue!,(OrderStatus)comboBoxStatus.SelectedItem!, CreateListProducts()));
Close();
}
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private List<Product> CreateListProducts()
private List<Order_Product> CreateListProducts()
{
var list = new List<Product>();
var list = new List<Order_Product>();
foreach (DataGridViewRow row in dataGridViewData.Rows)
{
if (row.Cells["ColumnProduct"].Value == null || row.Cells["ColumnMaterial"].Value == null)
if (row.Cells["ColumnProduct"].Value == null)
{
continue;
}
list.Add(Product.CreateProduct(0, (ProductType)row.Cells["ColumnType"].Value,(FrameMaterial)row.Cells["ColumnMaterial"].Value, 0,0));
list.Add(Order_Product.CreateElement(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value)));
}
return list;
}

View File

@ -120,7 +120,4 @@
<metadata name="ColumnProduct.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnMaterial.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -55,17 +55,5 @@ namespace ProjectOpticsSalon.Forms
}
private void LoadList() => dataGridViewData.DataSource = _orderRepository.ReadOrder();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}

View File

@ -27,7 +27,7 @@ namespace ProjectOpticsSalon.Forms
try
{
var product = _productRepository.ReadProductById(value);
if (product != null)
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
@ -40,8 +40,8 @@ namespace ProjectOpticsSalon.Forms
}
comboBoxFrameMaterial.SelectedItem = product.FrameMaterial;
comboBoxLeftLens.SelectedIndex = product.LeftLensId;
comboBoxRightLens.SelectedIndex = product.RightLensId;
comboBoxLeftLens.SelectedValue = product.LeftLensId;
comboBoxRightLens.SelectedValue = product.RightLensId;
_productId = value;
}
catch (Exception ex)
@ -63,9 +63,11 @@ namespace ProjectOpticsSalon.Forms
comboBoxLeftLens.DataSource = lensRepository.ReadLens();
comboBoxLeftLens.DisplayMember = "Id";
comboBoxLeftLens.ValueMember = "Id";
comboBoxRightLens.DataSource = lensRepository.ReadLens();
comboBoxRightLens.DisplayMember= "Id";
comboBoxRightLens.ValueMember = "Id";
foreach (var elem in Enum.GetValues(typeof(FrameMaterial)))
{

View File

@ -61,9 +61,9 @@
label3.AutoSize = true;
label3.Location = new Point(84, 185);
label3.Name = "label3";
label3.Size = new Size(66, 20);
label3.Size = new Size(83, 20);
label3.TabIndex = 2;
label3.Text = "Продукт";
label3.Text = "ID продукт";
//
// maskedTextBoxComponentsPrice
//

View File

@ -25,14 +25,14 @@ namespace ProjectOpticsSalon.Forms
try
{
var production = _productionRepository.ReadProductionById(value);
if (production != null)
if (production == null)
{
throw new InvalidDataException(nameof(production));
}
maskedTextBoxComponentsPrice.Text = production.ComponentsPrice.ToString();
maskedTextBoxWorkPrice.Text = production.WorkPrice.ToString();
comboBoxProduct.SelectedItem = production.Product;
comboBoxProduct.SelectedItem = production.ProductId;
_productionId = value;
}
@ -62,7 +62,8 @@ namespace ProjectOpticsSalon.Forms
{
throw new Exception("Имеются незаполненные поля");
}
_productionRepository.CreateProduction(Production.CreateProduction(0, Convert.ToDouble(maskedTextBoxComponentsPrice.Text), Convert.ToDouble(maskedTextBoxWorkPrice.Text), (Product)comboBoxProduct.SelectedItem!));
_productionRepository.CreateProduction(Production.CreateProduction(0, Convert.ToDouble(maskedTextBoxComponentsPrice.Text), Convert.ToDouble(maskedTextBoxWorkPrice.Text), (int)comboBoxProduct.SelectedValue!));
Close();
}
catch (Exception ex)
{

View File

@ -1,6 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectOpticsSalon.Repositories;
using ProjectOpticsSalon.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectOpticsSalon
{
@ -21,12 +25,27 @@ namespace ProjectOpticsSalon
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IClientRepository, ClientRepository>();
container.RegisterType<ILensRepository, LensRepository>();
container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<IProductionRepository, ProductionRepository>();
container.RegisterType<IProductRepository, ProductRepository>();
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,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.2" />
<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="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -27,4 +40,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectOpticsSalon.Repositories
{
public interface IConnectionString
{
public string ConnectionString { get;}
}
}

View File

@ -9,8 +9,6 @@ namespace ProjectOpticsSalon.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrder();
Order ReadOrderById(int id);
void CreateOrder(Order order);
void UpdateOrder(Order order);
IEnumerable<MakeOrder> ReadOrder();
void CreateOrder(MakeOrder order);
}

View File

@ -1,4 +1,8 @@
using ProjectOpticsSalon.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsSalon.Entites;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,25 +13,107 @@ namespace ProjectOpticsSalon.Repositories.Implementations;
public class ClientRepository : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepository> _logger;
public ClientRepository(IConnectionString connectionString, ILogger<ClientRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO Client (Name) VALUES (@Name)";
connection.Execute(queryInsert, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteClient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Client
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Client ReadClientById(int id)
{
return Client.CreateClient(0,string.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Client
WHERE Id=@id";
var client = connection.QueryFirst<Client>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Client> ReadClients()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Client";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateClient(Client client)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Client
SET
Name=@Name
WHERE Id=@Id";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectOpticsSalon.Repositories.Implementations;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=opticssalon";
}

View File

@ -1,4 +1,8 @@
using ProjectOpticsSalon.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsSalon.Entites;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,25 +13,110 @@ namespace ProjectOpticsSalon.Repositories.Implementations;
public class LensRepository : ILensRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<LensRepository> _logger;
public LensRepository(IConnectionString connectionString, ILogger<LensRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateLens(Lens lens)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(lens));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"INSERT INTO Lens (Dioptres, Astigmatism) VALUES (@Dioptres, @Astigmatism)";
connection.Execute(queryInsert, lens);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteLens(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Lens
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Lens> ReadLens()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Lens";
var lenses = connection.Query<Lens>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(lenses));
return lenses;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Lens ReadLensById(int id)
{
return Lens.CreateLens(0,0,0);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Lens
WHERE Id=@id";
var lens = connection.QueryFirst<Lens>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(lens));
return lens;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateLens(Lens lens)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(lens));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Lens
SET
Dioptres=@Dioptres,
Astigmatism=@Astigmatism
WHERE Id=@Id";
connection.Execute(queryUpdate, lens);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectOpticsSalon.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsSalon.Entites;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,21 +13,65 @@ namespace ProjectOpticsSalon.Repositories.Implementations;
public class OrderRepository : IOrderRepository
{
public void CreateOrder(Order order)
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateOrder(MakeOrder order)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO MakeOrder (Price, OrderDate, ClientId, OrderStatus)
VALUES (@Price, @OrderDate, @ClientId, @OrderStatus);
SELECT MAX(Id) FROM MakeOrder";
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @"
INSERT INTO Order_Product (OrderId, ProductId)
VALUES (@OrderId, @ProductId)";
foreach (var elem in order.Products)
{
connection.Execute(querySubInsert, new
{
orderId,
elem.ProductId
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Order> ReadOrder()
public IEnumerable<MakeOrder> ReadOrder()
{
return [];
}
_logger.LogInformation("Получение всех объектов");
public Order ReadOrderById(int id)
{
return Order.CreateOrder(0,0,0,0,[]);
}
public void UpdateOrder(Order order)
{
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM MakeOrder";
var orders = connection.Query<MakeOrder>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectOpticsSalon.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsSalon.Entites;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,25 +13,110 @@ namespace ProjectOpticsSalon.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 (ProductType, FrameMaterial, LeftLensId, RightLensId) VALUES (@ProductType, @FrameMaterial, @LeftLensId, @RightLensId)";
connection.Execute(queryInsert, 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.CreateProduct(0,0,0,0,0);
_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 [];
_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;
}
}
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
ProductType=@ProductType,
FrameMaterial=@FrameMaterial,
LeftLensId=@LeftLensId,
RightLensId=@RightLensId
WHERE Id=@Id";
connection.Execute(queryUpdate, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectOpticsSalon.Entites;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOpticsSalon.Entites;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,21 +13,91 @@ namespace ProjectOpticsSalon.Repositories.Implementations;
public class ProductionRepository : IProductionRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductionRepository> _logger;
public ProductionRepository(IConnectionString connectionString, ILogger<ProductionRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProduction(Production production)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(production));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO Production (ComponentsPrice, WorkPrice, ProductId, Date) VALUES (@ComponentsPrice, @WorkPrice, @ProductId, @Date)";
connection.Execute(queryInsert, production);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Production> ReadProduction()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Production";
var productions = connection.Query<Production>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(productions));
return productions;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Production ReadProductionById(int id)
{
return Production.CreateProduction(0,0,0,null);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Production
WHERE Id=@id";
var production = connection.QueryFirst<Production>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(production));
return production;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateProduction(Production production)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(production));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Production
SET
ComponentsPrice=@ComponentsPrice,
WorkPrice=@WorkPrice,
ProductId=@ProductId,
Date=@Date
WHERE Id=@Id";
connection.Execute(queryUpdate, production);
}
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/optics_log.txt",
"rollingInterval": "Day"
}
}
]
}
}