labwork2WIP

This commit is contained in:
Ctepa 2024-12-06 12:01:27 +04:00
parent afafe3814f
commit 0daf6ae715
21 changed files with 468 additions and 50 deletions

View File

@ -6,6 +6,7 @@ public class Materials
public int Id { get; set; } public int Id { get; set; }
public DateTime DateMaterials { get; set; } public DateTime DateMaterials { get; set; }
public int Count { get; set; } public int Count { get; set; }
public TypeMaterials Material { get; set; } public TypeMaterials Material { get; set; }
public static Materials CreateEntity(int id, DateTime dateMaterials, int count, TypeMaterials typeMaterials) public static Materials CreateEntity(int id, DateTime dateMaterials, int count, TypeMaterials typeMaterials)

View File

@ -11,7 +11,7 @@ public class PrintingHouses
public IEnumerable<PrintingHouseOrders> printingHouseOrder { get; set; } = []; public IEnumerable<PrintingHouseOrders> printingHouseOrder { get; set; } = [];
public static PrintingHouses CreateEntity(int id, string title, string phone, string address,IEnumerable<PrintingHouseOrders> printingHouseOrders) public static PrintingHouses CreateEntity(int id, string title, string phone, string address,int materialsId,IEnumerable<PrintingHouseOrders> printingHouseOrders)
{ {
return new PrintingHouses return new PrintingHouses
@ -20,6 +20,7 @@ public class PrintingHouses
Title = title, Title = title,
Phone = phone, Phone = phone,
Address = address, Address = address,
MaterialsId=materialsId,
printingHouseOrder = printingHouseOrders printingHouseOrder = printingHouseOrders
}; };
} }

View File

@ -63,7 +63,7 @@ public partial class FormCustomer : Form
else else
{ {
customerRepository.CreateCustomer(CreateCustomer(0)); customerRepository.CreateCustomer(CreateCustomer(1));
} }
Close(); Close();

View File

@ -126,7 +126,6 @@
Name = "FormMaterial"; Name = "FormMaterial";
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
Text = "FormMaterials"; Text = "FormMaterials";
Load += FormMaterials_Load;
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit(); ((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();

View File

@ -40,8 +40,9 @@ public partial class FormMaterial : Form
checkedListBox1.SetItemChecked(checkedListBox1.Items.IndexOf(elem), true); checkedListBox1.SetItemChecked(checkedListBox1.Items.IndexOf(elem), true);
} }
} }
material.DateMaterials = dateTimePickerDateMaterial.Value.Date; MessageBox.Show(material.DateMaterials.ToString());
material.Count = int.Parse(numericUpDownCount.Value.ToString()); numericUpDownCount.Value=material.Count;
dateTimePickerDateMaterial.Value = material.DateMaterials;
materialId = value; materialId = value;
} }
catch (Exception ex) catch (Exception ex)
@ -62,16 +63,13 @@ public partial class FormMaterial : Form
} }
} }
private void FormMaterials_Load(object sender, EventArgs e)
{
}
private void ButtonSave_Click(object sender, EventArgs e) private void ButtonSave_Click(object sender, EventArgs e)
{ {
try try
{ {
if (int.Parse(numericUpDownCount.Value.ToString()) <= 0 || dateTimePickerDateMaterial.Value.Date < DateTime.Now || checkedListBox1.SelectedItems.Count == 0) if (int.Parse(numericUpDownCount.Value.ToString()) <= 0 || dateTimePickerDateMaterial.Value.Date <= DateTime.Now || checkedListBox1.SelectedItems.Count == 0)
{ {
throw new Exception("Имеются незаполненные поля"); throw new Exception("Имеются незаполненные поля");
} }
@ -84,7 +82,7 @@ public partial class FormMaterial : Form
else else
{ {
materialRepository.CreateMaterial(CreateMaterials(0)); materialRepository.CreateMaterial(CreateMaterials(1));
} }
Close(); Close();
@ -103,6 +101,7 @@ public partial class FormMaterial : Form
{ {
typeMaterials |= (TypeMaterials)elem; typeMaterials |= (TypeMaterials)elem;
} }
return Materials.CreateEntity(id, dateTimePickerDateMaterial.Value.Date, int.Parse(numericUpDownCount.Value.ToString()), typeMaterials); MessageBox.Show(dateTimePickerDateMaterial.Value.ToString());
return Materials.CreateEntity(id, dateTimePickerDateMaterial.Value, (int)numericUpDownCount.Value, typeMaterials);
} }
} }

