почти

This commit is contained in:
asakky 2024-11-22 04:43:19 +04:00
parent 07cf9a9998
commit cba0da95da
17 changed files with 516 additions and 140 deletions

View File

@ -49,6 +49,5 @@ namespace ProjectLibrary.Forms
} }
private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private void ButtonCancel_Click(object sender, EventArgs e) => Close();
} }
} }

View File

@ -30,7 +30,6 @@
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
panel1 = new Panel(); panel1 = new Panel();
buttonDel = new Button();
buttonAdd = new Button(); buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
panel1.SuspendLayout(); panel1.SuspendLayout();
@ -56,7 +55,6 @@
// //
// panel1 // panel1
// //
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonAdd); panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right; panel1.Dock = DockStyle.Right;
panel1.Location = new Point(656, 0); panel1.Location = new Point(656, 0);
@ -64,17 +62,6 @@
panel1.Size = new Size(144, 450); panel1.Size = new Size(144, 450);
panel1.TabIndex = 2; panel1.TabIndex = 2;
// //
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.minus;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(33, 119);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(75, 60);
buttonDel.TabIndex = 1;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonAdd // buttonAdd
// //
buttonAdd.BackgroundImage = Properties.Resources.plus; buttonAdd.BackgroundImage = Properties.Resources.plus;
@ -105,7 +92,6 @@
private DataGridView dataGridView; private DataGridView dataGridView;
private Panel panel1; private Panel panel1;
private Button buttonDel;
private Button buttonAdd; private Button buttonAdd;
} }
} }

View File

@ -53,40 +53,6 @@ namespace ProjectLibrary.Forms
} }
} }
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_bookRestorationRepository.DeleteBookRestoration(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _bookRestorationRepository.ReadBookRestorations(); private void LoadList() => dataGridView.DataSource = _bookRestorationRepository.ReadBookRestorations();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
} }
} }

View File

@ -30,8 +30,6 @@
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
panel1 = new Panel(); panel1 = new Panel();
buttonUpd = new Button();
buttonDel = new Button();
buttonAdd = new Button(); buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
panel1.SuspendLayout(); panel1.SuspendLayout();
@ -57,8 +55,6 @@
// //
// panel1 // panel1
// //
panel1.Controls.Add(buttonUpd);
panel1.Controls.Add(buttonDel);
panel1.Controls.Add(buttonAdd); panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right; panel1.Dock = DockStyle.Right;
panel1.Location = new Point(656, 0); panel1.Location = new Point(656, 0);
@ -66,17 +62,6 @@
panel1.Size = new Size(144, 450); panel1.Size = new Size(144, 450);
panel1.TabIndex = 2; panel1.TabIndex = 2;
// //
// buttonDel
//
buttonDel.BackgroundImage = Properties.Resources.minus;
buttonDel.BackgroundImageLayout = ImageLayout.Stretch;
buttonDel.Location = new Point(33, 119);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(75, 60);
buttonDel.TabIndex = 1;
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonAdd // buttonAdd
// //
buttonAdd.BackgroundImage = Properties.Resources.plus; buttonAdd.BackgroundImage = Properties.Resources.plus;
@ -107,8 +92,6 @@
private DataGridView dataGridView; private DataGridView dataGridView;
private Panel panel1; private Panel panel1;
private Button buttonUpd;
private Button buttonDel;
private Button buttonAdd; private Button buttonAdd;
} }
} }

View File

@ -53,43 +53,6 @@ namespace ProjectLibrary.Forms
} }
} }
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_issueRepository.DeleteIssue(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _issueRepository.ReadIssue(); private void LoadList() => dataGridView.DataSource = _issueRepository.ReadIssue();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
} }
} }

View File

