From 912f547d3222514b0ac5f2c9faaf29e51759216d Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Mon, 25 Nov 2024 04:25:15 +0400 Subject: [PATCH 1/8] add extensions, add logger, add example logic --- .../PIbd-23_Gutorov_I.A._IT-Company.csproj | 17 +++++ PIbd-23_Gutorov_I.A._IT-Company/Program.cs | 19 +++++ .../Repositories/IConnectionString.cs | 12 ++++ .../Implementations/ConnectionString.cs | 12 ++++ .../Implementations/ContractRepository.cs | 70 +++++++++++++++++-- .../appsettings.json | 15 ++++ 6 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Repositories/IConnectionString.cs create mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs create mode 100644 PIbd-23_Gutorov_I.A._IT-Company/appsettings.json diff --git a/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj b/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj index 5159f6f..a3a964f 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj +++ b/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj @@ -10,7 +10,18 @@ + + + + + + + + + + + @@ -28,4 +39,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs index 3c5e10d..8114fc4 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs @@ -1,6 +1,10 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using PIbd_23_Gutorov_I.A._IT_Company.Repositories; using PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; +using Serilog; using Unity; +using Unity.Microsoft.Logging; namespace PIbd_23_Gutorov_I.A._IT_Company { @@ -22,13 +26,28 @@ namespace PIbd_23_Gutorov_I.A._IT_Company { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); + container.RegisterType(); container.RegisterType(); container.RegisterType(); 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/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IConnectionString.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IConnectionString.cs new file mode 100644 index 0000000..10298a0 --- /dev/null +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..c4b3c3f --- /dev/null +++ b/PIbd-23_Gutorov_I.A._IT-Company/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 PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => ""; +} diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index 1e14ec1..04e2130 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -1,19 +1,81 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System.Data.SqlClient; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class ContractRepository : IContractRepository { - public void CreateContract(Contract contract) + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public ContractRepository(IConnectionString connectionString, ILogger logger) { + _connectionString = connectionString; + _logger = logger; + } + + public void CreateContract(Entities.Contract contract) + { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(contract)); + + try + { + using var connection = new SqlConnection(_connectionString.ConnectionString); + connection.Open(); + var queryInsert = @" +INSERT INTO Contracts (CustomerId, ExecutorId, Category, ConclusionDate, Deadline, PaymentAmount) +VALUES (@CustomerId, @ExecutorId, @Category, @ConclusionDate, @Deadline, @PaymentAmount)"; + connection.Execute(queryInsert, contract); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteContract(int id) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new SqlConnection(_connectionString.ConnectionString); + connection.Open(); + var queryDelete = @" +DELETE FROM Contracts +WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } - public IEnumerable ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null, int? customerId = null, int? executorId = null) + public IEnumerable ReadContracts(DateTime? dateFrom = null, DateTime? dateTo = null, int? customerId = null, int? executorId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new SqlConnection(_connectionString.ConnectionString); + connection.Open(); + var querySelect = @"SELECT * FROM Contracts"; + var contracts = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts)); + return contracts; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/appsettings.json b/PIbd-23_Gutorov_I.A._IT-Company/appsettings.json new file mode 100644 index 0000000..8578938 --- /dev/null +++ b/PIbd-23_Gutorov_I.A._IT-Company/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/it-company_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file -- 2.25.1 From 1fc85814dc9a8cb6a4f2180a383bf5cab0b16e4e Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Mon, 25 Nov 2024 05:51:05 +0400 Subject: [PATCH 2/8] set connection string, work on repositories continues --- .../PIbd-23_Gutorov_I.A._IT-Company.csproj | 1 + .../Implementations/ConnectionString.cs | 2 +- .../Implementations/ContractRepository.cs | 15 +-- .../CustomerExecutorReviewRepository.cs | 6 +- .../Implementations/CustomerRepository.cs | 103 +++++++++++++++++- .../Implementations/ExecutorRepository.cs | 6 +- .../Implementations/ServiceRepository.cs | 103 +++++++++++++++++- 7 files changed, 220 insertions(+), 16 deletions(-) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj b/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj index a3a964f..b1e209f 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj +++ b/PIbd-23_Gutorov_I.A._IT-Company/PIbd-23_Gutorov_I.A._IT-Company.csproj @@ -15,6 +15,7 @@ + diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs index c4b3c3f..d5afdbc 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ConnectionString.cs @@ -8,5 +8,5 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class ConnectionString : IConnectionString { - string IConnectionString.ConnectionString => ""; + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=OTP"; } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index 04e2130..e1c6667 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -1,6 +1,7 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Npgsql; using System.Data.SqlClient; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; @@ -24,11 +25,11 @@ public class ContractRepository : IContractRepository try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); var queryInsert = @" -INSERT INTO Contracts (CustomerId, ExecutorId, Category, ConclusionDate, Deadline, PaymentAmount) -VALUES (@CustomerId, @ExecutorId, @Category, @ConclusionDate, @Deadline, @PaymentAmount)"; + INSERT INTO Contracts (CustomerId, ExecutorId, Category, ConclusionDate, Deadline, PaymentAmount) + VALUES (@CustomerId, @ExecutorId, @Category, @ConclusionDate, @Deadline, @PaymentAmount)"; connection.Execute(queryInsert, contract); } catch (Exception ex) @@ -45,11 +46,11 @@ VALUES (@CustomerId, @ExecutorId, @Category, @ConclusionDate, @Deadline, @Paymen try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); var queryDelete = @" -DELETE FROM Contracts -WHERE Id=@id"; + DELETE FROM Contracts + WHERE Id = @id"; connection.Execute(queryDelete, new { id }); } catch (Exception ex) @@ -65,7 +66,7 @@ WHERE Id=@id"; try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); var querySelect = @"SELECT * FROM Contracts"; var contracts = connection.Query(querySelect); diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs index ebd6a67..24d341a 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs @@ -1,9 +1,13 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Microsoft.Extensions.Logging; +using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class CustomerExecutorReviewRepository : ICustomerExecutorReviewRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public void CreateCustomerExecutorReview(CustomerExecutorReview customerContractReview) { } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerRepository.cs index 618d76a..1f3ba11 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerRepository.cs @@ -1,28 +1,125 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class CustomerRepository : ICustomerRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public CustomerRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateCustomer(Customer customer) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Customers (Name, Contact, Address) + VALUES (@Name, @Contact, @Address); + "; + connection.Execute(queryInsert, customer); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteCustomer(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Customers WHERE Id = @Id; + "; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Customer ReadCustomerById(int id) { - return Customer.CreateEntity(0, string.Empty, string.Empty, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Customers WHERE Id = @Id; + "; + var customer = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer)); + return customer; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadCustomers() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Customers; + "; + var customers = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customers)); + return customers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateCustomer(Customer customer) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Customers + SET Name = @Name, Contact = @Contact, Address = @Address + WHERE Id = @Id; + "; + connection.Execute(queryUpdate, customer); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs index 6533fc8..e1130a8 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs @@ -1,9 +1,13 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Microsoft.Extensions.Logging; +using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class ExecutorRepository : IExecutorRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public void CreateExecutor(Executor executor) { } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs index 1c4d86a..c3af217 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs @@ -1,28 +1,125 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; internal class ServiceRepository : IServiceRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ServiceRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateService(Service service) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Services (Description, ContractId) + VALUES (@Description, @ContractId); + "; + connection.Execute(queryInsert, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteService(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Services WHERE Id = @Id; + "; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Service ReadServiceById(int id) { - return Service.CreateEntity(0, string.Empty, 0); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Services WHERE Id = @Id; + "; + var service = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(service)); + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadServices(int? contractId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + SELECT * FROM Services; + "; + var services = connection.Query(queryInsert); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(services)); + return services; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateService(Service service) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Services + SET Description = @Description, ContractId = @ContractId + WHERE Id = @Id; + "; + connection.Execute(queryUpdate, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } -- 2.25.1 From 1da0a7d90c47307eeaa60800591de947cc702ada Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Mon, 25 Nov 2024 07:56:26 +0400 Subject: [PATCH 3/8] fix forms, restruct entities --- .../Entities/Contract.cs | 9 +- .../FormItCompany.Designer.cs | 11 +- .../FormItCompany.cs | 12 -- .../Forms/FormContract.Designer.cs | 6 +- .../Forms/FormContract.cs | 24 +++- .../Forms/FormCustomer.cs | 2 +- .../Forms/FormExecutor.cs | 2 +- .../Forms/FormService.Designer.cs | 121 ----------------- .../Forms/FormService.cs | 64 --------- .../Forms/FormService.resx | 120 ----------------- .../Forms/FormServices.Designer.cs | 126 ------------------ .../Forms/FormServices.cs | 96 ------------- .../Forms/FormServices.resx | 120 ----------------- PIbd-23_Gutorov_I.A._IT-Company/Program.cs | 1 - .../Repositories/IServiceRepository.cs | 16 --- .../Implementations/ServiceRepository.cs | 125 ----------------- 16 files changed, 30 insertions(+), 825 deletions(-) delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.Designer.cs delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.Designer.cs delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.cs delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.resx delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs delete mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Entities/Contract.cs b/PIbd-23_Gutorov_I.A._IT-Company/Entities/Contract.cs index cb943c3..66ec15b 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Entities/Contract.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Entities/Contract.cs @@ -18,7 +18,11 @@ public class Contract public int PaymentAmount { get; private set; } - public static Contract CreateEntity(int id, int customerID, int executorID, ContractCategory category, DateTime deadline, int paymentAmount) + public IEnumerable Services { get; private set; } = []; + + public static Contract CreateEntity(int id, int customerID, int executorID, + ContractCategory category, DateTime deadline, + int paymentAmount, IEnumerable services) { return new Contract { @@ -28,7 +32,8 @@ public class Contract Category = category, ConclusionDate = DateTime.Now, Deadline = deadline, - PaymentAmount = paymentAmount + PaymentAmount = paymentAmount, + Services = services }; } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs index 3e5371a..4aec222 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs @@ -32,7 +32,6 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); CustomersToolStripMenuItem = new ToolStripMenuItem(); ExecutorsToolStripMenuItem = new ToolStripMenuItem(); - ServicesToolStripMenuItem = new ToolStripMenuItem(); операцииToolStripMenuItem = new ToolStripMenuItem(); CustomerContractReviewsToolStripMenuItem = new ToolStripMenuItem(); контрактыToolStripMenuItem = new ToolStripMenuItem(); @@ -51,7 +50,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomersToolStripMenuItem, ExecutorsToolStripMenuItem, ServicesToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomersToolStripMenuItem, ExecutorsToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники"; @@ -70,13 +69,6 @@ ExecutorsToolStripMenuItem.Text = "Исполнители"; ExecutorsToolStripMenuItem.Click += ExecutorsToolStripMenuItem_Click; // - // ServicesToolStripMenuItem - // - ServicesToolStripMenuItem.Name = "ServicesToolStripMenuItem"; - ServicesToolStripMenuItem.Size = new Size(180, 22); - ServicesToolStripMenuItem.Text = "Услуги"; - ServicesToolStripMenuItem.Click += ServicesToolStripMenuItem_Click; - // // операцииToolStripMenuItem // операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomerContractReviewsToolStripMenuItem, контрактыToolStripMenuItem }); @@ -128,7 +120,6 @@ private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem CustomersToolStripMenuItem; private ToolStripMenuItem ExecutorsToolStripMenuItem; - private ToolStripMenuItem ServicesToolStripMenuItem; private ToolStripMenuItem операцииToolStripMenuItem; private ToolStripMenuItem отчетыToolStripMenuItem; private ToolStripMenuItem CustomerContractReviewsToolStripMenuItem; diff --git a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.cs b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.cs index 710d8e2..3035efc 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.cs @@ -37,18 +37,6 @@ namespace PIbd_23_Gutorov_I.A._IT_Company } } - private void ServicesToolStripMenuItem_Click(object sender, EventArgs e) - { - try - { - _container.Resolve().ShowDialog(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void ContractsToolStripMenuItem_Click(object sender, EventArgs e) { try diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs index 2eed9bf..165e71c 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs @@ -42,7 +42,7 @@ labelContractPaymentAmount = new Label(); dataGridViewServices = new DataGridView(); groupBox = new GroupBox(); - ColumnServiceDescription = new DataGridViewComboBoxColumn(); + ColumnServiceDescription = new DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)numericUpDownContractPaymentAmount).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridViewServices).BeginInit(); groupBox.SuspendLayout(); @@ -185,10 +185,10 @@ // // ColumnServiceDescription // + ColumnServiceDescription.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; ColumnServiceDescription.HeaderText = "Услуга"; ColumnServiceDescription.Name = "ColumnServiceDescription"; ColumnServiceDescription.Resizable = DataGridViewTriState.True; - ColumnServiceDescription.SortMode = DataGridViewColumnSortMode.Automatic; // // FormContract // @@ -234,6 +234,6 @@ private Label labelContractPaymentAmount; private DataGridView dataGridViewServices; private GroupBox groupBox; - private DataGridViewComboBoxColumn ColumnServiceDescription; + private DataGridViewTextBoxColumn ColumnServiceDescription; } } \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs index 7be33b9..b2ceea6 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs @@ -9,7 +9,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms private readonly IContractRepository _contractRepository; public FormContract(IContractRepository contractRepository, ICustomerRepository customerRepository, - IExecutorRepository executorRepository, IServiceRepository serviceRepository) + IExecutorRepository executorRepository) { InitializeComponent(); _contractRepository = contractRepository ?? throw new ArgumentNullException(nameof(contractRepository)); @@ -22,10 +22,6 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms comboBoxContractExecutorId.DisplayMember = "Name"; comboBoxContractExecutorId.DisplayMember = "Id"; - ColumnServiceDescription.DataSource = serviceRepository.ReadServices(); - ColumnServiceDescription.DisplayMember = "Description"; - comboBoxContractExecutorId.DisplayMember = "Id"; - foreach (var elem in Enum.GetValues(typeof(ContractCategory))) { checkedListBoxContractCategory.Items.Add(elem); @@ -63,8 +59,22 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms contractCategory |= (ContractCategory)elem; } - return Contract.CreateEntity(id, (int)comboBoxContractCustomerId.SelectedValue!, (int)comboBoxContractExecutorId.SelectedValue!, - contractCategory, dateTimePickerContractDeadline.Value, Convert.ToInt32(numericUpDownContractPaymentAmount.Value)); + return Contract.CreateEntity(id, (int)comboBoxContractCustomerId.SelectedValue!, + (int)comboBoxContractExecutorId.SelectedValue!, contractCategory, + dateTimePickerContractDeadline.Value, Convert.ToInt32(numericUpDownContractPaymentAmount.Value), + CreateServicesFromDataGrid()); } + + private List CreateServicesFromDataGrid() + { + var list = new List(); + + foreach (DataGridViewRow row in dataGridViewServices.Rows) + if (!row.IsNewRow) + list.Add(Service.CreateEntity(0, Convert.ToString(row.Cells["Description"].Value)!, 0)); + + return list; + } + } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomer.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomer.cs index 84309c8..cbb6c0d 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomer.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomer.cs @@ -49,7 +49,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms } if (_customerId.HasValue) _customerRepository.UpdateCustomer(CreateCustomer(_customerId.Value)); - else _customerRepository.UpdateCustomer(CreateCustomer(0)); + else _customerRepository.CreateCustomer(CreateCustomer(0)); Close(); } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormExecutor.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormExecutor.cs index 5945fe2..d847278 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormExecutor.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormExecutor.cs @@ -50,7 +50,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms } if (_executorId.HasValue) _executorRepository.UpdateExecutor(CreateExecutor(_executorId.Value)); - else _executorRepository.UpdateExecutor(CreateExecutor(0)); + else _executorRepository.CreateExecutor(CreateExecutor(0)); Close(); } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.Designer.cs deleted file mode 100644 index 08125c8..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.Designer.cs +++ /dev/null @@ -1,121 +0,0 @@ -namespace PIbd_23_Gutorov_I.A._IT_Company.Forms -{ - partial class FormService - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - comboBoxServiceContractId = new ComboBox(); - labelServiceContractId = new Label(); - labelServiceDescription = new Label(); - richTextBoxServiceDescription = new RichTextBox(); - buttonCancel = new Button(); - buttonSave = new Button(); - SuspendLayout(); - // - // comboBoxServiceContractId - // - comboBoxServiceContractId.DropDownStyle = ComboBoxStyle.DropDownList; - comboBoxServiceContractId.FormattingEnabled = true; - comboBoxServiceContractId.Location = new Point(169, 6); - comboBoxServiceContractId.Name = "comboBoxServiceContractId"; - comboBoxServiceContractId.Size = new Size(202, 23); - comboBoxServiceContractId.TabIndex = 15; - // - // labelServiceContractId - // - labelServiceContractId.AutoSize = true; - labelServiceContractId.Location = new Point(12, 9); - labelServiceContractId.Name = "labelServiceContractId"; - labelServiceContractId.Size = new Size(60, 15); - labelServiceContractId.TabIndex = 14; - labelServiceContractId.Text = "Контракт:"; - // - // labelServiceDescription - // - labelServiceDescription.AutoSize = true; - labelServiceDescription.Location = new Point(12, 38); - labelServiceDescription.Name = "labelServiceDescription"; - labelServiceDescription.Size = new Size(65, 15); - labelServiceDescription.TabIndex = 30; - labelServiceDescription.Text = "Описание:"; - // - // richTextBoxServiceDescription - // - richTextBoxServiceDescription.Location = new Point(169, 35); - richTextBoxServiceDescription.Name = "richTextBoxServiceDescription"; - richTextBoxServiceDescription.Size = new Size(202, 96); - richTextBoxServiceDescription.TabIndex = 29; - richTextBoxServiceDescription.Text = ""; - // - // buttonCancel - // - buttonCancel.Location = new Point(12, 166); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(359, 23); - buttonCancel.TabIndex = 32; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += ButtonCancel_Click; - // - // buttonSave - // - buttonSave.Location = new Point(12, 137); - buttonSave.Name = "buttonSave"; - buttonSave.Size = new Size(359, 23); - buttonSave.TabIndex = 31; - buttonSave.Text = "Сохранить"; - buttonSave.UseVisualStyleBackColor = true; - buttonSave.Click += ButtonSave_Click; - // - // FormService - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(387, 208); - Controls.Add(buttonCancel); - Controls.Add(buttonSave); - Controls.Add(labelServiceDescription); - Controls.Add(richTextBoxServiceDescription); - Controls.Add(comboBoxServiceContractId); - Controls.Add(labelServiceContractId); - Name = "FormService"; - StartPosition = FormStartPosition.CenterParent; - Text = "Услуга"; - ResumeLayout(false); - PerformLayout(); - } - - #endregion - - private ComboBox comboBoxServiceContractId; - private Label labelServiceContractId; - private Label labelServiceDescription; - private RichTextBox richTextBoxServiceDescription; - private Button buttonCancel; - private Button buttonSave; - } -} \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs deleted file mode 100644 index f94d5b7..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs +++ /dev/null @@ -1,64 +0,0 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; -using PIbd_23_Gutorov_I.A._IT_Company.Repositories; - -namespace PIbd_23_Gutorov_I.A._IT_Company.Forms -{ - public partial class FormService : Form - { - private readonly IServiceRepository _serviceRepository; - - private int? _serviceId; - - public int Id - { - set - { - try - { - var contract = _serviceRepository.ReadServiceById(value); - if (contract == null) throw new InvalidDataException(nameof(contract)); - - richTextBoxServiceDescription.Text = contract.Description; - _serviceId = value; - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - } - } - - public FormService(IServiceRepository serviceRepository, IContractRepository contractRepository) - { - InitializeComponent(); - _serviceRepository = serviceRepository ?? throw new ArgumentNullException(nameof(serviceRepository)); - - comboBoxServiceContractId.DataSource = contractRepository.ReadContracts(); - comboBoxServiceContractId.DisplayMember = "Id"; - } - - private void ButtonSave_Click(object sender, EventArgs e) - { - try - { - if (comboBoxServiceContractId.SelectedIndex < 0 || - string.IsNullOrEmpty(richTextBoxServiceDescription.Text)) - { - throw new Exception("Имеются незаполненные поля"); - } - - _serviceRepository.CreateService(Service.CreateEntity(0, - richTextBoxServiceDescription.Text, (int)comboBoxServiceContractId.SelectedValue!)); - - Close(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - } -} diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx deleted file mode 100644 index 8b2ff64..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.Designer.cs deleted file mode 100644 index dafc7f2..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.Designer.cs +++ /dev/null @@ -1,126 +0,0 @@ -namespace PIbd_23_Gutorov_I.A._IT_Company.Forms -{ - partial class FormServices - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - dataGridViewData = new DataGridView(); - panel = new Panel(); - buttonDel = new Button(); - buttonUpd = new Button(); - buttonAdd = new Button(); - ((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit(); - panel.SuspendLayout(); - SuspendLayout(); - // - // dataGridViewData - // - dataGridViewData.AllowUserToAddRows = false; - dataGridViewData.AllowUserToDeleteRows = false; - dataGridViewData.AllowUserToResizeColumns = false; - dataGridViewData.AllowUserToResizeRows = false; - dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; - dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridViewData.Dock = DockStyle.Fill; - dataGridViewData.Location = new Point(0, 0); - dataGridViewData.MultiSelect = false; - dataGridViewData.Name = "dataGridViewData"; - dataGridViewData.ReadOnly = true; - dataGridViewData.RowHeadersVisible = false; - dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridViewData.Size = new Size(677, 450); - dataGridViewData.TabIndex = 5; - // - // panel - // - panel.Controls.Add(buttonDel); - panel.Controls.Add(buttonUpd); - panel.Controls.Add(buttonAdd); - panel.Dock = DockStyle.Right; - panel.Location = new Point(677, 0); - panel.Name = "panel"; - panel.Size = new Size(123, 450); - panel.TabIndex = 4; - // - // buttonDel - // - buttonDel.BackgroundImage = Properties.Resources.icon_remove_button; - buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(16, 204); - buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(90, 90); - buttonDel.TabIndex = 2; - buttonDel.UseVisualStyleBackColor = true; - buttonDel.Click += ButtonDel_Click; - // - // buttonUpd - // - buttonUpd.BackgroundImage = Properties.Resources.icon_edit_button; - buttonUpd.BackgroundImageLayout = ImageLayout.Stretch; - buttonUpd.Location = new Point(16, 108); - buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(90, 90); - buttonUpd.TabIndex = 1; - buttonUpd.UseVisualStyleBackColor = true; - buttonUpd.Click += ButtonUpd_Click; - // - // buttonAdd - // - buttonAdd.BackgroundImage = Properties.Resources.icon_add_button; - buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(16, 12); - buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(90, 90); - buttonAdd.TabIndex = 0; - buttonAdd.UseVisualStyleBackColor = true; - buttonAdd.Click += ButtonAdd_Click; - // - // FormServices - // - AutoScaleDimensions = new SizeF(7F, 15F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); - Controls.Add(dataGridViewData); - Controls.Add(panel); - Name = "FormServices"; - StartPosition = FormStartPosition.CenterParent; - Text = "Услуги"; - Load += FormServices_Load; - ((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit(); - panel.ResumeLayout(false); - ResumeLayout(false); - } - - #endregion - - private DataGridView dataGridViewData; - private Panel panel; - private Button buttonDel; - private Button buttonUpd; - private Button buttonAdd; - } -} \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.cs deleted file mode 100644 index 5b0cea9..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.cs +++ /dev/null @@ -1,96 +0,0 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Repositories; -using Unity; - -namespace PIbd_23_Gutorov_I.A._IT_Company.Forms -{ - public partial class FormServices : Form - { - private readonly IUnityContainer _container; - - private readonly IServiceRepository _serviceRepository; - - public FormServices(IUnityContainer container, IServiceRepository serviceRepository) - { - InitializeComponent(); - _container = container ?? throw new ArgumentException(nameof(container)); - _serviceRepository = serviceRepository ?? throw new ArgumentException(nameof(serviceRepository)); - } - - private void FormServices_Load(object sender, EventArgs e) - { - try - { - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void ButtonAdd_Click(object sender, EventArgs e) - { - try - { - _container.Resolve().ShowDialog(); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - 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 - { - _serviceRepository.DeleteService(findId); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - private void LoadList() => dataGridViewData.DataSource = _serviceRepository.ReadServices(); - - 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; - } - } -} diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.resx b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.resx deleted file mode 100644 index 8b2ff64..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormServices.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs index 8114fc4..a253ffa 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs @@ -32,7 +32,6 @@ namespace PIbd_23_Gutorov_I.A._IT_Company container.RegisterType(); container.RegisterType(); container.RegisterType(); - container.RegisterType(); container.RegisterType(); diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs deleted file mode 100644 index 703736b..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs +++ /dev/null @@ -1,16 +0,0 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; - -namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories; - -public interface IServiceRepository -{ - IEnumerable ReadServices(int? contractId = null); - - Service ReadServiceById(int id); - - void CreateService(Service service); - - void UpdateService(Service service); - - void DeleteService(int id); -} diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs deleted file mode 100644 index c3af217..0000000 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs +++ /dev/null @@ -1,125 +0,0 @@ -using Dapper; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Npgsql; -using PIbd_23_Gutorov_I.A._IT_Company.Entities; - -namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; - -internal class ServiceRepository : IServiceRepository -{ - private readonly IConnectionString _connectionString; - private readonly ILogger _logger; - - public ServiceRepository(IConnectionString connectionString, ILogger logger) - { - _connectionString = connectionString; - _logger = logger; - } - - public void CreateService(Service service) - { - _logger.LogInformation("Добавление объекта"); - _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); - - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryInsert = @" - INSERT INTO Services (Description, ContractId) - VALUES (@Description, @ContractId); - "; - connection.Execute(queryInsert, service); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при добавлении объекта"); - throw; - } - } - - public void DeleteService(int id) - { - _logger.LogInformation("Удаление объекта"); - _logger.LogDebug("Объект: {id}", id); - - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryDelete = @" - DELETE FROM Services WHERE Id = @Id; - "; - connection.Execute(queryDelete, new { id }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при удалении объекта"); - throw; - } - } - - public Service ReadServiceById(int id) - { - _logger.LogInformation("Получение объекта по идентификатору"); - _logger.LogDebug("Объект: {id}", id); - - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @" - SELECT * FROM Services WHERE Id = @Id; - "; - var service = connection.QueryFirst(querySelect, new { id }); - _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(service)); - return service; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при поиске объекта"); - throw; - } - } - - public IEnumerable ReadServices(int? contractId = null) - { - _logger.LogInformation("Получение всех объектов"); - - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryInsert = @" - SELECT * FROM Services; - "; - var services = connection.Query(queryInsert); - _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(services)); - return services; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при чтении объектов"); - throw; - } - } - - public void UpdateService(Service service) - { - _logger.LogInformation("Редактирование объекта"); - _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); - - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryUpdate = @" - UPDATE Services - SET Description = @Description, ContractId = @ContractId - WHERE Id = @Id; - "; - connection.Execute(queryUpdate, service); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при редактировании объекта"); - throw; - } - } -} -- 2.25.1 From 4a12f3b1e478e6d9788bf87c386b5c23aebe0164 Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Mon, 25 Nov 2024 11:10:38 +0400 Subject: [PATCH 4/8] almost done, except customerexecutorreview... --- .../Forms/FormContract.cs | 7 +- .../Forms/FormCustomerExecutorReview.cs | 20 ++-- .../Implementations/ContractRepository.cs | 29 ++++-- .../CustomerExecutorReviewRepository.cs | 65 +++++++++++- .../Implementations/ExecutorRepository.cs | 99 ++++++++++++++++++- 5 files changed, 195 insertions(+), 25 deletions(-) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs index b2ceea6..a8edfe6 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs @@ -16,11 +16,11 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms comboBoxContractCustomerId.DataSource = customerRepository.ReadCustomers(); comboBoxContractCustomerId.DisplayMember = "Name"; - comboBoxContractCustomerId.DisplayMember = "Id"; + comboBoxContractCustomerId.ValueMember = "Id"; comboBoxContractExecutorId.DataSource = executorRepository.ReadExecutors(); comboBoxContractExecutorId.DisplayMember = "Name"; - comboBoxContractExecutorId.DisplayMember = "Id"; + comboBoxContractExecutorId.ValueMember = "Id"; foreach (var elem in Enum.GetValues(typeof(ContractCategory))) { @@ -71,10 +71,9 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms foreach (DataGridViewRow row in dataGridViewServices.Rows) if (!row.IsNewRow) - list.Add(Service.CreateEntity(0, Convert.ToString(row.Cells["Description"].Value)!, 0)); + list.Add(Service.CreateEntity(0, Convert.ToString(row.Cells["ColumnServiceDescription"].Value)!, 0)); return list; } - } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs index dcf0cef..ba849c6 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs @@ -11,15 +11,16 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms ICustomerRepository customerRepository, IExecutorRepository executorRepository) { InitializeComponent(); - _customerExecutorReviewRepository = customerExecutorReviewRepository ?? throw new ArgumentNullException(nameof(customerExecutorReviewRepository)); + _customerExecutorReviewRepository = customerExecutorReviewRepository ?? + throw new ArgumentNullException(nameof(customerExecutorReviewRepository)); comboBoxCustomerExecutorReviewCustomerId.DataSource = customerRepository.ReadCustomers(); comboBoxCustomerExecutorReviewCustomerId.DisplayMember = "Name"; - comboBoxCustomerExecutorReviewCustomerId.DisplayMember = "Id"; + comboBoxCustomerExecutorReviewCustomerId.ValueMember = "Id"; comboBoxCustomerExecutorReviewExecutorId.DataSource = executorRepository.ReadExecutors(); comboBoxCustomerExecutorReviewExecutorId.DisplayMember = "Name"; - comboBoxCustomerExecutorReviewCustomerId.DisplayMember = "Id"; + comboBoxCustomerExecutorReviewCustomerId.ValueMember = "Id"; } private void ButtonSave_Click(object sender, EventArgs e) @@ -33,9 +34,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms throw new Exception("Имеются незаполненные поля"); } - _customerExecutorReviewRepository.CreateCustomerExecutorReview(CustomerExecutorReview.CreateElement( - 0, (int)comboBoxCustomerExecutorReviewCustomerId.SelectedValue!, (int)comboBoxCustomerExecutorReviewExecutorId.SelectedValue!, - richTextBoxCustomerExecutorReviewReview.Text, Convert.ToInt32(numericUpDownCustomerExecutorReviewGrade.Value))); + _customerExecutorReviewRepository.CreateCustomerExecutorReview(CreateCustomerExecutorReview(0)); Close(); } @@ -46,5 +45,14 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); + + private CustomerExecutorReview CreateCustomerExecutorReview(int id) + { + return CustomerExecutorReview.CreateElement( + id, (int)comboBoxCustomerExecutorReviewCustomerId.SelectedValue!, + (int)comboBoxCustomerExecutorReviewExecutorId.SelectedValue!, + richTextBoxCustomerExecutorReviewReview.Text, + Convert.ToInt32(numericUpDownCustomerExecutorReviewGrade.Value)); + } } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index e1c6667..d909fb3 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -2,14 +2,12 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; -using System.Data.SqlClient; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; public class ContractRepository : IContractRepository { private readonly IConnectionString _connectionString; - private readonly ILogger _logger; public ContractRepository(IConnectionString connectionString, ILogger logger) @@ -27,10 +25,24 @@ public class ContractRepository : IContractRepository { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" - INSERT INTO Contracts (CustomerId, ExecutorId, Category, ConclusionDate, Deadline, PaymentAmount) - VALUES (@CustomerId, @ExecutorId, @Category, @ConclusionDate, @Deadline, @PaymentAmount)"; - connection.Execute(queryInsert, contract); + INSERT INTO Contracts (CustomerId, ExecutorId, Category, + ConclusionDate, Deadline, PaymentAmount) + VALUES (@CustomerId, @ExecutorId, @Category, + @ConclusionDate, @Deadline, @PaymentAmount); + SELECT MAX(Id) FROM Contracts; + "; + var contractId = connection.QueryFirst(queryInsert, contract, transaction); + + var querySubInsert = @" + INSERT INTO Services (Description, ContractId) + VALUES (@Description, @ContractId); + "; + foreach (var elem in contract.Services) + connection.Execute(querySubInsert, new { elem.Description, contractId }, transaction); + transaction.Commit(); } catch (Exception ex) { @@ -41,16 +53,16 @@ public class ContractRepository : IContractRepository public void DeleteContract(int id) { - _logger.LogInformation("Добавление объекта"); + _logger.LogInformation("Удаление объекта"); _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); var queryDelete = @" DELETE FROM Contracts - WHERE Id = @id"; + WHERE Id = @id + "; connection.Execute(queryDelete, new { id }); } catch (Exception ex) @@ -67,7 +79,6 @@ public class ContractRepository : IContractRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); var querySelect = @"SELECT * FROM Contracts"; var contracts = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts)); diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs index 24d341a..cefc193 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/CustomerExecutorReviewRepository.cs @@ -1,4 +1,7 @@ -using Microsoft.Extensions.Logging; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; @@ -8,17 +11,73 @@ public class CustomerExecutorReviewRepository : ICustomerExecutorReviewRepositor private readonly IConnectionString _connectionString; private readonly ILogger _logger; + public CustomerExecutorReviewRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateCustomerExecutorReview(CustomerExecutorReview customerContractReview) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customerContractReview)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO CustomerExecutorReviews (CustomerId, ExecutorId, Review, Grade) + VALUES (@CustomerId, @ExecutorId, @Review, @Grade); + "; + connection.Execute(queryInsert, customerContractReview); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public CustomerExecutorReview ReadCustomerExecutorReviewById(int id) { - return CustomerExecutorReview.CreateElement(0, 0, 0, string.Empty, 0); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM CustomerExecutorReviews WHERE Id = @Id; + "; + var customerEexcutorReview = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customerEexcutorReview)); + return customerEexcutorReview; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadCustomerExecutorReviews(int? customerId = null, int? executorId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM CustomerExecutorReviews; + "; + var customerExecutorReviews = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customerExecutorReviews)); + return customerExecutorReviews; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs index e1130a8..d4b663b 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ExecutorRepository.cs @@ -1,4 +1,7 @@ -using Microsoft.Extensions.Logging; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; using PIbd_23_Gutorov_I.A._IT_Company.Entities; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; @@ -8,25 +11,115 @@ public class ExecutorRepository : IExecutorRepository private readonly IConnectionString _connectionString; private readonly ILogger _logger; + public ExecutorRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateExecutor(Executor executor) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(executor)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Executors (Name, Post) + VALUES (@Name, @Post); + "; + connection.Execute(queryInsert, executor); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteExecutor(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Executors WHERE Id = @Id; + "; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Executor ReadExecutorById(int id) { - return Executor.CreateEntity(0, string.Empty, Entities.Enums.ExecutorPost.None); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Executors WHERE Id = @Id; + "; + var executor = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(executor)); + return executor; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadExecutors() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Executors; + "; + var executors = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(executors)); + return executors; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateExecutor(Executor executor) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(executor)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Executors + SET Name = @Name, Post = @Post + WHERE Id = @Id; + "; + connection.Execute(queryUpdate, executor); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } -- 2.25.1 From dbe7980c2f993d636654cf0748900757fa7f45ca Mon Sep 17 00:00:00 2001 From: vasmaae Date: Mon, 25 Nov 2024 00:29:54 -0800 Subject: [PATCH 5/8] fix customereditorreview issue --- .../Forms/FormCustomerExecutorReview.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs index ba849c6..1ea7260 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormCustomerExecutorReview.cs @@ -20,7 +20,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms comboBoxCustomerExecutorReviewExecutorId.DataSource = executorRepository.ReadExecutors(); comboBoxCustomerExecutorReviewExecutorId.DisplayMember = "Name"; - comboBoxCustomerExecutorReviewCustomerId.ValueMember = "Id"; + comboBoxCustomerExecutorReviewExecutorId.ValueMember = "Id"; } private void ButtonSave_Click(object sender, EventArgs e) -- 2.25.1 From 7d57c72997215beb5d940edbcc09c60c85a4de70 Mon Sep 17 00:00:00 2001 From: vasmaae Date: Mon, 25 Nov 2024 02:45:43 -0800 Subject: [PATCH 6/8] final (yeeeaaah) --- .../FormItCompany.Designer.cs | 64 ++++++---- .../Forms/FormContract.Designer.cs | 19 +-- .../Forms/FormContract.cs | 2 +- .../Forms/FormService.cs | 6 +- .../Forms/FormService.resx | 120 ++++++++++++++++++ PIbd-23_Gutorov_I.A._IT-Company/Program.cs | 1 + .../Repositories/IServiceRepository.cs | 4 +- .../Implementations/ContractRepository.cs | 10 +- .../Implementations/ServiceRepository.cs | 111 +++++++++++++++- 9 files changed, 285 insertions(+), 52 deletions(-) create mode 100644 PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx diff --git a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs index 75930b7..b70d236 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/FormItCompany.Designer.cs @@ -29,31 +29,32 @@ private void InitializeComponent() { menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); + EntitiesToolStripMenuItem = new ToolStripMenuItem(); CustomersToolStripMenuItem = new ToolStripMenuItem(); ExecutorsToolStripMenuItem = new ToolStripMenuItem(); - операцииToolStripMenuItem = new ToolStripMenuItem(); + ServicesToolStripMenuItem = new ToolStripMenuItem(); + OperationsToolStripMenuItem = new ToolStripMenuItem(); CustomerContractReviewsToolStripMenuItem = new ToolStripMenuItem(); - контрактыToolStripMenuItem = new ToolStripMenuItem(); - отчетыToolStripMenuItem = new ToolStripMenuItem(); + ContractsToolStripMenuItem = new ToolStripMenuItem(); + ReportsToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); SuspendLayout(); // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { EntitiesToolStripMenuItem, OperationsToolStripMenuItem, ReportsToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(734, 24); menuStrip.TabIndex = 0; menuStrip.Text = "menuStrip1"; // - // справочникиToolStripMenuItem + // EntitiesToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomersToolStripMenuItem, ExecutorsToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(94, 20); - справочникиToolStripMenuItem.Text = "Справочники"; + EntitiesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomersToolStripMenuItem, ExecutorsToolStripMenuItem, ServicesToolStripMenuItem }); + EntitiesToolStripMenuItem.Name = "EntitiesToolStripMenuItem"; + EntitiesToolStripMenuItem.Size = new Size(94, 20); + EntitiesToolStripMenuItem.Text = "Справочники"; // // CustomersToolStripMenuItem // @@ -69,12 +70,19 @@ ExecutorsToolStripMenuItem.Text = "Исполнители"; ExecutorsToolStripMenuItem.Click += ExecutorsToolStripMenuItem_Click; // - // операцииToolStripMenuItem + // ServicesToolStripMenuItem // - операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomerContractReviewsToolStripMenuItem, контрактыToolStripMenuItem }); - операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; - операцииToolStripMenuItem.Size = new Size(75, 20); - операцииToolStripMenuItem.Text = "Операции"; + ServicesToolStripMenuItem.Name = "ServicesToolStripMenuItem"; + ServicesToolStripMenuItem.Size = new Size(180, 22); + ServicesToolStripMenuItem.Text = "Услуги"; + ServicesToolStripMenuItem.Click += ServicesToolStripMenuItem_Click; + // + // OperationsToolStripMenuItem + // + OperationsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { CustomerContractReviewsToolStripMenuItem, ContractsToolStripMenuItem }); + OperationsToolStripMenuItem.Name = "OperationsToolStripMenuItem"; + OperationsToolStripMenuItem.Size = new Size(75, 20); + OperationsToolStripMenuItem.Text = "Операции"; // // CustomerContractReviewsToolStripMenuItem // @@ -83,18 +91,18 @@ CustomerContractReviewsToolStripMenuItem.Text = "Отзывы заказчиков"; CustomerContractReviewsToolStripMenuItem.Click += CustomerContractReviewsToolStripMenuItem_Click; // - // контрактыToolStripMenuItem + // ContractsToolStripMenuItem // - контрактыToolStripMenuItem.Name = "контрактыToolStripMenuItem"; - контрактыToolStripMenuItem.Size = new Size(181, 22); - контрактыToolStripMenuItem.Text = "Контракты"; - контрактыToolStripMenuItem.Click += ContractsToolStripMenuItem_Click; + ContractsToolStripMenuItem.Name = "ContractsToolStripMenuItem"; + ContractsToolStripMenuItem.Size = new Size(181, 22); + ContractsToolStripMenuItem.Text = "Контракты"; + ContractsToolStripMenuItem.Click += ContractsToolStripMenuItem_Click; // - // отчетыToolStripMenuItem + // ReportsToolStripMenuItem // - отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; - отчетыToolStripMenuItem.Size = new Size(60, 20); - отчетыToolStripMenuItem.Text = "Отчеты"; + ReportsToolStripMenuItem.Name = "ReportsToolStripMenuItem"; + ReportsToolStripMenuItem.Size = new Size(60, 20); + ReportsToolStripMenuItem.Text = "Отчеты"; // // FormItCompany // @@ -117,13 +125,13 @@ #endregion private MenuStrip menuStrip; - private ToolStripMenuItem справочникиToolStripMenuItem; + private ToolStripMenuItem EntitiesToolStripMenuItem; private ToolStripMenuItem CustomersToolStripMenuItem; private ToolStripMenuItem ExecutorsToolStripMenuItem; - private ToolStripMenuItem операцииToolStripMenuItem; - private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem OperationsToolStripMenuItem; + private ToolStripMenuItem ReportsToolStripMenuItem; private ToolStripMenuItem CustomerContractReviewsToolStripMenuItem; - private ToolStripMenuItem контрактыToolStripMenuItem; + private ToolStripMenuItem ContractsToolStripMenuItem; private ToolStripMenuItem ServicesToolStripMenuItem; } } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs index 165e71c..e694e67 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.Designer.cs @@ -41,8 +41,8 @@ labelContractDeadline = new Label(); labelContractPaymentAmount = new Label(); dataGridViewServices = new DataGridView(); + ColumnServiceDescription = new DataGridViewComboBoxColumn(); groupBox = new GroupBox(); - ColumnServiceDescription = new DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)numericUpDownContractPaymentAmount).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridViewServices).BeginInit(); groupBox.SuspendLayout(); @@ -172,6 +172,14 @@ dataGridViewServices.Size = new Size(352, 244); dataGridViewServices.TabIndex = 17; // + // ColumnServiceDescription + // + ColumnServiceDescription.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnServiceDescription.HeaderText = "Услуга"; + ColumnServiceDescription.Name = "ColumnServiceDescription"; + ColumnServiceDescription.Resizable = DataGridViewTriState.True; + ColumnServiceDescription.SortMode = DataGridViewColumnSortMode.Automatic; + // // groupBox // groupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; @@ -183,13 +191,6 @@ groupBox.TabStop = false; groupBox.Text = "Услуги:"; // - // ColumnServiceDescription - // - ColumnServiceDescription.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - ColumnServiceDescription.HeaderText = "Услуга"; - ColumnServiceDescription.Name = "ColumnServiceDescription"; - ColumnServiceDescription.Resizable = DataGridViewTriState.True; - // // FormContract // AutoScaleDimensions = new SizeF(7F, 15F); @@ -234,6 +235,6 @@ private Label labelContractPaymentAmount; private DataGridView dataGridViewServices; private GroupBox groupBox; - private DataGridViewTextBoxColumn ColumnServiceDescription; + private DataGridViewComboBoxColumn ColumnServiceDescription; } } \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs index d883750..6271a08 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormContract.cs @@ -9,7 +9,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms private readonly IContractRepository _contractRepository; public FormContract(IContractRepository contractRepository, ICustomerRepository customerRepository, - IExecutorRepository executorRepository) + IExecutorRepository executorRepository, IServiceRepository serviceRepository) { InitializeComponent(); _contractRepository = contractRepository ?? throw new ArgumentNullException(nameof(contractRepository)); diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs index 6831fd9..2d41b29 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.cs @@ -41,9 +41,9 @@ namespace PIbd_23_Gutorov_I.A._IT_Company.Forms { if (string.IsNullOrEmpty(richTextBoxServiceDescription.Text)) throw new Exception("Имеются незаполненные поля"); - - _serviceRepository.CreateService(Service.CreateEntity(0, - richTextBoxServiceDescription.Text)); + + if (_serviceId.HasValue) _serviceRepository.UpdateService(Service.CreateEntity(_serviceId.Value, richTextBoxServiceDescription.Text)); + else _serviceRepository.CreateService(Service.CreateEntity(0, richTextBoxServiceDescription.Text)); Close(); } diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/PIbd-23_Gutorov_I.A._IT-Company/Forms/FormService.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs index a253ffa..8114fc4 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Program.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Program.cs @@ -32,6 +32,7 @@ namespace PIbd_23_Gutorov_I.A._IT_Company container.RegisterType(); container.RegisterType(); container.RegisterType(); + container.RegisterType(); container.RegisterType(); diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs index aa261c0..99d3a4f 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/IServiceRepository.cs @@ -8,9 +8,9 @@ public interface IServiceRepository Service ReadServiceById(int id); - void CreateService(Service Service); + void CreateService(Service service); - void UpdateService(Service Service); + void UpdateService(Service service); void DeleteService(int id); } \ No newline at end of file diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index d909fb3..3b69512 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -37,11 +37,15 @@ public class ContractRepository : IContractRepository var contractId = connection.QueryFirst(queryInsert, contract, transaction); var querySubInsert = @" - INSERT INTO Services (Description, ContractId) - VALUES (@Description, @ContractId); + INSERT INTO ServiceContract (ServiceId, ContractId) + VALUES (@ServiceId, @ContractId); "; foreach (var elem in contract.Services) - connection.Execute(querySubInsert, new { elem.Description, contractId }, transaction); + { + var serviceId = elem.Id; + connection.Execute(querySubInsert, new { serviceId, contractId }, transaction); + } + transaction.Commit(); } catch (Exception ex) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs index 922a9fc..85718cb 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ServiceRepository.cs @@ -1,28 +1,127 @@ -using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using PIbd_23_Gutorov_I.A._IT_Company.Entities; +using System.CodeDom.Compiler; namespace PIbd_23_Gutorov_I.A._IT_Company.Repositories.Implementations; -internal class ServiceRepository : IServiceRepository +public class ServiceRepository : IServiceRepository { - public void CreateService(Service Service) + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ServiceRepository(IConnectionString connectionString, ILogger logger) { + _connectionString = connectionString; + _logger = logger; + } + + + public void CreateService(Service service) + { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Services (Description) + VALUES (@Description); + "; + connection.Execute(queryInsert, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteService(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Services WHERE Id = @Id; + "; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Service ReadServiceById(int id) { - return Service.CreateEntity(0, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Services WHERE Id = @Id; + "; + var service = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(service)); + return service; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadServices() { - return []; + _logger.LogInformation("Получение всех объектов"); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Services; + "; + var services = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(services)); + return services; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } - public void UpdateService(Service Service) + public void UpdateService(Service service) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(service)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Services + SET Description = @Description + WHERE Id = @Id; + "; + connection.Execute(queryUpdate, service); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } \ No newline at end of file -- 2.25.1 From d446aae8eb1a5f52f8019833e9bb2e957e593e44 Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Sun, 8 Dec 2024 21:16:46 +0400 Subject: [PATCH 7/8] fix ReadContracts log message --- .../Repositories/Implementations/ContractRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index 3b69512..2c79f9f 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -90,7 +90,7 @@ public class ContractRepository : IContractRepository } catch (Exception ex) { - _logger.LogError(ex, "Ошибка при удалении объекта"); + _logger.LogError(ex, "Ошибка при чтении объекта"); throw; } } -- 2.25.1 From d79c14c0ee31841aeec3b34d4c1d0dbe264f8b5c Mon Sep 17 00:00:00 2001 From: Ivan Gutorov Date: Sun, 8 Dec 2024 21:16:46 +0400 Subject: [PATCH 8/8] fix ReadContracts log message --- .../Repositories/Implementations/ContractRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs index 3b69512..c6a8c40 100644 --- a/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs +++ b/PIbd-23_Gutorov_I.A._IT-Company/Repositories/Implementations/ContractRepository.cs @@ -90,7 +90,7 @@ public class ContractRepository : IContractRepository } catch (Exception ex) { - _logger.LogError(ex, "Ошибка при удалении объекта"); + _logger.LogError(ex, "Ошибка при чтении объектов"); throw; } } -- 2.25.1