я устал бд переделывать

This commit is contained in:
RozhVan 2024-12-09 14:34:46 +04:00
parent 2aca72eed3
commit c5db05fbb1
15 changed files with 498 additions and 39 deletions

View File

@ -6,16 +6,16 @@ public class Product
{
public int Id { get; private set; }
public int Cost { get; private set; }
public int ProductCost { get; private set; }
public ProductType ProductType { get; private set; }
public static Product CreateProduct(int id, int cost, ProductType productType)
public static Product CreateProduct(int id, int productCost, ProductType productType)
{
return new Product
{
Id = id,
Cost = cost,
ProductCost = productCost,
ProductType = productType
};
}

View File

@ -4,14 +4,14 @@ public class Supplier
{
public int Id { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public string SupplierName { get; private set; } = string.Empty;
public static Supplier CreateSupplier(int id, string productName)
public static Supplier CreateSupplier(int id, string supplierName)
{
return new Supplier
{
Id = id,
ProductName = productName
SupplierName = supplierName
};
}
}

View File

@ -31,7 +31,7 @@
labelSupplier = new Label();
buttonSave = new Button();
buttonCancel = new Button();
comboBoxSupplierName = new ComboBox();
textBoxSupplier = new TextBox();
SuspendLayout();
//
// labelSupplier
@ -63,21 +63,19 @@
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// comboBoxSupplierName
// textBoxSupplier
//
comboBoxSupplierName.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSupplierName.FormattingEnabled = true;
comboBoxSupplierName.Location = new Point(100, 12);
comboBoxSupplierName.Name = "comboBoxSupplierName";
comboBoxSupplierName.Size = new Size(290, 23);
comboBoxSupplierName.TabIndex = 4;
textBoxSupplier.Location = new Point(112, 9);
textBoxSupplier.Name = "textBoxSupplier";
textBoxSupplier.Size = new Size(278, 23);
textBoxSupplier.TabIndex = 4;
//
// FormSupplier
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(438, 122);
Controls.Add(comboBoxSupplierName);
Controls.Add(textBoxSupplier);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelSupplier);
@ -92,6 +90,6 @@
private Label labelSupplier;
private Button buttonSave;
private Button buttonCancel;
private ComboBox comboBoxSupplierName;
private TextBox textBoxSupplier;
}
}

View File

@ -5,7 +5,7 @@ namespace GasStation.Forms
{
public partial class FormSupplier : Form
{
private readonly ISupplierRepository _suppliarRepository;
private readonly ISupplierRepository _supplierRepository;
private int? _supplierId;
@ -15,13 +15,13 @@ namespace GasStation.Forms
{
try
{
var supplier = _suppliarRepository.ReadSupplierByID(value);
var supplier = _supplierRepository.ReadSupplierByID(value);
if (supplier == null)
{
throw new InvalidDataException(nameof(supplier));
}
comboBoxSupplierName.DataSource = supplier.ProductName;
textBoxSupplier.Text = supplier.SupplierName;
_supplierId = value;
}
catch (Exception ex)
@ -35,7 +35,7 @@ namespace GasStation.Forms
public FormSupplier(ISupplierRepository supplierRepository)
{
InitializeComponent();
_suppliarRepository = supplierRepository ??
_supplierRepository = supplierRepository ??
throw new ArgumentNullException(nameof(supplierRepository));
}
@ -43,17 +43,17 @@ namespace GasStation.Forms
{
try
{
if (comboBoxSupplierName.SelectedIndex < 1)
if (textBoxSupplier.Text == "")
{
throw new Exception("Имеются незаполненые поля");
}
if (_supplierId.HasValue)
{
_suppliarRepository.UpdateSupplier(CreateSupplier(_supplierId.Value));
_supplierRepository.UpdateSupplier(CreateSupplier(_supplierId.Value));
}
else
{
_suppliarRepository.CreateSupplier(CreateSupplier(0));
_supplierRepository.CreateSupplier(CreateSupplier(0));
}
Close();
}
@ -64,7 +64,7 @@ namespace GasStation.Forms
}
}
private Supplier CreateSupplier(int id) => Supplier.CreateSupplier(id, comboBoxSupplierName.Text);
private Supplier CreateSupplier(int id) => Supplier.CreateSupplier(id, textBoxSupplier.Text);
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
}

View File

@ -9,7 +9,18 @@
</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.2" />
<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="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -27,4 +38,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -1,5 +1,9 @@
using GasStation.Repositories;
using GasStation.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity.Microsoft.Logging;
using System.Drawing.Text;
using Unity;
@ -23,12 +27,27 @@ internal static class Program
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IGasmanRepository, GasmanRepository>();
container.RegisterType<ISellingRepository,SellingRepository>();
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<ISupplyRepository, SupplyRepository>();
container.RegisterType<IProductRepository, ProductRepository>();
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,6 @@
namespace GasStation.Repositories;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -8,5 +8,4 @@ public interface ISellingRepository
void CreateSelling(Selling selling);
void DeleteSelling(int id);
}

