Лабораторная работа №2 (1) Финал

This commit is contained in:
Егор 2024-12-09 01:23:21 +04:00
parent 40f96e0127
commit aa0a09dcff
11 changed files with 544 additions and 47 deletions

View File

@ -62,12 +62,12 @@ namespace FurnitureCompany.Forms
var list = new List<DeliveryProduct>();
foreach (DataGridViewRow row in dataGridViewProducts.Rows)
{
if (row.Cells["ColumnFeed"].Value == null || row.Cells["ColumnCount"].Value == null)
if (row.Cells["ColumnProduct"].Value == null || row.Cells["ColumnCount"].Value == null)
{
continue;
}
list.Add(DeliveryProduct.CreateElement(0, Convert.ToInt32(row.Cells["ColumnFeed"].Value),
list.Add(DeliveryProduct.CreateElement(0, Convert.ToInt32(row.Cells["ColumnProduct"].Value),
Convert.ToInt32(row.Cells["ColumnCount"].Value), 0));
}

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="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<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

@ -1,6 +1,11 @@
using FurnitureCompany.Repositories;
using FurnitureCompany.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace FurnitureCompany
{
@ -22,13 +27,29 @@ namespace FurnitureCompany
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IClientRepository, ClientRepository>();
container.RegisterType<IWorkerRepository, WorkerRepository>();
container.RegisterType<IProductRepository, ProductRepository>();
container.RegisterType<IInvoiceRepository, InvoiceRepository>();
container.RegisterType<IDeliveryRepository, DeliveryRepository>();
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

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

View File

@ -1,33 +1,134 @@
using FurnitureCompany.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Npgsql;
namespace FurnitureCompany.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));
public void DeleteClient(int id)
{
}
public IEnumerable<Client> ReadClients()
{
return[];
}
public Client ReadClientById(int id)
{
return Client.CreateEntity(0, string.Empty, string.Empty, 0, 0);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Clients (Name, Address, Age, Earnings)
VALUES (@Name, @Address, @Age, @Earnings)";
connection.Execute(queryInsert, client);
}
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 Clients
SET
Name = @Name,
Address = @Address,
Age = @Age,
Earnings = @Earnings
WHERE Id = @Id";
connection.Execute(queryUpdate, 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 Clients
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Client ReadClientById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Clients
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()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Clients";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
namespace FurnitureCompany.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost;Port=5432;Username=postgres;Password=admin;Database=OTP";
}

View File

@ -1,24 +1,99 @@
using FurnitureCompany.Entities;
using Dapper;
using FurnitureCompany.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace FurnitureCompany.Repositories.Implementations;
public class DeliveryRepository : IDeliveryRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<DeliveryRepository> _logger;
public DeliveryRepository(IConnectionString connectionString, ILogger<DeliveryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateDelivery(Delivery delivery)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(delivery));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Deliverys (WorkerId, DateDelivery)
VALUES (@WorkerId, @DateDelivery);
SELECT MAX(Id) FROM Deliverys";
var deliveryId = connection.QueryFirst<int>(queryInsert, delivery, transaction);
var querySubInsert = @"
INSERT INTO DeliveryProducts (ProductId, DeliveryId, Count)
VALUES (@ProductId, @DeliveryId, @Count)";
foreach (var elem in delivery.DeliveryProducts)
{
connection.Execute(querySubInsert, new { deliveryId, elem.ProductId, elem.Count }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteDelivery(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Deliverys
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Delivery> ReadDeliverys(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null, int? workerId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Deliverys";
var deliverys = connection.Query<Delivery>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(deliverys));
return deliverys;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using FurnitureCompany.Entities;
using Dapper;
using FurnitureCompany.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,12 +13,53 @@ namespace FurnitureCompany.Repositories.Implementations;
public class InvoiceRepository : IInvoiceRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<InvoiceRepository> _logger;
public InvoiceRepository(IConnectionString connectionString, ILogger<InvoiceRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateInvoice(Invoice invoice)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(invoice));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Invoices (WorkerId, ClientId, ProductId, Date, CountProduct)
VALUES (@WorkerId, @ClientId, @ProductId, @Date, @CountProduct)";
connection.Execute(queryInsert, invoice);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Invoice> ReadInvoices(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null, int? workerId = null, int? clientId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Invoices";
var invoices = connection.Query<Invoice>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(invoices));
return invoices;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,5 +1,9 @@
using FurnitureCompany.Entities;
using Dapper;
using FurnitureCompany.Entities;
using FurnitureCompany.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
@ -10,25 +14,119 @@ namespace FurnitureCompany.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));
public void DeleteProduct(int id)
{
}
public Product ReadProductById(int id)
{
return Product.CreateEntity(0, Material.None, string.Empty, 0);
}
public IEnumerable<Product> ReadProducts()
{
return [];
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Products (Name, Material, Price)
VALUES (@Name, @Material, @Price)";
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 Products
SET
Name = @Name,
Material = @Material,
Price = @Price
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 Products
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Product ReadProductById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Products
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()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,5 +1,9 @@
using FurnitureCompany.Entities;
using Dapper;
using FurnitureCompany.Entities;
using FurnitureCompany.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
@ -10,25 +14,119 @@ namespace FurnitureCompany.Repositories.Implementations;
public class WorkerRepository : IWorkerRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<WorkerRepository> _logger;
public WorkerRepository(IConnectionString connectionString, ILogger<WorkerRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateWorker(Worker worker)
{
}
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(worker));
public void DeleteWorker(int id)
{
}
public Worker ReadWorkerById(int id)
{
return Worker.CreateEntity(0, string.Empty, string.Empty, WorkerPost.None);
}
public IEnumerable<Worker> ReadWorkers()
{
return [];
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Workers (FirstName, LastName, WorkerPost)
VALUES (@FirstName, @LastName, @WorkerPost)";
connection.Execute(queryInsert, worker);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateWorker(Worker worker)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(worker));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Workers
SET
FirstName = @FirstName,
LastName = @LastName,
WorkerPost = @WorkerPost
WHERE Id = @Id";
connection.Execute(queryUpdate, worker);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteWorker(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Workers
WHERE Id = @Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Worker ReadWorkerById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Workers
WHERE Id = @Id";
var worker = connection.QueryFirst<Worker>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(worker));
return worker;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Worker> ReadWorkers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Workers";
var workers = connection.Query<Worker>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(workers));
return workers;
}
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/furniture_log.txt",
"rollingInterval": "Day"
}
}
]
}
}