ПИбд-22. Шурыгин Д.И. Лаб 2 #2
@ -5,7 +5,7 @@ public class Expenditure
|
||||
public int Id { get; private set; }
|
||||
public int ClothId { get; private set; }
|
||||
public double Value { get; private set; }
|
||||
public static Expenditure CreateOperation(int id, int clothId, double value)
|
||||
public static Expenditure CreateElement(int id, int clothId, double value)
|
||||
{
|
||||
return new Expenditure
|
||||
{
|
||||
|
@ -16,4 +16,14 @@ public class Model
|
||||
Expenditures = expenditures
|
||||
};
|
||||
}
|
||||
|
||||
public static Model CreateEntity(TempExpenditure tempExpenditure, IEnumerable<Expenditure> expenditures)
|
||||
{
|
||||
return new Model
|
||||
{
|
||||
Id = tempExpenditure.Id,
|
||||
ModelType = tempExpenditure.ModelType,
|
||||
Expenditures = expenditures
|
||||
};
|
||||
}
|
||||
}
|
11
ProjectAtelier/ProjectAtelier/Entities/TempExpenditure.cs
Normal file
11
ProjectAtelier/ProjectAtelier/Entities/TempExpenditure.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using ProjectAtelier.Entities.Enums;
|
||||
|
||||
namespace ProjectAtelier.Entities;
|
||||
|
||||
public class TempExpenditure
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
public ModelType ModelType { get; private set; }
|
||||
public int ClothId { get; private set; }
|
||||
public double Value { get; private set; }
|
||||
}
|
@ -45,46 +45,42 @@
|
||||
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
|
||||
dataGridViewData.Dock = DockStyle.Fill;
|
||||
dataGridViewData.Location = new Point(0, 0);
|
||||
dataGridViewData.Margin = new Padding(3, 2, 3, 2);
|
||||
dataGridViewData.MultiSelect = false;
|
||||
dataGridViewData.Name = "dataGridViewData";
|
||||
dataGridViewData.ReadOnly = true;
|
||||
dataGridViewData.RowHeadersVisible = false;
|
||||
dataGridViewData.RowHeadersWidth = 51;
|
||||
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
|
||||
dataGridViewData.Size = new Size(583, 338);
|
||||
dataGridViewData.Size = new Size(666, 451);
|
||||
dataGridViewData.TabIndex = 5;
|
||||
//
|
||||
// panel1
|
||||
//
|
||||
panel1.Controls.Add(buttonAdd);
|
||||
panel1.Dock = DockStyle.Right;
|
||||
panel1.Location = new Point(583, 0);
|
||||
panel1.Margin = new Padding(3, 2, 3, 2);
|
||||
panel1.Location = new Point(666, 0);
|
||||
panel1.Name = "panel1";
|
||||
panel1.Size = new Size(117, 338);
|
||||
panel1.Size = new Size(134, 451);
|
||||
panel1.TabIndex = 4;
|
||||
//
|
||||
// buttonAdd
|
||||
//
|
||||
buttonAdd.BackgroundImage = Properties.Resources.icons8_добавить_96;
|
||||
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonAdd.Location = new Point(18, 14);
|
||||
buttonAdd.Margin = new Padding(3, 2, 3, 2);
|
||||
buttonAdd.Location = new Point(21, 19);
|
||||
buttonAdd.Name = "buttonAdd";
|
||||
buttonAdd.Size = new Size(82, 69);
|
||||
buttonAdd.Size = new Size(94, 92);
|
||||
buttonAdd.TabIndex = 0;
|
||||
buttonAdd.UseVisualStyleBackColor = true;
|
||||
buttonAdd.Click += ButtonAdd_Click;
|
||||
//
|
||||
// FormEntrances
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(700, 338);
|
||||
ClientSize = new Size(800, 451);
|
||||
Controls.Add(dataGridViewData);
|
||||
Controls.Add(panel1);
|
||||
Margin = new Padding(3, 2, 3, 2);
|
||||
Name = "FormEntrances";
|
||||
StartPosition = FormStartPosition.CenterParent;
|
||||
Text = "История пополнений";
|
||||
|
@ -1,4 +1,5 @@
|
||||
using ProjectAtelier.Repositories;
|
||||
using ProjectAtelier.Repositories.Implementations;
|
||||
using Unity;
|
||||
|
||||
namespace ProjectAtelier.Forms
|
||||
|
@ -1,19 +1,48 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using ProjectAtelier.Entities.Enums;
|
||||
using ProjectAtelier.Repositories;
|
||||
using ProjectAtelier.Repositories.Implementations;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ProjectAtelier.Forms
|
||||
{
|
||||
public partial class FormModel : Form
|
||||
{
|
||||
private readonly IModelRepository _modelRepository;
|
||||
private int? _modelId;
|
||||
public int Id
|
||||
{
|
||||
set
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = _modelRepository.ReadModelById(value);
|
||||
if (model == null)
|
||||
{
|
||||
throw new InvalidDataException(nameof(model));
|
||||
}
|
||||
comboBoxModelType.SelectedItem = model.ModelType;
|
||||
foreach (var elem in model.Expenditures)
|
||||
{
|
||||
var row = dataGridViewCloths.Rows[dataGridViewCloths.Rows.Add()];
|
||||
row.Cells["ColumnClothType"].Value = elem.ClothId;
|
||||
row.Cells["ColumnValue"].Value = elem.Value;
|
||||
}
|
||||
_modelId = value;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
public FormModel(IOrderRepository orderRepository, IClothRepository clothRepository, IModelRepository modelRepository)
|
||||
{
|
||||
InitializeComponent();
|
||||
_modelRepository = modelRepository ?? throw new ArgumentNullException(nameof(orderRepository));
|
||||
|
||||
comboBoxModelType.DataSource = modelRepository.ReadModels();
|
||||
comboBoxModelType.DisplayMember = "ModelType";
|
||||
comboBoxModelType.ValueMember = "Id";
|
||||
|
||||
comboBoxModelType.DataSource = Enum.GetValues(typeof(ModelType));
|
||||
|
||||
ColumnClothType.DataSource = clothRepository.ReadCloths();
|
||||
ColumnClothType.DisplayMember = "ClothType";
|
||||
@ -27,7 +56,14 @@ namespace ProjectAtelier.Forms
|
||||
{
|
||||
throw new Exception("Имеются незаполненные поля");
|
||||
}
|
||||
_modelRepository.CreateModel(Model.CreateEntity(0, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid()));
|
||||
if (_modelId.HasValue)
|
||||
{
|
||||
_modelRepository.UpdateModel(CreateModel(_modelId.Value));
|
||||
}
|
||||
else
|
||||
{
|
||||
_modelRepository.CreateModel(Model.CreateEntity(0, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid()));
|
||||
}
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -36,9 +72,9 @@ namespace ProjectAtelier.Forms
|
||||
}
|
||||
}
|
||||
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
|
||||
private Model CreateModel(int id) => Model.CreateEntity(id, (Entities.Enums.ModelType)(int)comboBoxModelType.SelectedValue!, CreateListExpenditureFromDataGrid());
|
||||
|
||||
private List<Expenditure>
|
||||
CreateListExpenditureFromDataGrid()
|
||||
private List<Expenditure> CreateListExpenditureFromDataGrid()
|
||||
{
|
||||
var list = new List<Expenditure>();
|
||||
foreach (DataGridViewRow row in dataGridViewCloths.Rows)
|
||||
@ -47,9 +83,13 @@ namespace ProjectAtelier.Forms
|
||||
{
|
||||
continue;
|
||||
}
|
||||
list.Add(Expenditure.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnClothType"].Value), Convert.ToInt32(row.Cells["ColumnValue"].Value)));
|
||||
list.Add(Expenditure.CreateElement(0,
|
||||
Convert.ToInt32(row.Cells["ColumnClothType"].Value),
|
||||
Convert.ToInt32(row.Cells["ColumnValue"].Value)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -31,6 +31,7 @@
|
||||
buttonDel = new Button();
|
||||
buttonAdd = new Button();
|
||||
panel1 = new Panel();
|
||||
buttonUpd = new Button();
|
||||
dataGridViewData = new DataGridView();
|
||||
panel1.SuspendLayout();
|
||||
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
|
||||
@ -40,7 +41,7 @@
|
||||
//
|
||||
buttonDel.BackgroundImage = Properties.Resources.icons8_удалить_100;
|
||||
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonDel.Location = new Point(18, 87);
|
||||
buttonDel.Location = new Point(18, 160);
|
||||
buttonDel.Margin = new Padding(3, 2, 3, 2);
|
||||
buttonDel.Name = "buttonDel";
|
||||
buttonDel.Size = new Size(82, 69);
|
||||
@ -62,6 +63,7 @@
|
||||
//
|
||||
// panel1
|
||||
//
|
||||
panel1.Controls.Add(buttonUpd);
|
||||
panel1.Controls.Add(buttonDel);
|
||||
panel1.Controls.Add(buttonAdd);
|
||||
panel1.Dock = DockStyle.Right;
|
||||
@ -71,6 +73,18 @@
|
||||
panel1.Size = new Size(117, 450);
|
||||
panel1.TabIndex = 8;
|
||||
//
|
||||
// buttonUpd
|
||||
//
|
||||
buttonUpd.BackgroundImage = Properties.Resources.icons8_редактировать_96;
|
||||
buttonUpd.BackgroundImageLayout = ImageLayout.Stretch;
|
||||
buttonUpd.Location = new Point(18, 87);
|
||||
buttonUpd.Margin = new Padding(3, 2, 3, 2);
|
||||
buttonUpd.Name = "buttonUpd";
|
||||
buttonUpd.Size = new Size(82, 69);
|
||||
buttonUpd.TabIndex = 10;
|
||||
buttonUpd.UseVisualStyleBackColor = true;
|
||||
buttonUpd.Click += ButtonUpd_Click;
|
||||
//
|
||||
// dataGridViewData
|
||||
//
|
||||
dataGridViewData.AllowUserToAddRows = false;
|
||||
@ -113,5 +127,6 @@
|
||||
private Button buttonAdd;
|
||||
private Panel panel1;
|
||||
private DataGridView dataGridViewData;
|
||||
private Button buttonUpd;
|
||||
}
|
||||
}
|
@ -36,6 +36,24 @@ namespace ProjectAtelier.Forms
|
||||
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<FormModel>();
|
||||
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))
|
||||
|
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
@ -48,7 +48,7 @@
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
|
@ -2,6 +2,10 @@ using Unity.Lifetime;
|
||||
using Unity;
|
||||
using ProjectAtelier.Repositories;
|
||||
using ProjectAtelier.Repositories.Implementations;
|
||||
using Unity.Microsoft.Logging;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace ProjectAtelier
|
||||
{
|
||||
@ -22,12 +26,27 @@ namespace ProjectAtelier
|
||||
private static IUnityContainer CreateContainer()
|
||||
{
|
||||
var container = new UnityContainer();
|
||||
|
||||
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
|
||||
|
||||
container.RegisterType<IClientRepository, ClientRepository>(new TransientLifetimeManager());
|
||||
container.RegisterType<IClothRepository, ClothRepository>(new TransientLifetimeManager());
|
||||
container.RegisterType<IEntranceRepository, EntranceRepository>(new TransientLifetimeManager());
|
||||
container.RegisterType<IModelRepository, ModelRepository>(new TransientLifetimeManager());
|
||||
container.RegisterType<IOrderRepository, OrderRepository>(new TransientLifetimeManager());
|
||||
container.RegisterType<IConnectionString, ConnectionString>(new TransientLifetimeManager());
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
@ -9,7 +9,19 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<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.2.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
|
||||
<PackageReference Include="Unity" Version="5.11.10" />
|
||||
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@ -27,4 +39,10 @@
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,6 @@
|
||||
namespace ProjectAtelier.Repositories;
|
||||
|
||||
public interface IConnectionString
|
||||
{
|
||||
string ConnectionString { get; }
|
||||
}
|
@ -1,24 +1,119 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using Dapper;
|
||||
using ProjectAtelier.Entities;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class ClientRepository : IClientRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<ClientRepository> _logger;
|
||||
public ClientRepository(IConnectionString connectionString, ILogger<ClientRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void CreateClient(Client client)
|
||||
{
|
||||
}
|
||||
public void DeleteClient(int id)
|
||||
{
|
||||
}
|
||||
public Client ReadClientById(int id)
|
||||
{
|
||||
return Client.CreateEntity(0, string.Empty, string.Empty);
|
||||
}
|
||||
public IEnumerable<Client> ReadClients()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO Clients (Name, Phone)
|
||||
VALUES (@Name, @Phone)";
|
||||
connection.Execute(queryInsert, client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void UpdateClient(Client client)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryUpdate = @"
|
||||
UPDATE Clients
|
||||
SET
|
||||
Name=@Name,
|
||||
Phone=@Phone
|
||||
WHERE Id=@Id";
|
||||
connection.Execute(queryUpdate, client);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void DeleteClient(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Clients
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public Client ReadClientById(int id)
|
||||
{
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM Clients
|
||||
WHERE Id=@id";
|
||||
var client = connection.QueryFirst<Client>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}",
|
||||
JsonConvert.SerializeObject(client));
|
||||
return client;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public IEnumerable<Client> ReadClients()
|
||||
{
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM Clients";
|
||||
var clients = connection.Query<Client>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(clients));
|
||||
return clients;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,25 +1,118 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using ProjectAtelier.Entities.Enums;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class ClothRepository : IClothRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<ClothRepository> _logger;
|
||||
public ClothRepository(IConnectionString connectionString, ILogger<ClothRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateCloth(Cloth cloth)
|
||||
{
|
||||
}
|
||||
public void DeleteCloth(int id)
|
||||
{
|
||||
}
|
||||
public Cloth ReadClothById(int id)
|
||||
{
|
||||
return Cloth.CreateEntity(0, ClothType.None, 0);
|
||||
}
|
||||
public IEnumerable<Cloth> ReadCloths()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cloth));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO Cloths (ClothType, Length)
|
||||
VALUES (@ClothType, @Length)";
|
||||
connection.Execute(queryInsert, cloth);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void UpdateCloth(Cloth cloth)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cloth));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryUpdate = @"
|
||||
UPDATE Cloths
|
||||
SET
|
||||
ClothType=@ClothType,
|
||||
Length=@Length
|
||||
WHERE Id=@Id";
|
||||
connection.Execute(queryUpdate, cloth);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void DeleteCloth(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Cloths
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public Cloth ReadClothById(int id)
|
||||
{
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT * FROM Cloths
|
||||
WHERE Id=@id";
|
||||
var cloth = connection.QueryFirst<Cloth>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}",
|
||||
JsonConvert.SerializeObject(cloth));
|
||||
return cloth;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public IEnumerable<Cloth> ReadCloths()
|
||||
{
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM Cloths";
|
||||
var cloths = connection.Query<Cloth>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(cloths));
|
||||
return cloths;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class ConnectionString : IConnectionString
|
||||
{
|
||||
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Database=atelierotp;Username=postgres;Password=postgres";
|
||||
}
|
@ -1,14 +1,55 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class EntranceRepository : IEntranceRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<EntranceRepository> _logger;
|
||||
public EntranceRepository(IConnectionString connectionString, ILogger<EntranceRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateEntrance(Entrance entrance)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(entrance));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryInsert = @"
|
||||
INSERT INTO Entrances (ClothId, Value, Date)
|
||||
VALUES (@ClothId, @Value, @Date)";
|
||||
connection.Execute(queryInsert, entrance);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public IEnumerable<Entrance> ReadEntrances(DateTime? dateForm = null, DateTime? dateTo = null, int? clothId = null)
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = "SELECT * FROM Entrances";
|
||||
var entrances = connection.Query<Entrance>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(entrances));
|
||||
return entrances;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,24 +1,161 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
using System.Transactions;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class ModelRepository : IModelRepository
|
||||
public class ModelRepository : IModelRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<ModelRepository> _logger;
|
||||
public ModelRepository(IConnectionString connectionString, ILogger<ModelRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateModel(Model model)
|
||||
{
|
||||
}
|
||||
public void DeleteModel(int id)
|
||||
{
|
||||
}
|
||||
public Model ReadModelById(int id)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
public IEnumerable<Model> ReadModels()
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(model));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var queryInsert = @"
|
||||
INSERT INTO Models (ModelType)
|
||||
VALUES (@ModelType);
|
||||
SELECT MAX(Id) FROM Models";
|
||||
var modelId = connection.QueryFirst<int>(queryInsert, model, transaction);
|
||||
var querySubInsert = @"
|
||||
INSERT INTO Expenditures (modelId, ClothId, Value)
|
||||
VALUES (@modelId,@ClothId, @Value)";
|
||||
foreach (var elem in model.Expenditures)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
modelId,
|
||||
elem.ClothId,
|
||||
elem.Value
|
||||
}, transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void UpdateModel(Model model)
|
||||
{
|
||||
_logger.LogInformation("Редактирование объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(model));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var queryUpdate = @"
|
||||
UPDATE Models
|
||||
SET
|
||||
ModelType=@ModelType
|
||||
WHERE Id=@Id;
|
||||
DELETE FROM Expenditures
|
||||
WHERE ModelId=@Id";
|
||||
connection.Execute(queryUpdate, model);
|
||||
var querySubInsert = @"
|
||||
INSERT INTO Expenditures (ModelId, ClothId, Value)
|
||||
VALUES (@Id, @ClothId, @Value)";
|
||||
foreach (var elem in model.Expenditures)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
model.Id,
|
||||
elem.ClothId,
|
||||
elem.Value
|
||||
}, transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при редактировании объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void DeleteModel(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Models
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public Model ReadModelById(int id)
|
||||
{
|
||||
_logger.LogInformation("Получение объекта по идентификатору");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT p.*, pc.ClothId, pc.Value FROM Models p
|
||||
INNER JOIN Expenditures pc ON pc.ModelId = p.Id
|
||||
WHERE p.Id=@id";
|
||||
var model = connection.Query<TempExpenditure>(querySelect, new
|
||||
{
|
||||
id
|
||||
});
|
||||
_logger.LogDebug("Найденный объект: {json}",
|
||||
JsonConvert.SerializeObject(model));
|
||||
return model.GroupBy(x => x.Id, y => y,
|
||||
(key, value) => Model.CreateEntity(value.First(),
|
||||
value.Select(z => Expenditure.
|
||||
CreateElement(0, z.ClothId, z.Value)))).ToList().First();
|
||||
;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public IEnumerable<Model> ReadModels()
|
||||
{
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"
|
||||
SELECT p.*, pc.ClothId, pc.Value FROM Models p
|
||||
INNER JOIN Expenditures pc ON pc.ModelId = p.Id";
|
||||
var models = connection.Query<TempExpenditure>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(models));
|
||||
return models.GroupBy(x => x.Id, y => y,
|
||||
(key, value) => Model.CreateEntity(value.First(),
|
||||
value.Select(z => Expenditure.
|
||||
CreateElement(0, z.ClothId, z.Value)))).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,17 +1,90 @@
|
||||
using ProjectAtelier.Entities;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Npgsql;
|
||||
using ProjectAtelier.Entities;
|
||||
|
||||
namespace ProjectAtelier.Repositories.Implementations;
|
||||
|
||||
internal class OrderRepository : IOrderRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<OrderRepository> _logger;
|
||||
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
_logger = logger;
|
||||
}
|
||||
public void CreateOrder(Order order)
|
||||
{
|
||||
_logger.LogInformation("Добавление объекта");
|
||||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
var queryInsert = @"
|
||||
INSERT INTO Orders (ClientId, Prise, Date, Prints)
|
||||
VALUES (@ClientId, @Prise, @Date, @Prints);
|
||||
SELECT MAX(Id) FROM Orders";
|
||||
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
|
||||
var querySubInsert = @"
|
||||
INSERT INTO ModelLists (orderId, ModelId, Count)
|
||||
VALUES (@orderId,@ModelId, @Count)";
|
||||
foreach (var elem in order.ModelLists)
|
||||
{
|
||||
connection.Execute(querySubInsert, new
|
||||
{
|
||||
orderId,
|
||||
elem.ModelId,
|
||||
elem.Count
|
||||
}, transaction);
|
||||
}
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public void DeleteOrder(int id)
|
||||
{
|
||||
_logger.LogInformation("Удаление объекта");
|
||||
_logger.LogDebug("Объект: {id}", id);
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var queryDelete = @"
|
||||
DELETE FROM Orders
|
||||
WHERE Id=@id";
|
||||
connection.Execute(queryDelete, new { id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||||
throw;
|
||||
}
|
||||
|
||||
}
|
||||
public IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? clientId = null, int? modelId = null)
|
||||
{
|
||||
return [];
|
||||
_logger.LogInformation("Получение всех объектов");
|
||||
try
|
||||
{
|
||||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||||
var querySelect = @"SELECT * FROM Orders";
|
||||
var orders = connection.Query<Order>(querySelect);
|
||||
_logger.LogDebug("Полученные объекты: {json}",
|
||||
JsonConvert.SerializeObject(orders));
|
||||
return orders;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
15
ProjectAtelier/ProjectAtelier/appsettings.json
Normal file
15
ProjectAtelier/ProjectAtelier/appsettings.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "Logs/atelier_log.txt",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user