Pibd-24 Boyko_M.S. LabWork02 #2

Closed
LivelyPuer wants to merge 2 commits from lab2 into lab1
12 changed files with 559 additions and 53 deletions

View File

@ -9,6 +9,10 @@ namespace ProjectGSM.Entities.Enums
[Flags]
public enum LicenseType
{
None, Base, Novokek, Pro, Master, Guru
None = 0,
Base = 1 << 0,
Pro = 1 << 1,
Master = 1 << 2,
Guru = 1 << 3
}
}
}

View File

@ -5,7 +5,6 @@ using ProjectGSM.Repositories;
namespace ProjectGSM.Forms
{
public partial class FormAdvocate : Form
{
private readonly IAdvocateRepository _advocateRepository;
@ -19,11 +18,11 @@ namespace ProjectGSM.Forms
try
{
var advocate =
_advocateRepository.ReadAdvocateById(value);
_advocateRepository.ReadAdvocateById(value);
if (advocate == null)
{
throw new
InvalidDataException(nameof(advocate));
InvalidDataException(nameof(advocate));
}
_advocateId = value;
@ -32,13 +31,14 @@ namespace ProjectGSM.Forms
if ((elem & advocate.LicenseType) != 0)
{
checkedListBox.SetItemChecked(checkedListBox.Items.IndexOf(
elem), true);
elem), true);
}
}
nameTextBox.Text = advocate.Name;
sexCheckBox.Checked= advocate.Sex;
dateTimePicker.Value = new DateTime(advocate.DateOfBirth.Year, advocate.DateOfBirth.Month, advocate.DateOfBirth.Day);
sexCheckBox.Checked = advocate.Sex;
dateTimePicker.Value = new DateTime(advocate.DateOfBirth.Year, advocate.DateOfBirth.Month,
advocate.DateOfBirth.Day);
expNumeric.Value = advocate.Experience;
tasksNumeric.Value = advocate.CompletedTasks;
ratingNumeric.Value = advocate.Rating;
@ -48,7 +48,8 @@ namespace ProjectGSM.Forms
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
@ -59,14 +60,13 @@ namespace ProjectGSM.Forms
{
InitializeComponent();
_advocateRepository = advocateRepository ??
throw new
ArgumentNullException(nameof(advocateRepository));
throw new
ArgumentNullException(nameof(advocateRepository));
foreach (var elem in Enum.GetValues(typeof(LicenseType)))
{
checkedListBox.Items.Add(elem);
}
}
private void saveButton_Click(object sender, EventArgs e)
@ -80,6 +80,7 @@ namespace ProjectGSM.Forms
{
throw new Exception("Имеются незаполненные поля");
}
if (_advocateId.HasValue)
{
_advocateRepository.UpdateAdvocate(CreateAdvocate(_advocateId.Value));
@ -88,36 +89,35 @@ namespace ProjectGSM.Forms
{
_advocateRepository.CreateAdvocate(CreateAdvocate(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void cancelButton_Click(object sender, EventArgs e) => Close();
private Advocate CreateAdvocate(int id)
{
LicenseType licenseType = LicenseType.None;
foreach (var elem in checkedListBox.CheckedItems)
int licenseType = 0;
foreach (int elem in checkedListBox.CheckedItems)
{
licenseType |= (LicenseType)elem;
licenseType |= elem;
}
return Advocate.CreateEntity(id,
nameTextBox.Text,
sexCheckBox.Checked,
dateTimePicker.Value,
Convert.ToInt32(expNumeric.Value),
Convert.ToInt32(tasksNumeric.Value),
Convert.ToInt32(ratingNumeric.Value),
emailTextBox.Text,
phoneText.Text,
adressBox.Text, licenseType);
nameTextBox.Text,
sexCheckBox.Checked,
dateTimePicker.Value,
Convert.ToInt32(expNumeric.Value),
Convert.ToInt32(tasksNumeric.Value),
Convert.ToInt32(ratingNumeric.Value),
emailTextBox.Text,
phoneText.Text,
adressBox.Text, (LicenseType)licenseType);
}
}
}
}

View File