View File

@ -40,6 +40,7 @@ public partial class FormMaterials : Form
{ {
if (!TryGetIdentifierFromSelectedRow(out var findId)) if (!TryGetIdentifierFromSelectedRow(out var findId))
{ {
MessageBox.Show("Привет", "Привет");
return; return;
} }
try try
@ -99,8 +100,7 @@ public partial class FormMaterials : Form
return false; return false;
} }
id = id =Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);
return true; return true;
} }

View File

@ -40,10 +40,10 @@ public partial class FormOrder : Form
throw new Exception("Имеются незаполненные поля"); throw new Exception("Имеются незаполненные поля");
} }
orderRepository.CreateOrder(Orders.CreateEntity( orderRepository.CreateOrder(Orders.CreateEntity(
0, 1,
textBoxDescription.Text, textBoxDescription.Text,
(int)comboBoxCutomer.SelectedIndex, (int)comboBoxCutomer.SelectedValue!,
(int)comboBoxPublishingHouse.SelectedIndex (int)comboBoxPublishingHouse.SelectedValue!
)); ));
Close(); Close();
} }

View File

@ -105,6 +105,7 @@
// //
// comboBoxMaterials // comboBoxMaterials
// //
comboBoxMaterials.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxMaterials.FormattingEnabled = true; comboBoxMaterials.FormattingEnabled = true;
comboBoxMaterials.Location = new Point(129, 200); comboBoxMaterials.Location = new Point(129, 200);
comboBoxMaterials.Name = "comboBoxMaterials"; comboBoxMaterials.Name = "comboBoxMaterials";

View File

@ -45,17 +45,20 @@ public partial class FormPrintingHouse : Form
( (
PrintingHouses.CreateEntity PrintingHouses.CreateEntity
( (
0, 1,
textBoxTitle.Text, textBoxTitle.Text,
textBoxPhone.Text, textBoxPhone.Text,
textBoxAddress.Text, textBoxAddress.Text,
(int)comboBoxMaterials.SelectedValue!,
CreateListPrintingHouseOrdersFromDataGrid() CreateListPrintingHouseOrdersFromDataGrid()
) )
); );
Close();
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -72,7 +72,7 @@ public partial class FormPublishingHouse : Form
else else
{ {
publisingHouseRepository.CreatePublishingHouse(CreatePublishingHouse(0)); publisingHouseRepository.CreatePublishingHouse(CreatePublishingHouse(1));
} }
Close(); Close();

View File

@ -1,4 +1,7 @@
using Dapper;
using Npgsql;
using Publication.Forms; using Publication.Forms;
using System.Data.SqlClient;
using Unity; using Unity;
namespace Publication; namespace Publication;
@ -37,6 +40,7 @@ public partial class Publication : Form
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void PublishingHousesToolStripMenuItem_Click(object sender, EventArgs e) private void PublishingHousesToolStripMenuItem_Click(object sender, EventArgs e)

View File

