Compare commits

...

2 Commits

Author SHA1 Message Date
ba982de835 изменения 2024-11-16 14:07:48 +04:00
b65eb828b7 Лабораторная работ №2 2024-11-16 14:06:34 +04:00
12 changed files with 552 additions and 58 deletions

View File

@ -10,13 +10,15 @@ public class ExpensePeopleExpense
{
public int Id { get; private set; }
public int ExpenseId { get; private set; }
public int PeopleExpenseId { get; private set; }
public int Sum { get; private set; }
public static ExpensePeopleExpense CreateElement(int id, int expenseId, int sum)
public static ExpensePeopleExpense CreateElement(int id, int expenseId, int peopleExpenseId,int sum)
{
return new ExpensePeopleExpense
{
Id = id,
ExpenseId = expenseId,
PeopleExpenseId = peopleExpenseId,
Sum = sum
};
}

View File

@ -10,13 +10,15 @@ public class IncomePeopleIncome
{
public int Id { get; private set; }
public int IncomeId { get; private set; }
public int PeopleIncomeId { get; private set; }
public int Sum { get; private set; }
public static IncomePeopleIncome CreateElement(int id,int incomeId, int sum)
public static IncomePeopleIncome CreateElement(int id,int incomeId,int peopleIncomeId, int sum)
{
return new IncomePeopleIncome
{
Id = id,
IncomeId = incomeId,
PeopleIncomeId = peopleIncomeId,
Sum = sum
};
}

View File

@ -1,7 +1,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectFamilyBudget.Repositories;
using ProjectFamilyBudget.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Lifetime;
using Unity.Microsoft.Logging;
namespace ProjectFamilyBudget
{
@ -23,14 +26,29 @@ namespace ProjectFamilyBudget
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IPeople, PeopleRepository>();
container.RegisterType<IIncome, IncomeRepository>();
container.RegisterType<IExpense, ExpenseRepository>();
container.RegisterType<IPeopleIncome, PeopleIncomeRepository>();
container.RegisterType<IPeopleExpense, PeopleExpenseRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
container.RegisterType<IPeople, PeopleRepository>(new TransientLifetimeManager());
container.RegisterType<IIncome, IncomeRepository>(new TransientLifetimeManager());
container.RegisterType<IExpense, ExpenseRepository>(new TransientLifetimeManager());
container.RegisterType<IPeopleIncome, PeopleIncomeRepository>(new TransientLifetimeManager());
container.RegisterType<IPeopleExpense, PeopleExpenseRepository>(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

@ -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="8.0.5" />
<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

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

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectFamilyBudget.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=otp";
}

View File

@ -1,37 +1,123 @@
using ProjectFamilyBudget.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Entities;
using ProjectFamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace ProjectFamilyBudget.Repositories.Implementations;
public class ExpenseRepository : IExpense
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ExpenseRepository> _logger;
public ExpenseRepository(IConnectionString connectionString, ILogger<ExpenseRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateExpense(Expense expense)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(expense));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Expense (ExpenseType, Name, ExpenseCategory)
VALUES (@ExpenseType, @Name, @ExpenseCategory)";
connection.Execute(queryInsert, expense);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateExpense(Expense expense)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(expense));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Expense
SET
ExpenseType=@ExpenseType,
Name=@Name,
ExpenseCategory=@ExpenseCategory,
WHERE Id=@Id";
connection.Execute(queryUpdate, expense);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteExpense(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Expense
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Expense ReadExpenseById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Expense
WHERE Id=@id";
var expense = connection.QueryFirst<Expense>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(expense));
return expense;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Expense> ReadExpense()
{
return [];
}
public Expense ReadExpenseById(int id)
_logger.LogInformation("Получение всех объектов");
try
{
return Expense.CreateEntity(0, IncomeExpenseType.None, string.Empty, string.Empty);
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Expense";
var expenses = connection.Query<Expense>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(expenses));
return expenses;
}
public void UpdateExpense(Expense expense)
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectFamilyBudget.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Entities;
using ProjectFamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
@ -10,28 +14,109 @@ namespace ProjectFamilyBudget.Repositories.Implementations;
public class IncomeRepository : IIncome
{
private readonly IConnectionString _connectionString;
private readonly ILogger<IncomeRepository> _logger;
public IncomeRepository(IConnectionString connectionString, ILogger<IncomeRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateIncome(Income income)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(income));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Income (IncomeType, Name, IncomeCategory)
VALUES (@IncomeType, @Name, @IncomeCategory)";
connection.Execute(queryInsert, income);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateIncome(Income income)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(income));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Income
SET
IncomeType=@IncomeType,
Name=@Name,
IncomeCategory=@IncomeCategory,
WHERE Id=@Id";
connection.Execute(queryUpdate, income);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteIncome(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Income
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Income ReadIncomeById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Income
WHERE Id=@id";
var income = connection.QueryFirst<Income>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(income));
return income;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Income> ReadIncome()
{
return [];
}
public Income ReadIncomeById(int id)
_logger.LogInformation("Получение всех объектов");
try
{
return Income.CreateEntity(0, IncomeExpenseType.None, string.Empty, string.Empty);
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Income";
var incomes = connection.Query<Income>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(incomes));
return incomes;
}
public void UpdateIncome(Income income)
catch (Exception ex)
{
throw new NotImplementedException();
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectFamilyBudget.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,18 +13,94 @@ namespace ProjectFamilyBudget.Repositories.Implementations;
public class PeopleExpenseRepository : IPeopleExpense
{
public IEnumerable<PeopleExpense> ReadPeopleExpense(DateTime? dateForm = null, DateTime? dateTo = null, int? peopleId = null, int? expenseId = null)
private readonly IConnectionString _connectionString;
private readonly ILogger<PeopleExpenseRepository> _logger;
public PeopleExpenseRepository(IConnectionString connectionString, ILogger<PeopleExpenseRepository> logger)
{
return [];
_connectionString = connectionString;
_logger = logger;
}
public void CreatePeopleExpense(PeopleExpense peopleExpense)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(peopleExpense));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO PeopleExpense (PeopleId, Date)
VALUES (@PeopleId, @Date);
SELECT MAX(Id) FROM PeopleIncome";
var peopleExpenseId =
connection.QueryFirst<int>(queryInsert, peopleExpense, transaction);
var querySubInsert = @"
INSERT INTO ExpensePeopleExpense (ExpenseId, PeopleExpenseId, Sum)
VALUES (@IncomeId, @PeopleIncomeId, @Sum)";
foreach (var elem in peopleExpense.ExpensePeopleExpenses)
{
connection.Execute(querySubInsert, new
{
peopleExpenseId,
elem.ExpenseId,
elem.Sum
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletPeopleExpense(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 ExpensePeopleExpense
WHERE PeopleExpenseId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM PeopleExpense
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<PeopleExpense> ReadPeopleExpense(DateTime? dateForm = null, DateTime? dateTo = null, int? peopleId = null, int? expenseId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM PeopleExpense";
var peopleExpenses = connection.Query<PeopleExpense>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(peopleExpenses));
return peopleExpenses;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectFamilyBudget.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
@ -9,20 +13,93 @@ namespace ProjectFamilyBudget.Repositories.Implementations;
public class PeopleIncomeRepository : IPeopleIncome
{
public IEnumerable<PeopleIncome> ReadPeopleIncome(DateTime? dateForm = null, DateTime? dateTo = null, int? peopleId = null, int? incomeId = null)
private readonly IConnectionString _connectionString;
private readonly ILogger<PeopleIncomeRepository> _logger;
public PeopleIncomeRepository(IConnectionString connectionString, ILogger<PeopleIncomeRepository> logger)
{
return [];
_connectionString = connectionString;
_logger = logger;
}
public void CreatePeopleIncome(PeopleIncome peopleIncome)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(peopleIncome));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO PeopleIncome (PeopleId, Date)
VALUES (@PeopleId, @Date);
SELECT MAX(Id) FROM PeopleIncome";
var peopleIncomeId =
connection.QueryFirst<int>(queryInsert, peopleIncome, transaction);
var querySubInsert = @"
INSERT INTO IncomePeopleIncome (IncomeId, PeopleIncomeId, Sum)
VALUES (@IncomeId, @PeopleIncomeId, @Sum)";
foreach (var elem in peopleIncome.IncomePeopleIncomes)
{
connection.Execute(querySubInsert, new
{
peopleIncomeId,
elem.IncomeId,
elem.Sum
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletPeopleIncome(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 IncomePeopleIncome
WHERE PeopleIncomeId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM PeopleIncome
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<PeopleIncome> ReadPeopleIncome(DateTime? dateForm = null, DateTime? dateTo = null, int? peopleId = null, int? incomeId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM PeopleIncome";
var peopleIncomes = connection.Query<PeopleIncome>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(peopleIncomes));
return peopleIncomes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,4 +1,8 @@
using ProjectFamilyBudget.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectFamilyBudget.Entities;
using ProjectFamilyBudget.Entities.Enums;
using System;
using System.Collections.Generic;
@ -10,28 +14,112 @@ namespace ProjectFamilyBudget.Repositories.Implementations;
public class PeopleRepository : IPeople
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PeopleRepository> _logger;
public PeopleRepository(IConnectionString connectionString, ILogger<PeopleRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreatePeople(People people)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(people));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO People (Name, LastName, Age, MemberType)
VALUES (@Name, @LastName, @Age, @MemberType)";
connection.Execute(queryInsert, people);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdatePeople(People people)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",JsonConvert.SerializeObject(people));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE People
SET
Name=@Name,
LastName=@LastName,
Age=@Age,
MemberType=@MemberType
WHERE Id=@Id";
connection.Execute(queryUpdate, people);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeletePeople(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM People
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public People ReadPeopleById(int id)
{
return People.CreateEntity(0, string.Empty, string.Empty, 0, FamilyMemberType.None);
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM People
WHERE Id=@id";
var people = connection.QueryFirst<People>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(people));
return people;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<People> ReadPeople()
{
return [];
}
public void UpdatePeople(People people)
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM People";
var peoples = connection.Query<People>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",JsonConvert.SerializeObject(peoples));
return peoples;
}
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/budget_log.txt",
"rollingInterval": "Day"
}
}
]
}
}