@ -2,6 +2,10 @@ using Unity.Lifetime;
using Unity; using Unity;
using ProjectLibrary.Repositories; using ProjectLibrary.Repositories;
using ProjectLibrary.Repositories.Implementations; using ProjectLibrary.Repositories.Implementations;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.Configuration;
using Unity.Microsoft.Logging;
namespace ProjectLibrary namespace ProjectLibrary
{ {
@ -22,12 +26,26 @@ namespace ProjectLibrary
private static IUnityContainer CreateContainer() private static IUnityContainer CreateContainer()
{ {
var container = new UnityContainer(); var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IBookRepository, BookRepository>(new TransientLifetimeManager()); container.RegisterType<IBookRepository, BookRepository>(new TransientLifetimeManager());
container.RegisterType<IIssueRepository, IssueRepository>(new TransientLifetimeManager()); container.RegisterType<IIssueRepository, IssueRepository>(new TransientLifetimeManager());
container.RegisterType<ILibrarianRepository, LibrarianRepository>(new TransientLifetimeManager()); container.RegisterType<ILibrarianRepository, LibrarianRepository>(new TransientLifetimeManager());
container.RegisterType<IReaderRepository, ReaderRepository>(new TransientLifetimeManager()); container.RegisterType<IReaderRepository, ReaderRepository>(new TransientLifetimeManager());
container.RegisterType<IBookRestorationRepository, BookRestorationRepository>(new TransientLifetimeManager()); container.RegisterType<IBookRestorationRepository, BookRestorationRepository>(new TransientLifetimeManager());
return container; 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,19 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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.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="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" /> <PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -27,4 +39,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -11,5 +11,4 @@ public interface IBookRestorationRepository
{ {
IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId = null, string? description = null, DateTime? dateFrom = null, DateTime? dateTo = null); IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId = null, string? description = null, DateTime? dateFrom = null, DateTime? dateTo = null);
void CreateBookRestoration(BookRestoration bookRestoration); void CreateBookRestoration(BookRestoration bookRestoration);
void DeleteBookRestoration(int id);
} }

View File

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

View File

@ -11,5 +11,4 @@ public interface IIssueRepository
{ {
IEnumerable<Issue> ReadIssue(int? id=null, int? librarianId = null, int? readerId = null, DateTime? dateFrom = null, DateTime? dateTo = null); IEnumerable<Issue> ReadIssue(int? id=null, int? librarianId = null, int? readerId = null, DateTime? dateFrom = null, DateTime? dateTo = null);
void CreateIssue(Issue issue); void CreateIssue(Issue issue);
void DeleteIssue(int id);
} }

View File

@ -1,6 +1,10 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectLibrary.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,25 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations;
public class BookRepository : IBookRepository public class BookRepository : IBookRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<BookRepository> _logger;
public BookRepository(IConnectionString connectionString, ILogger<BookRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateBook(Book book) public void CreateBook(Book book)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(book));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Books (Title, Topic, IsIssued) VALUES (@Title, @Topic, @IsIssued)";
connection.Execute(queryInsert, book);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateBook(Book book)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(book));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Books
SET
Title=@Title,
Topic=@Topic,
IsIssued=@IsIssued,
WHERE Id=@Id";
connection.Execute(queryUpdate, book);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
public void DeleteBook(int id) public void DeleteBook(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Books
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public Book ReadBookById(int id) public Book ReadBookById(int id)
{ {
return Book.CreateEntity(0, string.Empty, 0, false); _logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Books
WHERE [Id]=@id";
var book = connection.QueryFirst<Book>(querySelect, new {id});
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(book));
return book;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public IEnumerable<Book> ReadBooks() public IEnumerable<Book> ReadBooks()
{ {
return []; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Books";
var books = connection.Query<Book>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(books));
return books;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
public void UpdateBook(Book book)
{
}
} }

View File

@ -1,6 +1,10 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectLibrary.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,16 +13,55 @@ namespace ProjectLibrary.Repositories.Implementations;
public class BookRestorationRepository : IBookRestorationRepository public class BookRestorationRepository : IBookRestorationRepository
{ {
public void CreateBookRestoration(BookRestoration bookRestoration) private readonly IConnectionString _connectionString;
private readonly ILogger<BookRestorationRepository> _logger;
public BookRestorationRepository(IConnectionString connectionString, ILogger<BookRestorationRepository> logger)
{ {
_connectionString = connectionString;
_logger = logger;
} }
public void DeleteBookRestoration(int id) public void CreateBookRestoration(BookRestoration bookRestoration)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(bookRestoration));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO BookRestorations (LibrarianId, RestorationDate, Description)
VALUES (@LibrarianId, @RestorationDate, @Description)";
connection.Execute(queryInsert, bookRestoration);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId, string? description, DateTime? dateFrom = null, DateTime? dateTo = null) public IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId, string? description, DateTime? dateFrom = null, DateTime? dateTo = null)
{ {
return []; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM BookRestorations";
var bookRestorations =
connection.Query<BookRestoration>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(bookRestorations));
return bookRestorations;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
namespace ProjectLibrary.Repositories.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost,5432;Database=library;Uid=postgres;Pwd=postgres;";
}

View File

@ -1,6 +1,10 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectLibrary.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,16 +13,72 @@ namespace ProjectLibrary.Repositories.Implementations;
public class IssueRepository : IIssueRepository public class IssueRepository : IIssueRepository
{ {
public void CreateIssue(Issue issue) private readonly IConnectionString _connectionString;
private readonly ILogger<IssueRepository> _logger;
public IssueRepository(IConnectionString connectionString, ILogger<IssueRepository> logger)
{ {
_connectionString = connectionString;
_logger = logger;
} }
public void DeleteIssue(int id) public void CreateIssue(Issue issue)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(issue));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Issues (IssueDate, DueDate, ReturnDate, LibrarianId, ReaderId)
VALUES (@IssueDate, @DueDate, @ReturnDate, @LibrarianId, @ReaderId);
SELECT MAX(Id) FROM Issues";
var issueId =
connection.QueryFirst<int>(queryInsert, issue, transaction);
var querySubInsert = @"
INSERT INTO BookIssue (Description, BookId, IssueId)
VALUES (@Description,@BookId, @IssueId)";
foreach (var elem in issue.BookIssue)
{
connection.Execute(querySubInsert, new
{
issueId,
elem.Description,
elem.BookId
}, transaction); ;
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public IEnumerable<Issue> ReadIssue(int? id, int? librarianId, int? readerId, DateTime? dateFrom = null, DateTime? dateTo = null) public IEnumerable<Issue> ReadIssue(int? id, int? librarianId, int? readerId, DateTime? dateFrom = null, DateTime? dateTo = null)
{ {
return []; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM FeedReplenishments";
var issue =
connection.Query<Issue>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(issue));
return issue;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

View File

@ -1,6 +1,10 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectLibrary.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,26 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations;
public class LibrarianRepository : ILibrarianRepository public class LibrarianRepository : ILibrarianRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<LibrarianRepository> _logger;
public LibrarianRepository(IConnectionString connectionString, ILogger<LibrarianRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateLibrarian(Librarian librarian) public void CreateLibrarian(Librarian librarian)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(librarian));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Librarians (Name, AllowedTopic) VALUES (@Name, @AllowedTopic)";
connection.Execute(queryInsert, librarian);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateLibrarian(Librarian librarian)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(librarian));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Librarians
SET
Name=@Name,
AllowedTopic=@AllowedTopic,
WHERE Id=@Id";
connection.Execute(queryUpdate, librarian);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
public void DeleteLibrarian(int id) public void DeleteLibrarian(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Librarians
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public Librarian ReadLibrarianById(int id) public Librarian ReadLibrarianById(int id)
{ {
return Librarian.CreateEntity(0,string.Empty,0); _logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Librarians
WHERE [Id]=@id";
var librarian = connection.QueryFirst<Librarian>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(librarian));
return librarian;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
} }
public IEnumerable<Librarian> ReadLibrarians() public IEnumerable<Librarian> ReadLibrarians()
{ {
return []; _logger.LogInformation("Получение всех объектов");
} try
{
public void UpdateLibrarian(Librarian librarian) using var connection = new
{ SqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Librarians";
var librarians = connection.Query<Librarian>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(librarians));
return librarians;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

View File

@ -1,6 +1,10 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectLibrary.Entities;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,25 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations;
public class ReaderRepository : IReaderRepository public class ReaderRepository : IReaderRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<ReaderRepository> _logger;
public ReaderRepository(IConnectionString connectionString, ILogger<ReaderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateReader(Reader reader) public void CreateReader(Reader reader)
{ {
} _logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(reader));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Readers (Name, LibraryCard, CardValidity) VALUES (@Name, @LibraryCard, @CardValidity)";
connection.Execute(queryInsert, reader);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
public void DeleteReader(int id)
{
}
public Reader ReadReaderById(int id)
{
return Reader.CreateEntity(0,string.Empty,0);
}
public IEnumerable<Reader> ReadReaders()
{
return [];
} }
public void UpdateReader(Reader reader) public void UpdateReader(Reader reader)
{ {
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(reader));
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Readers
SET
Name=@Name,
LibraryCard=@LibraryCard,
CardValidity=@CardValidity,
WHERE Id=@Id";
connection.Execute(queryUpdate, reader);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteReader(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Readers
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Reader ReadReaderById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Readers
WHERE [Id]=@id";
var reader = connection.QueryFirst<Reader>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(reader));
return reader;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Reader> ReadReaders()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
SqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Readers";
var readers = connection.Query<Reader>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(readers));
return readers;
}
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/library_log.txt",
"rollingInterval": "Day"
}
}
]
}
}