View File

@ -0,0 +1,6 @@
namespace GasStation.Repositories.Implementations;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=normis";
}

View File

@ -1,29 +1,127 @@
using GasStation.Entities;
using GasStation.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System;
namespace GasStation.Repositories.Implementations;
public class GasmanRepository : IGasmanRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<GasmanRepository> _logger;
public GasmanRepository(IConnectionString connectionString, ILogger<GasmanRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateGasman(Gasman gasman)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(gasman));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO gasman (gasmanName, phoneNumber, post)
VALUES (@GasmanName, @PhoneNumber, @Post)";
connection.Execute(queryInsert, gasman);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteGasman(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM gasman
WHERE id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Gasman ReadGasmanByID(int id)
{
return Gasman.CreateGasman(0, string.Empty, string.Empty, Post.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM gasman
WHERE id=@id";
var gasman = connection.QueryFirst<Gasman>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(gasman));
return gasman;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Gasman> ReadGasman()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM gasman";
var gasman = connection.Query<Gasman>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(gasman));
return gasman;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateGasman(Gasman gasman)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(gasman));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE gasman
SET
gasmanName=@GasmanName,
phoneNumber=@PhoneNumber,
post=@Post
WHERE id=@Id";
connection.Execute(queryUpdate, gasman);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,29 +1,126 @@
using GasStation.Entities;
using Dapper;
using GasStation.Entities;
using GasStation.Entities.Enums;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class ProductRepository : IProductRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductRepository> _logger;
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProduct(Product product)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO product (productCost, productType)
VALUES (@ProductCost, @ProductType)";
connection.Execute(queryInsert, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteProduct(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM product
WHERE id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Product> ReadProduct()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM product";
var product = connection.Query<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Product ReadProductByID(int id)
{
return Product.CreateProduct(0, 0, ProductType.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM product
WHERE id=@Id";
var product = connection.QueryFirst<Product>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateProduct(Product product)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE product
SET
productCost=@ProductCost,
productType=@ProductType
WHERE id=@Id";
connection.Execute(queryUpdate, product);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,19 +1,69 @@
using GasStation.Entities;
using Dapper;
using GasStation.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class SellingRepository : ISellingRepository
{
public void CreateSelling(Selling selling)
private readonly IConnectionString _connectionString;
private readonly ILogger<SellingRepository> _logger;
public SellingRepository(IConnectionString connectionString, ILogger<SellingRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void DeleteSelling(int id)
public void CreateSelling(Selling selling)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(selling));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO selling (sellingDateTime, gasmanId, count)
VALUES (@SellingDateTime, @GasmanId, @Count);
SELECT MAX(Id) FROM selling";
var Id = connection.QueryFirst<int>(queryInsert, selling, transaction);
var querySubInsert = @"
INSERT INTO product_selling (id, productID, count)
VALUES (@Id, @ProductID, @Count)";
foreach (var elem in selling.ProdutcSellings)
{
connection.Execute(querySubInsert, new { Id, elem.ProductID, elem.Count }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public IEnumerable<Selling> ReadSelling(DateTime? dateTime = null, int? count = null, int? gasmanID = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM selling";
var selling = connection.Query<Selling>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(selling));
return selling;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,28 +1,123 @@
using GasStation.Entities;
using Dapper;
using GasStation.Entities;
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 (supplierName)
VALUES (@SupplierName)";
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.CreateSupplier(0, string.Empty);
_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> ReadSupplier()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM supplier";
var supplier = connection.Query<Supplier>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supplier));
return supplier;
}
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
supplierName=@SupplierName
WHERE id=@Id";
connection.Execute(queryUpdate, supplier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -1,19 +1,78 @@
using GasStation.Entities;
using Dapper;
using GasStation.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
namespace GasStation.Repositories.Implementations;
public class SupplyRepository : ISupplyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplyRepository> _logger;
public SupplyRepository(IConnectionString connectionString, ILogger<SupplyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupply(Supply supply)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO supply (productID, supplierID, count, supplyDate)
VALUES (@ProductID, @SupplierID, @Count, @SupplyDate)";
connection.Execute(queryInsert, supply);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSupply(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM supply
WHERE id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Supply> ReadSupply(DateTime? supplyDate = null, int? supplierID = null, int? productID = null, int? count = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM supply";
var supply = connection.Query<Supply>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supply));
return supply;
}
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": "C:\\Users\\rozko\\Documents\\log.txt",
"rollinInterval": "Day"
}
}
]
}
}