ISEbd-21 KlepikovP.A LabWork02 #2

Closed
PeterKlepikov wants to merge 3 commits from LabWork_2 into LabWork_1
13 changed files with 546 additions and 26 deletions

View File

@ -80,7 +80,6 @@
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridView.RowTemplate.Height = 25;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(264, 223);
dataGridView.TabIndex = 0;

View File

@ -41,8 +41,9 @@ public partial class FormFuelSale : Form
{
throw new Exception("Имеются незаполненные поля");
}
int countQuantity = int.Parse(dataGridView.Rows[0].Cells["ColumnQuantity"].Value?.ToString() ?? "0");
_fuelSalesRepository.CreateFuelSale(FuelSale.CreateElement(0,
(int)comboBoxCashier.SelectedValue!, dateTimePickerDate.Value, 0, CreateListFuelFuelSaleFromDataGrid()));
(int)comboBoxCashier.SelectedValue!, dateTimePickerDate.Value, countQuantity, CreateListFuelFuelSaleFromDataGrid()));
Close();
}
catch (Exception ex)

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<TargetFramework>net8.0-windows7.0</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
@ -19,7 +19,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="8.0.5" />
<PackageReference Include="Serilog" Version="4.0.2" />
<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.8.6" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -37,4 +49,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -2,6 +2,10 @@ using GasStation.Repositories.Implementations;
using GasStation.Repositories;
using Unity.Lifetime;
using Unity;
using Unity.Microsoft.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
namespace GasStation
{
@ -23,13 +27,30 @@ namespace GasStation
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType <ICashierRepository, CashierRepository>();
container.RegisterType <IFuelRepository, FuelRepository>();
container.RegisterType <IFuelSalesRepository, FuelSalesRepository>();
container.RegisterType <ISuppliersFuelRepository, SuppliersFuelRepository>();
container.RegisterType <ISupplierRepository, SupplierRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

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

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GasStation.Entities;
using GasStation.Entities;
namespace GasStation.Repositories;

View File

@ -1,34 +1,133 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using GasStation.Entities;
using GasStation.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class CashierRepository : ICashierRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CashierRepository> _logger;
public CashierRepository(IConnectionString connectionString, ILogger<CashierRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateCashier(Cashier cashier)
{
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cashier));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Cashier (FirstName, LastName, CashierPost)
VALUES (@FirstName, @LastName, @CashierPost)";
connection.Execute(queryInsert, cashier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteCashier(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Cashier
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Cashier ReadCashierById(int id)
{
return Cashier.CreateEntity(0, string.Empty, string.Empty, CashierPost.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Cashier
WHERE Id=@id";
var cashier = connection.QueryFirst<Cashier>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(cashier));
return cashier;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Cashier> ReadCashiers()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Cashier";
var cashier = connection.Query<Cashier>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(cashier));
return cashier;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateCashier(Cashier cashier)
{
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cashier));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Cashier
SET
FirstName=@FirstName,
LastName=@LastName,
CashierPost=@CashierPost
WHERE Id=@Id";
connection.Execute(queryUpdate, cashier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -0,0 +1,6 @@
namespace GasStation.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost,5432;Database=egov;Uid=postgres;Pwd=postgres;";
}

View File

@ -1,34 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GasStation.Entities;
using GasStation.Entities.Enums;
using GasStation.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System.Data.SqlClient;
namespace GasStation.Repositories.Implementations;
public class FuelRepository : IFuelRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<FuelRepository> _logger;
public FuelRepository(IConnectionString connectionString, ILogger<FuelRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateFuel(Fuel fuel)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(fuel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Fuel (Cost, Type)
VALUES (@Cost, @Type)";
connection.Execute(queryInsert, fuel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteFuel(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Fuel
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Fuel ReadFuelById(int id)
{
return Fuel.CreateEntity(0, 0, FuelType.Fuel_diesel);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Fuel
WHERE Id=@id";
var fuel = connection.QueryFirst<Fuel>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(fuel));
return fuel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Fuel> ReadFuels()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Fuel";
var fuels = connection.Query<Fuel>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(fuels));
return fuels;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateFuel(Fuel fuel)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(fuel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Fuel
SET
Cost=@Cost,
Type=@Type
WHERE Id=@Id";
connection.Execute(queryUpdate, fuel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,24 +1,112 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using GasStation.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class FuelSalesRepository : IFuelSalesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<FuelSalesRepository> _logger;
public FuelSalesRepository(IConnectionString connectionString, ILogger<FuelSalesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateFuelSale(FuelSale fuelSale)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(fuelSale));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO FuelSale (CashierId, SaleDate, TotalPrice)
VALUES (@CashierId, @SaleDate, @TotalPrice);
SELECT MAX(Id) FROM FuelSale";
var fuelSaleId =
connection.QueryFirst<int>(queryInsert, fuelSale, transaction);
var querySubInsert = @"
INSERT INTO FuelFuelSale (FuelSaleId, FuelId, Quantity, Price)
VALUES (@FuelSaleId, @FuelId, @Quantity, @Price)";
foreach (var elem in fuelSale.FuelFuelSale)
{
connection.Execute(querySubInsert, new
{
fuelSaleId,
elem.FuelId,
elem.Quantity,
elem.Price
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteFuelSale(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM FuelFuelSale
WHERE FuelSaleId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM FuelSale
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<FuelSale> ReadFuelSale(DateTime? dateFrom = null, DateTime? dateTo = null, int? gasStationId = null, int? fuelId = null, int? cashierId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM FuelSale";
var fuelSales = connection.Query<FuelSale>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(fuelSales));
return fuelSales;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -4,32 +4,126 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using GasStation.Entities;
using GasStation.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class SupplierRepository : ISupplierRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplierRepository> _logger;
public SupplierRepository(IConnectionString connectionString, ILogger<SupplierRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupplier(Supplier supplier)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supplier));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Supplier (Brand, Types)
VALUES (@Brand, @Types)";
connection.Execute(queryInsert, supplier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSupplier(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Supplier
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Supplier ReadSupplierById(int id)
{
return Supplier.CreateEntity(0, string.Empty, SupppliersFuelType.Fuel_diesel);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Supplier
WHERE Id=@id";
var supplier = connection.QueryFirst<Supplier>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(supplier));
return supplier;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Supplier> ReadSuppliers()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Supplier";
var suppliers = connection.Query<Supplier>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(suppliers));
return suppliers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateSupplier(Supplier supplier)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(supplier));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Supplier
SET
Brand=@Brand,
Types=@Types
WHERE Id=@Id";
connection.Execute(queryUpdate, supplier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -3,22 +3,107 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using GasStation.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class SuppliersFuelRepository : ISuppliersFuelRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SuppliersFuelRepository> _logger;
public SuppliersFuelRepository(IConnectionString connectionString, ILogger<SuppliersFuelRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSuppliersFuel(SuppliersFuel suppliersFuel)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(suppliersFuel));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO SuppliersFuel (SuppliersId, Date)
VALUES (@SuppliersId, @Date);
SELECT MAX(Id) FROM SuppliersFuel";
var suppliersFuelId =
connection.QueryFirst<int>(queryInsert, suppliersFuel, transaction);
var querySubInsert = @"
INSERT INTO SuppliersFuelFuel (SuppliersFuelId, FuelId, Quantity)
VALUES (@SuppliersFuelId, @FuelId, @Quantity)";
foreach (var elem in suppliersFuel.SuppliersFuelFuel)
{
connection.Execute(querySubInsert, new
{
suppliersFuelId,
elem.FuelId,
elem.Quantity
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSuppliersFuel(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM SuppliersFuelFuel
WHERE SuppliersFuelId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM SuppliersFuel
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<SuppliersFuel> ReadSuppliersFuels(DateTime? dateFrom = null, DateTime? dateTo = null, int? suppliersId = null, int? fuelId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM SuppliersFuel";
var suppliersFuels = connection.Query<SuppliersFuel>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(suppliersFuels));
return suppliersFuels;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/gas_log.txt",
"rollingInterval": "Day"
}
}
]
}
}