@ -1,8 +1,13 @@
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectGSM.Forms;
using ProjectGSM.Repositories;
using ProjectGSM.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ProjectGSM
{
@ -23,12 +28,29 @@ namespace ProjectGSM
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.RegisterType<ICaseAdvocateRepository, CaseAdvocateRepository>(new TransientLifetimeManager());
container.AddExtension(new
LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IConnectionString,
PSQLConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IAdvocateRepository, AdvocateRepository>(new TransientLifetimeManager());
container.RegisterType<ICaseRepository, CaseRepository>(new TransientLifetimeManager());
container.RegisterType<IClientRepository, ClientRepository>(new TransientLifetimeManager());
container.RegisterType<ICourtRepository, CourtRepository>(new TransientLifetimeManager());
container.RegisterType<IStatusHistoryRepository, StatusHistoryRepository>(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;
}
}
}

View File

@ -50,9 +50,7 @@
<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="Npgsql" Version="9.0.0" />
<PackageReference Include="Serilog" Version="4.2.0-dev-02328" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10410" />

View File

@ -0,0 +1,9 @@
using System.Data.SqlClient;
namespace ProjectGSM.Repositories
{
public interface IConnectionString
{
string ConnectionString { get; }
}
}

View File

@ -1,29 +1,133 @@
using ProjectGSM.Entities;
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
namespace ProjectGSM.Repositories.Implementations;
public class AdvocateRepository : IAdvocateRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AdvocateRepository> _logger;
public AdvocateRepository(IConnectionString connectionString,
ILogger<AdvocateRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Advocate> ReadAdvocates()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM advocates";
var advocates = connection.Query<Advocate>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(advocates));
return advocates;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Advocate ReadAdvocateById(int id)
{
return Advocate.CreateEntity(0, String.Empty, false, DateTime.UtcNow, 0, 0, 0, String.Empty, String.Empty,
String.Empty, Entities.Enums.LicenseType.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM advocates WHERE Id=@id";
var advocate = connection.QueryFirst<Advocate>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonSerializer.Serialize(advocate));
return advocate;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateAdvocate(Advocate advocate)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(advocate));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO advocates (name, sex, dateofbirth, experience, completed_tasks, rating, email, phonenumber, address, licensetype, createdat)
VALUES (@Name, @Sex, @DateOfBirth, @Experience, @CompletedTasks, @Rating, @Email, @PhoneNumber, @Address, @LicenseType, @CreatedAt)";
connection.Execute(queryInsert, advocate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateAdvocate(Advocate advocate)
{
_logger.LogInformation("Обновление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(advocate));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE advocates
SET id = @Id,
name = @Name,
sex = @Sex,
dateofbirth = @DateOfBirth,
experience = @Experience,
completed_tasks = @CompletedTasks,
rating = @Rating,
email = @Email,
phonenumber = @PhoneNumber,
address = @Address,
licensetype = @LicenseType,
createdat = @CreatedAt
WHERE id = @Id;";
connection.Execute(queryUpdate, advocate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обновлении объекта");
throw;
}
}
public void DeleteAdvocate(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM advocates WHERE id = @Id;";
connection.Execute(queryDelete, new { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -1,28 +1,112 @@
using ProjectGSM.Entities;
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
namespace ProjectGSM.Repositories.Implementations;
public class CaseRepository : ICaseRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CaseRepository> _logger;
public CaseRepository(IConnectionString connectionString,
ILogger<CaseRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Case> ReadCases()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM cases";
var cases = connection.Query<Case>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(cases));
return cases;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Case ReadCaseById(int id)
{
return Case.CreateEntity(0, 0, false, 0, 0, false, 0, 0, String.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM cases WHERE Id=@id";
var caseE = connection.QueryFirst<Case>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonSerializer.Serialize(caseE));
return caseE;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateCase(Case caseEntity)
{
}
public void UpdateCase(Case caseEntity)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(caseEntity));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"INSERT INTO Cases (typeappeal, Payment, Price, victoryprice, Verdict, courtid, clientid, Description, createdat)
VALUES (@TypeAppeal, @Payment, @Price, @VictoryPrice, @Verdict, @CourtId, @ClientId, @Description, @CreatedAt);
SELECT MAX(Id) FROM cases;";
var caseId =
connection.QueryFirst<int>(queryInsert, caseEntity, transaction);
var querySubInsert = @"
INSERT INTO case_advocates (caseid, advocateid, post, createdat)
VALUES (@CaseId, @AdvocateId, @Post, @CreatedAt)";
foreach (var elem in caseEntity.Advocates)
{
connection.Execute(querySubInsert, new {
caseId, elem.AdvocateId, elem.Post, elem.CreatedAt }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteCase(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM cases WHERE id = @Id;";
connection.Execute(queryDelete, new { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -1,21 +1,126 @@
using ProjectGSM.Entities;
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
namespace ProjectGSM.Repositories.Implementations;
public class ClientRepository : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepository> _logger;
public ClientRepository(IConnectionString connectionString,
ILogger<ClientRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Client> ReadClients()
{
return [];}
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM clients";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Client ReadClientById(int id)
{
return Client.CreateEntity(0, String.Empty, false, DateTime.UtcNow, String.Empty, String.Empty, String.Empty);
_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}",
JsonSerializer.Serialize(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateClient(Client client) { }
public void CreateClient(Client client)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(client));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO clients (name, sex, dateOfBirth, email, phonenumber, address, createdAt)
VALUES (@Name, @Sex, @DateOfBirth, @Email, @PhoneNumber, @Address, @CreatedAt);";
connection.Execute(queryInsert, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateClient(Client client) { }
public void UpdateClient(Client client)
{
_logger.LogInformation("Обновление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(client));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE clients
SET name = @Name,
sex = @Sex,
dateofbirth = @DateOfBirth,
email = @Email,
phonenumber = @PhoneNumber,
address = @Address
WHERE id = @Id;";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обновлении объекта");
throw;
}
}
public void DeleteClient(int id) { }
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 = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -1,28 +1,122 @@
using ProjectGSM.Entities;
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
namespace ProjectGSM.Repositories.Implementations;
public class CourtRepository : ICourtRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CourtRepository> _logger;
public CourtRepository(IConnectionString connectionString,
ILogger<CourtRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Court> ReadCourts()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM courts";
var courts = connection.Query<Court>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(courts));
return courts;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Court ReadCourtById(int id)
{
return Court.CreateEntity(0, String.Empty, String.Empty);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM courts WHERE Id = @Id";
var court = connection.QueryFirst<Court>(querySelect, new { id });
_logger.LogDebug("Полученный объект: {json}",
JsonSerializer.Serialize(court));
return court;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объекта");
throw;
}
}
public void CreateCourt(Court court)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(court));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO courts (name, address, createdat)
VALUES (@Name, @Address, @CreatedAt);";
connection.Execute(queryInsert, court);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateCourt(Court court)
{
_logger.LogInformation("Обновление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(court));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"UPDATE courts
SET name = @Name,
address = @Address
WHERE id = @Id;";
connection.Execute(queryUpdate, court);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обновлении объекта");
throw;
}
}
public void DeleteCourt(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM courts WHERE id = @Id;";
connection.Execute(queryDelete, new { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -0,0 +1,9 @@
namespace ProjectGSM.Repositories.Implementations;
public class PSQLConnectionString : IConnectionString
{
private readonly string _connectionString =
"User Id=postgres; Password=postgres; Host=localhost; Port=5432; Database=egovdb;";
public string ConnectionString => _connectionString;
}

View File

@ -1,20 +1,82 @@
using ProjectGSM.Entities;
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
namespace ProjectGSM.Repositories.Implementations;
public class StatusHistoryRepository : IStatusHistoryRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StatusHistoryRepository> _logger;
public StatusHistoryRepository(IConnectionString connectionString,
ILogger<StatusHistoryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<StatusHistory> ReadStatusHistories(DateTime? dateForm = null, DateTime? dateTo = null,
int? caseId = null, int? statusId = null)
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM status_histories";
var statusHistories =
connection.Query<StatusHistory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(statusHistories));
return statusHistories;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void CreateStatusHistory(StatusHistory statusHistory)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(statusHistory));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO status_histories (caseid, status, price, createdat)
VALUES (@CaseId, @Status, @Price, @CreatedAt)";
connection.Execute(queryInsert, statusHistory);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteStatusHistory(int statusId, int caseId)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Идентификаторы: {statusId}, {caseId}", statusId, caseId);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM status_histories WHERE status = @Status AND caseid = @CaseId";
connection.Execute(queryDelete, new { StatusId = statusId, CaseId = caseId });
}
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/advocates_log.txt",
"rollingInterval": "Day"
}
}
]
}
}