diff --git a/ProjectRepairWork/Entities/Enums/MaterialsName.cs b/ProjectRepairWork/Entities/Enums/MaterialsName.cs index 05bf497..2636d1f 100644 --- a/ProjectRepairWork/Entities/Enums/MaterialsName.cs +++ b/ProjectRepairWork/Entities/Enums/MaterialsName.cs @@ -14,10 +14,10 @@ public enum MaterialsName Wallpaper = 2, // обои - Paints = 3, // краски + Paints = 4, // краски - Furniture = 4, // мебель + Furniture = 8, // мебель - Windows = 5, // окна + Windows = 16, // окна } diff --git a/ProjectRepairWork/FormRepairWork.cs b/ProjectRepairWork/FormRepairWork.cs index 78d7742..2762be8 100644 --- a/ProjectRepairWork/FormRepairWork.cs +++ b/ProjectRepairWork/FormRepairWork.cs @@ -29,7 +29,7 @@ namespace ProjectRepairWork { try { - _container.Resolve().ShowDialog(); + _container.Resolve().ShowDialog(); } catch (Exception ex) { diff --git a/ProjectRepairWork/Forms/FormContractors.cs b/ProjectRepairWork/Forms/FormContractors.cs index ec739c8..c19f219 100644 --- a/ProjectRepairWork/Forms/FormContractors.cs +++ b/ProjectRepairWork/Forms/FormContractors.cs @@ -18,12 +18,12 @@ namespace ProjectRepairWork.Forms { private readonly IUnityContainer _container; private readonly IContractorsRepository _contractorsRepository; - public FormContractors(IUnityContainer container, IContractorsRepository premisesRepository) + public FormContractors(IUnityContainer container, IContractorsRepository contractorsRepository) { InitializeComponent(); _container = container ?? throw new ArgumentNullException(nameof(container)); - _contractorsRepository = premisesRepository ?? throw new ArgumentNullException(nameof(premisesRepository)); + _contractorsRepository = contractorsRepository ?? throw new ArgumentNullException(nameof(contractorsRepository)); } private void FormContractors_Load(object sender, EventArgs e) @@ -59,7 +59,7 @@ namespace ProjectRepairWork.Forms } try { - var form = _container.Resolve(); + var form = _container.Resolve(); form.Id = findId; form.ShowDialog(); LoadList(); diff --git a/ProjectRepairWork/Forms/FormCost.Designer.cs b/ProjectRepairWork/Forms/FormCost.Designer.cs index 7b78b2c..01368f0 100644 --- a/ProjectRepairWork/Forms/FormCost.Designer.cs +++ b/ProjectRepairWork/Forms/FormCost.Designer.cs @@ -58,6 +58,7 @@ // numericUpDownPrice // numericUpDownPrice.Location = new Point(180, 97); + numericUpDownPrice.Maximum = new decimal(new int[] { 100000, 0, 0, 0 }); numericUpDownPrice.Name = "numericUpDownPrice"; numericUpDownPrice.Size = new Size(200, 27); numericUpDownPrice.TabIndex = 14; diff --git a/ProjectRepairWork/Forms/FormCost.cs b/ProjectRepairWork/Forms/FormCost.cs index 735b3aa..1888672 100644 --- a/ProjectRepairWork/Forms/FormCost.cs +++ b/ProjectRepairWork/Forms/FormCost.cs @@ -18,12 +18,12 @@ namespace ProjectRepairWork.Forms { try { - var premises = _costRepository.ReadCostById(value); - if (premises == null) + var cost = _costRepository.ReadCostById(value); + if (cost == null) { - throw new InvalidDataException(nameof(premises)); + throw new InvalidDataException(nameof(cost)); } - numericUpDownPrice.Value = (decimal)premises.Price; + numericUpDownPrice.Value = (decimal)cost.Price; _costId = value; } catch (Exception ex) diff --git a/ProjectRepairWork/Forms/FormCosts.cs b/ProjectRepairWork/Forms/FormCosts.cs index 9bc3699..770dc14 100644 --- a/ProjectRepairWork/Forms/FormCosts.cs +++ b/ProjectRepairWork/Forms/FormCosts.cs @@ -47,7 +47,7 @@ namespace ProjectRepairWork.Forms } try { - var form = _container.Resolve(); + var form = _container.Resolve(); form.Id = findId; form.ShowDialog(); LoadList(); diff --git a/ProjectRepairWork/Forms/FormPremise.cs b/ProjectRepairWork/Forms/FormPremise.cs index 3be6dde..fdff255 100644 --- a/ProjectRepairWork/Forms/FormPremise.cs +++ b/ProjectRepairWork/Forms/FormPremise.cs @@ -25,8 +25,8 @@ namespace ProjectRepairWork.Forms textBoxClientName.Text = premises.ClientName; textBoxAddress.Text = premises.Address; numericUpDownArea.Value = (decimal)premises.Area; - dateTimePickerStart.Value = DateTime.Now; - dateTimePickerEnd.Value = DateTime.Now; + dateTimePickerStart.Value = premises.DateStart; + dateTimePickerEnd.Value = premises.DateEnd; comboBoxPremisesType.SelectedItem = premises.PremisesType; _premisesId = value; } @@ -81,7 +81,7 @@ namespace ProjectRepairWork.Forms textBoxClientName.Text, textBoxAddress.Text, Convert.ToInt32(numericUpDownArea.Value), - dateTimePickerStart.Value, dateTimePickerStart.Value, (PremisesType)comboBoxPremisesType.SelectedItem!); + dateTimePickerStart.Value, dateTimePickerEnd.Value, (PremisesType)comboBoxPremisesType.SelectedItem!); } diff --git a/ProjectRepairWork/Forms/FormRepair.cs b/ProjectRepairWork/Forms/FormRepair.cs index bd8fe15..a23c794 100644 --- a/ProjectRepairWork/Forms/FormRepair.cs +++ b/ProjectRepairWork/Forms/FormRepair.cs @@ -10,7 +10,7 @@ namespace ProjectRepairWork.Forms { private readonly IRepairRepository _repairRepository; - public FormRepair(IRepairRepository repairRepository, IContractorsRepository contractorsRepository, ICostRepository costRepository, IPremisesRepository premisesRepository, IWorksRepository worksRepository) + public FormRepair(IRepairRepository repairRepository, IContractorsRepository contractorsRepository, IPremisesRepository premisesRepository, IWorksRepository worksRepository) { InitializeComponent(); _repairRepository = repairRepository ?? throw new ArgumentNullException(nameof(repairRepository)); @@ -22,11 +22,11 @@ namespace ProjectRepairWork.Forms comboBoxContractors.ValueMember = "Id"; comboBoxPremises.DataSource = premisesRepository.ReadPremises(); - comboBoxPremises.DisplayMember = "Name"; + comboBoxPremises.DisplayMember = "ClientName"; comboBoxPremises.ValueMember = "Id"; ColumnWork.DataSource = worksRepository.ReadWorks(); - ColumnWork.DisplayMember = "Name"; + ColumnWork.DisplayMember = "WorkName"; ColumnWork.ValueMember = "Id"; diff --git a/ProjectRepairWork/Forms/FormWorks.cs b/ProjectRepairWork/Forms/FormWorks.cs index de7b8c3..a079259 100644 --- a/ProjectRepairWork/Forms/FormWorks.cs +++ b/ProjectRepairWork/Forms/FormWorks.cs @@ -45,7 +45,7 @@ namespace ProjectRepairWork.Forms } try { - var form = _container.Resolve(); + var form = _container.Resolve(); form.Id = findId; form.ShowDialog(); LoadList(); diff --git a/ProjectRepairWork/Program.cs b/ProjectRepairWork/Program.cs index df37fa6..947f6d1 100644 --- a/ProjectRepairWork/Program.cs +++ b/ProjectRepairWork/Program.cs @@ -2,6 +2,10 @@ using Unity; using ProjectRepairWork.Repositories; using ProjectRepairWork.Repositories.Implementation; using Unity.Lifetime; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; +using Unity.Microsoft.Logging; namespace ProjectRepairWork { internal static class Program @@ -19,14 +23,31 @@ namespace ProjectRepairWork } private static IUnityContainer CreateContainer() { - var container = new UnityContainer(); - container.RegisterType(new TransientLifetimeManager()); - container.RegisterType(new TransientLifetimeManager()); - container.RegisterType(new TransientLifetimeManager()); - container.RegisterType(new TransientLifetimeManager()); - container.RegisterType(new TransientLifetimeManager()); + var container = new UnityContainer() + .AddExtension(new Diagnostic()); + + 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/ProjectRepairWork/ProjectRepairWork.csproj b/ProjectRepairWork/ProjectRepairWork.csproj index accbdf0..ebed082 100644 --- a/ProjectRepairWork/ProjectRepairWork.csproj +++ b/ProjectRepairWork/ProjectRepairWork.csproj @@ -9,7 +9,19 @@ + + + + + + + + + + + + @@ -27,4 +39,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectRepairWork/Repositories/IConnectionString.cs b/ProjectRepairWork/Repositories/IConnectionString.cs new file mode 100644 index 0000000..6d5a6cb --- /dev/null +++ b/ProjectRepairWork/Repositories/IConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRepairWork.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/ProjectRepairWork/Repositories/Implementation/ConnectionString.cs b/ProjectRepairWork/Repositories/Implementation/ConnectionString.cs new file mode 100644 index 0000000..ae919e7 --- /dev/null +++ b/ProjectRepairWork/Repositories/Implementation/ConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRepairWork.Repositories.Implementation; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=12345;Database=OTP;"; +} diff --git a/ProjectRepairWork/Repositories/Implementation/ContractorsRepository.cs b/ProjectRepairWork/Repositories/Implementation/ContractorsRepository.cs index c88b4dc..481819d 100644 --- a/ProjectRepairWork/Repositories/Implementation/ContractorsRepository.cs +++ b/ProjectRepairWork/Repositories/Implementation/ContractorsRepository.cs @@ -1,4 +1,8 @@ -using ProjectRepairWork.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectRepairWork.Entities; using ProjectRepairWork.Entities.Enums; using System; using System.Collections.Generic; @@ -10,28 +14,115 @@ namespace ProjectRepairWork.Repositories.Implementation; public class ContractorsRepository : IContractorsRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public ContractorsRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateContractors(Contractors contractors) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(contractors)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO Contractors (companyName, Contacts) +VALUES (@CompanyName, @Contacts)"; + connection.Execute(queryInsert, contractors); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateContractors(Contractors contractors) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(contractors)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Contractors + SET + CompanyName=@CompanyName, + Contacts=@Contacts + WHERE Id=@Id"; + connection.Execute(queryUpdate, contractors); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeletedContractors(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Contractors + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadContractors() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Contractors"; + var contractors = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(contractors)); + return contractors; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Contractors ReadContractorsById(int id) { - return Contractors.CreatEntity(0, string.Empty, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Contractors + WHERE Id=@id"; + var contractors = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(contractors)); + return contractors; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } - public void UpdateContractors(Contractors contractors) - { - - } + } diff --git a/ProjectRepairWork/Repositories/Implementation/CostRepository.cs b/ProjectRepairWork/Repositories/Implementation/CostRepository.cs index 517b326..04c83c5 100644 --- a/ProjectRepairWork/Repositories/Implementation/CostRepository.cs +++ b/ProjectRepairWork/Repositories/Implementation/CostRepository.cs @@ -1,4 +1,8 @@ -using ProjectRepairWork.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectRepairWork.Entities; using ProjectRepairWork.Entities.Enums; using System; using System.Collections.Generic; @@ -10,28 +14,115 @@ namespace ProjectRepairWork.Repositories.Implementation; public class CostRepository : ICostRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public CostRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateCost(Cost cost) { - + + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cost)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO Cost (Price) +VALUES (@Price)"; + connection.Execute(queryInsert, cost); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeletedCost(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Cost + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadCost() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Cost"; + var cost = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(cost)); + return cost; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Cost ReadCostById(int id) { - return Cost.CreatEntity(0, 0); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Cost + WHERE Id=@id"; + var cost = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(cost)); + return cost; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdateCost(Cost cost) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(cost)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Cost + SET + Price=@Price + WHERE Id=@Id"; + connection.Execute(queryUpdate, cost); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectRepairWork/Repositories/Implementation/PremisesRepository.cs b/ProjectRepairWork/Repositories/Implementation/PremisesRepository.cs index 4a48547..d4f5199 100644 --- a/ProjectRepairWork/Repositories/Implementation/PremisesRepository.cs +++ b/ProjectRepairWork/Repositories/Implementation/PremisesRepository.cs @@ -1,4 +1,8 @@ -using ProjectRepairWork.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectRepairWork.Entities; using ProjectRepairWork.Entities.Enums; using System; using System.Collections.Generic; @@ -9,27 +13,120 @@ using System.Threading.Tasks; namespace ProjectRepairWork.Repositories.Implementation; public class PremisesRepository : IPremisesRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public PremisesRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreatePremises(Premises premises) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(premises)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + + var queryInsert = @" +INSERT INTO Premises (ClientName, Address, Area, DateStart, DateEnd, PremisesType) +VALUES (@ClientName,@Address,@Area,@DateStart,@DateEnd,@PremisesType)"; + connection.Execute(queryInsert, premises); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeletePremises(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Premises + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadPremises() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Premises"; + var premises = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(premises)); + return premises; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Premises ReadPremisesById(int id) { - return Premises.CreatEntity(0, string.Empty, string.Empty, 0, DateTime.Now, DateTime.Now, PremisesType.None); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Premises + WHERE Id=@id"; + var premises = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(premises)); + return premises; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdatePremises(Premises premises) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(premises)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Premises + SET + ClientName = @ClientName, + Address = @Address, + Area = @Area, + DateStart = @DateStart, + DateEnd = @DateEnd, + PremisesType = @PremisesType + WHERE Id=@Id"; + connection.Execute(queryUpdate, premises); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectRepairWork/Repositories/Implementation/RepairRepository.cs b/ProjectRepairWork/Repositories/Implementation/RepairRepository.cs index a98f3ac..5612bc4 100644 --- a/ProjectRepairWork/Repositories/Implementation/RepairRepository.cs +++ b/ProjectRepairWork/Repositories/Implementation/RepairRepository.cs @@ -1,4 +1,8 @@ -using ProjectRepairWork.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectRepairWork.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,13 +13,68 @@ namespace ProjectRepairWork.Repositories.Implementation; public class RepairRepository : IRepairRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public RepairRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CraeteRepair(Repair repair) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(repair)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO Repair (ContractorsId, PremisesId) + VALUES (@ContractorsId, @PremisesId); + SELECT MAX(Id) FROM Repair"; + var repairId = + connection.QueryFirst(queryInsert, repair, transaction); + var querySubInsert = @" + INSERT INTO RepairRepair (RepairId, WorkId, Count) + VALUES (@RepairId, @WorkId, @Count)"; + foreach (var elem in repair.RepairRepair) + { + connection.Execute(querySubInsert, new + { + repairId, + elem.WorkId, + elem.Count + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadRepair(int? contractorsId = null, int? costId = null, int? worksId = null, int? premisesId = null) { - return[]; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Repair"; + var repair = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(repair)); + return repair; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectRepairWork/Repositories/Implementation/WorksRepository.cs b/ProjectRepairWork/Repositories/Implementation/WorksRepository.cs index 2857579..af60249 100644 --- a/ProjectRepairWork/Repositories/Implementation/WorksRepository.cs +++ b/ProjectRepairWork/Repositories/Implementation/WorksRepository.cs @@ -1,4 +1,8 @@ -using ProjectRepairWork.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectRepairWork.Entities; using ProjectRepairWork.Entities.Enums; using System; using System.Collections.Generic; @@ -10,28 +14,115 @@ namespace ProjectRepairWork.Repositories.Implementation; public class WorksRepository : IWorksRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public WorksRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateWorks(Works works) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(works)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO Works (WorkName, MaterialsName) +VALUES (@WorkName, @MaterialsName)"; + connection.Execute(queryInsert, works); + } + + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteWorks(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Works + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadWorks() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Works"; + var works = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(works)); + return works; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Works ReadWorksById(int id) { - return Works.CreatEntity(0,string.Empty, MaterialsName.None); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Works + WHERE Id=@id"; + var works = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(works)); + return works; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public void UpdateWorks(Works works) { - + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(works)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Works + SET + WorkName=@WorkName, + MaterialsName=@MaterialsName + WHERE Id=@Id"; + connection.Execute(queryUpdate, works); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectRepairWork/appsettings.json b/ProjectRepairWork/appsettings.json new file mode 100644 index 0000000..540cd04 --- /dev/null +++ b/ProjectRepairWork/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file