@ -1,7 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Publication.Repositories; using Publication.Repositories;
using Publication.Repositories.Implementations; using Publication.Repositories.Implementations;
using Serilog;
using Unity; using Unity;
using Unity.Lifetime; using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace Publication namespace Publication
{ {
@ -23,12 +27,26 @@ namespace Publication
private static IUnityContainer CreateContainer() private static IUnityContainer CreateContainer()
{ {
var container = new UnityContainer(); var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<ICustomerRepository,CustomerRepository>(new TransientLifetimeManager()); container.RegisterType<ICustomerRepository,CustomerRepository>(new TransientLifetimeManager());
container.RegisterType<IMaterialRepository, MaterialRepository>(new TransientLifetimeManager()); container.RegisterType<IMaterialRepository, MaterialRepository>(new TransientLifetimeManager());
container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager()); container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager());
container.RegisterType<IPrintingHouseRepository, PrintingHouseRepository>(new TransientLifetimeManager()); container.RegisterType<IPrintingHouseRepository, PrintingHouseRepository>(new TransientLifetimeManager());
container.RegisterType<IPublisingHouseRepository, PublishingHouseRepository>(new TransientLifetimeManager()); container.RegisterType<IPublisingHouseRepository, PublishingHouseRepository>(new TransientLifetimeManager());
container.RegisterType<IConnectionRepository, ConnectionRepository>(new TransientLifetimeManager());
return container; return container;
} }
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("C:\\Users\\Ctepa\\source\\repos\\PIbd-21_Chechevitsyn_S.A_Simple\\Publication\\application.json")
.Build())
.CreateLogger());
return loggerFactory;
}
} }
} }

View File

@ -9,7 +9,19 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" /> <PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

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

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Publication.Repositories.Implementations;
public class ConnectionRepository : IConnectionRepository
{
public string GetConnection => "Host=localhost;UserName=postgres;Password=1234;Database=publication";
}

View File

@ -1,30 +1,115 @@
 
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using Publication.Entites;
using Serilog.Core;
using System.Data.SqlClient;
namespace Publication.Repositories.Implementations; namespace Publication.Repositories.Implementations;
public class CustomerRepository : ICustomerRepository public class CustomerRepository : ICustomerRepository
{ {
public void CreateCustomer(Customers customer) private readonly IConnectionRepository connectionRepository;
{
private readonly ILogger<ICustomerRepository> logger;
public CustomerRepository (IConnectionRepository connectionRepository, ILogger<ICustomerRepository> logger)
{
this.connectionRepository = connectionRepository;
this.logger = logger;
}
public void CreateCustomer(Customers customer)
{
logger.LogInformation("Добавление объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryInsert = @"INSERT INTO customer (FullName, Age, TypeCustomer, Phone, Email)
VALUES (@FullName, @Age, @TypeCustomer, @Phone, @Email)";
connection.Execute(queryInsert, customer);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeleteCustomer(int id) public void DeleteCustomer(int id)
{ {
logger.LogInformation("Удаление объекта");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryDelete = @"DELETE FROM Customer WHERE id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public Customers ReadCustomerById(int id) public Customers ReadCustomerById(int id)
{ {
return Customers.CreateEntity(0, string.Empty, 0, Entites.Enums.TypeCustomers.None, string.Empty, string.Empty); logger.LogInformation("Получение объекта по идентификатору");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = @"SELECT * FROM Customer WHERE id=@Id";
var customer = connection.QueryFirst<Customers>(querySelect, new { id });
logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer));
return customer;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public IEnumerable<Customers> ReadCustomers() public IEnumerable<Customers> ReadCustomers()
{ {
return []; logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = "SELECT * FROM Customer";
var customer = connection.Query<Customers>(querySelect);
logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customer));
return customer;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public void UpdateCustomer(Customers customer) public void UpdateCustomer(Customers customer)
{ {
logger.LogInformation("Редактирование объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryUpdate = @"UPDATE Customer
SET fullName=@FullName, age=@Age, typeCustomer=@TypeCustomer, phone=@Phone, email=@Email
WHERE Id=@Id";
connection.Execute(queryUpdate, customer);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
} }

View File

@ -1,31 +1,110 @@
using Publication.Entites; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Publication.Entites;
using System.Text.Json.Serialization;
namespace Publication.Repositories.Implementations; namespace Publication.Repositories.Implementations;
public class MaterialRepository : IMaterialRepository public class MaterialRepository : IMaterialRepository
{ {
private readonly IConnectionRepository connectionRepository;
private readonly ILogger<MaterialRepository> logger;
public MaterialRepository(IConnectionRepository connectionRepository, ILogger<MaterialRepository> logger)
{
this.connectionRepository = connectionRepository;
this.logger = logger;
}
public void CreateMaterial(Materials material) public void CreateMaterial(Materials material)
{ {
logger.LogInformation("Добавление объекта");
logger.LogDebug("Объект: {json}",JsonConvert.SerializeObject(material));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryInsert = @"INSERT INTO Material(datematerials,count,material) VALUES
(@DateMaterials,@Count,@Material)";
connection.Execute(queryInsert, material);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeleteMaterial(int id) public void DeleteMaterial(int id)
{ {
logger.LogInformation("Удаление объекта");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryDelete = @"DELETE FROM Material WHERE id=@Id";
connection.Execute(queryDelete, new {id});
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public Materials ReadMaterialById(int id) public Materials ReadMaterialById(int id)
{ {
return Materials.CreateEntity(0, DateTime.Now, 0, Entites.Enums.TypeMaterials.None); logger.LogInformation("Получение объекта по идентификатору");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = @"SELECT * FROM Material WHERE id=@Id";
var material = connection.QueryFirst<Materials>(querySelect, new { id });
logger.LogDebug("Найденный объект: {json}",JsonConvert.SerializeObject(material));
return material;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public IEnumerable<Materials> ReadMaterials() public IEnumerable<Materials> ReadMaterials()
{ {
return []; logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = "SELECT * FROM Material";
var materials = connection.Query<Materials>(querySelect);
logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials));
return materials;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public void UpdateMaterial(Materials material) public void UpdateMaterial(Materials material)
{ {
logger.LogInformation("Редактирование объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryUpdate = @"UPDATE Material
SET datematerials=@DateMaterials, count=@Count, material=@Material
WHERE Id=@Id";
connection.Execute(queryUpdate, material);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
} }

View File

@ -1,23 +1,57 @@
 using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Publication.Entites; using Publication.Entites;
using Dapper;
using System.Data.SqlClient;
namespace Publication.Repositories.Implementations; namespace Publication.Repositories.Implementations;
public class OrderRepository : IOrderRepository public class OrderRepository : IOrderRepository
{ {
private readonly IConnectionRepository connectionRepository;
private readonly ILogger<IOrderRepository> logger;
public OrderRepository(IConnectionRepository connectionRepository, ILogger<IOrderRepository> logger)
{
this.connectionRepository = connectionRepository;
this.logger = logger;
}
public void CreateOrder(Orders order) public void CreateOrder(Orders order)
{ {
logger.LogInformation("Добавление объекта");
} logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
try
public void DeleteOrder(int id) {
{ using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryInsert = @"INSERT INTO Orders (OrderDate, Description, CustomerId, PublishingHouseId)
VALUES (@OrderDate, @Description, @CustomerId, @PublishingHouseId)";
connection.Execute(queryInsert, order);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public IEnumerable<Orders> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? customerId = null, int? publishingHouseId = null) public IEnumerable<Orders> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? customerId = null, int? publishingHouseId = null)
{ {
return []; logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = "SELECT * FROM Orders";
var orders = connection.Query<Orders>(querySelect);
logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

View File

@ -1,21 +1,83 @@
using Publication.Entites; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Publication.Entites;
using Dapper;
namespace Publication.Repositories.Implementations; namespace Publication.Repositories.Implementations;
public class PrintingHouseRepository : IPrintingHouseRepository public class PrintingHouseRepository : IPrintingHouseRepository
{ {
private readonly IConnectionRepository connectionRepository;
private readonly ILogger<IPrintingHouseRepository> logger;
public PrintingHouseRepository(IConnectionRepository connectionRepository, ILogger<IPrintingHouseRepository> logger)
{
this.connectionRepository = connectionRepository;
this.logger = logger;
}
public void CreatePrintingHouse(PrintingHouses printerHouse) public void CreatePrintingHouse(PrintingHouses printerHouse)
{ {
logger.LogInformation("Добавление объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(printerHouse));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
connection.Open();
using var transaction=connection.BeginTransaction();
var queryInsert = @"INSERT INTO PrintingHouses (Title, Phone, Address, MaterialsId)
VALUES (@Title, @Phone, @Address, @MaterialsId);
SELECT MAX(Id) FROM PrintingHouses";
var printingHousesId = connection.QueryFirst<int>(queryInsert, printerHouse, transaction);
var querySubInsert = @"
INSERT INTO PrintingHouseOrders (PrintingHouseId,orderid,count)
VALUES (@PrintingHouseId,@OrderId,@Count)";
foreach (var item in printerHouse.printingHouseOrder)
{
connection.Execute(querySubInsert, new { printingHousesId, item.OrderId, item.Count }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeletePrintingHouse(int id) public void DeletePrintingHouse(int id)
{ {
logger.LogInformation("Удаление объекта");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryDelete = @"DELETE FROM PrintingHouses WHERE Id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public IEnumerable<PrintingHouses> ReadPrintingHouses(int? printingHouseId = null, string? printingHousePhone = null, string? printingHouseAddress = null, int? materialsId = null) public IEnumerable<PrintingHouses> ReadPrintingHouses(int? printingHouseId = null, string? printingHousePhone = null, string? printingHouseAddress = null, int? materialsId = null)
{ {
return []; logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = "SELECT * FROM PrintingHouses";
var printingHouses = connection.Query<PrintingHouses>(querySelect);
logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(printingHouses));
return printingHouses;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

View File

@ -1,31 +1,111 @@
using Publication.Entites; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Publication.Entites;
using Dapper;
namespace Publication.Repositories.Implementations; namespace Publication.Repositories.Implementations;
public class PublishingHouseRepository : IPublisingHouseRepository public class PublishingHouseRepository : IPublisingHouseRepository
{ {
private readonly IConnectionRepository connectionRepository;
private readonly ILogger<IPublisingHouseRepository> logger;
public PublishingHouseRepository(IConnectionRepository connectionRepository, ILogger<IPublisingHouseRepository> logger)
{
this.connectionRepository = connectionRepository;
this.logger = logger;
}
public void CreatePublishingHouse(PublishingHouse publishingHouse) public void CreatePublishingHouse(PublishingHouse publishingHouse)
{ {
logger.LogInformation("Добавление объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(publishingHouse));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryInsert = @"INSERT INTO PublishingHouse (title,address,workphone) VALUES
(@Title,@Address,@WorkPhone)";
connection.Execute(queryInsert, publishingHouse);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeletePublishingHouse(int id) public void DeletePublishingHouse(int id)
{ {
logger.LogInformation("Удаление объекта");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryDelete = @"DELETE FROM PublishingHouse WHERE id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public IEnumerable<PublishingHouse> ReadPublishingHouses() public IEnumerable<PublishingHouse> ReadPublishingHouses()
{ {
return []; logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = "SELECT * FROM PublishingHouse";
var publishingHouses = connection.Query<PublishingHouse>(querySelect);
logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(publishingHouses));
return publishingHouses;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public PublishingHouse ReadPublishingHouseById(int id) public PublishingHouse ReadPublishingHouseById(int id)
{ {
return PublishingHouse.CreateEntity(0, string.Empty,string.Empty,string.Empty); logger.LogInformation("Получение объекта по идентификатору");
logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var querySelect = @"SELECT * FROM PublishingHouse WHERE id=@Id";
var publishingHouse = connection.QueryFirst<PublishingHouse>(querySelect, new { id });
logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(publishingHouse));
return publishingHouse;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public void UpdatePublishingHouse(PublishingHouse publishingHouse) public void UpdatePublishingHouse(PublishingHouse publishingHouse)
{ {
logger.LogInformation("Редактирование объекта");
logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(publishingHouse));
try
{
using var connection = new NpgsqlConnection(connectionRepository.GetConnection);
var queryUpdate = @"UPDATE PublishingHouse
SET title=@Title, address=@Address, workphone=@WorkPhone
WHERE Id=@Id";
connection.Execute(queryUpdate, publishingHouse);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
} }

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Users\\Ctepa\\OneDrive\\Рабочий стол\\test.txt",
"rollingInterval": "Day"
}
}
]
}
}