Лабораторная работа 2

This commit is contained in:
asakky 2024-12-05 22:17:30 +04:00
parent 5809386861
commit 843fccd3ba
18 changed files with 594 additions and 53 deletions

View File

@ -8,14 +8,17 @@ namespace ProjectLibrary.Entities;
public class BookIssue public class BookIssue
{ {
public int IssueId { get; private set; }
public string Description { get; private set; } public string Description { get; private set; }
public int BookId { get;private set; } public int BookId { get;private set; }
public static BookIssue CreateElement(string description, int bookId) public static BookIssue CreateElement(int issueId, string description, int bookId)
{ {
return new BookIssue return new BookIssue
{ {
IssueId = issueId,
Description = description, Description = description,
BookId = bookId BookId = bookId
}; };

View File

@ -8,18 +8,19 @@ namespace ProjectLibrary.Entities;
public class BookRestoration public class BookRestoration
{ {
public int Id { get; private set; }
public int LibrarianId { get; private set; } public int LibrarianId { get; private set; }
public int BookId { get; private set; } public int BookId { get; private set; }
public DateTime RestorationDate { get; private set; } public DateTime RestorationDate { get; private set; }
public string Description { get; private set; } = string.Empty; public string Description { get; private set; } = string.Empty;
public static BookRestoration CreateOperation(int librarianId, int bookId, string description) public static BookRestoration CreateOperation(int id, int librarianId, int bookId, string description)
{ {
return new BookRestoration return new BookRestoration
{ {
Id = id,
LibrarianId = librarianId, LibrarianId = librarianId,
BookId = bookId, BookId = bookId,
RestorationDate = DateTime.Now, RestorationDate = DateTime.Now,

View File

@ -30,8 +30,6 @@ namespace ProjectLibrary.Forms
comboBoxSelectLibrarian.DataSource = librarianRepository.ReadLibrarians(); comboBoxSelectLibrarian.DataSource = librarianRepository.ReadLibrarians();
comboBoxSelectLibrarian.DisplayMember = "Name"; comboBoxSelectLibrarian.DisplayMember = "Name";
comboBoxSelectLibrarian.ValueMember = "Id"; comboBoxSelectLibrarian.ValueMember = "Id";
} }
private void ButtonSave_Click(object sender, EventArgs e) private void ButtonSave_Click(object sender, EventArgs e)
@ -42,7 +40,7 @@ namespace ProjectLibrary.Forms
{ {
throw new Exception("Имеются незаполненные поля"); throw new Exception("Имеются незаполненные поля");
} }
_bookRestorationRepository.CreateBookRestoration(BookRestoration.CreateOperation((int)comboBoxSelectLibrarian.SelectedValue!, (int)comboBoxSelectBook.SelectedValue!, textBoxDescription.Text)); _bookRestorationRepository.CreateBookRestoration(BookRestoration.CreateOperation(Convert.ToInt32(0),(int)comboBoxSelectLibrarian.SelectedValue!, (int)comboBoxSelectBook.SelectedValue!, textBoxDescription.Text));
Close(); Close();
} }
catch (Exception ex) catch (Exception ex)

View File

@ -30,8 +30,8 @@
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
panel1 = new Panel(); panel1 = new Panel();
buttonDel = new Button();
buttonAdd = new Button(); buttonAdd = new Button();
ButtonDel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
panel1.SuspendLayout(); panel1.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -56,7 +56,7 @@
// //
// panel1 // panel1
// //
panel1.Controls.Add(buttonDel); 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 +64,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;
@ -86,6 +75,17 @@
buttonAdd.UseVisualStyleBackColor = true; buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click; buttonAdd.Click += ButtonAdd_Click;
// //
// 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;
//
// FormBookRestorations // FormBookRestorations
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -105,7 +105,7 @@
private DataGridView dataGridView; private DataGridView dataGridView;
private Panel panel1; private Panel panel1;
private Button buttonDel;
private Button buttonAdd; private Button buttonAdd;
private Button ButtonDel;
} }
} }

View File

@ -27,9 +27,9 @@ namespace ProjectLibrary.Forms
comboBoxSelectReader.DataSource = readerRepository.ReadReaders(); comboBoxSelectReader.DataSource = readerRepository.ReadReaders();
comboBoxSelectReader.DisplayMember = "Name"; comboBoxSelectReader.DisplayMember = "Name";
comboBoxSelectReader.ValueMember = "Id"; comboBoxSelectReader.ValueMember = "Id";
ColumnBook.DataSource = bookRepository.ReadBooks();
ColumnBook.DisplayMember = "Title";
ColumnBook.ValueMember = "Id"; ColumnBook.ValueMember = "Id";
ColumnBook.DisplayMember = "Title";
ColumnBook.DataSource = bookRepository.ReadBooks();
} }
private void ButtonSave_Click(object sender, EventArgs e) private void ButtonSave_Click(object sender, EventArgs e)
@ -41,7 +41,7 @@ namespace ProjectLibrary.Forms
{ {
throw new Exception("Имеются незаполненные поля"); throw new Exception("Имеются незаполненные поля");
} }
_issueRepository.CreateIssue(Issue.CreateOperation(0, (int)comboBoxSelectLibrarian.SelectedValue!, (int)comboBoxSelectReader.SelectedValue!, _issueRepository.CreateIssue(Issue.CreateOperation(Convert.ToInt32(0), (int)comboBoxSelectLibrarian.SelectedValue!, (int)comboBoxSelectReader.SelectedValue!,
CreateListBookIssueFromDataGrid())); CreateListBookIssueFromDataGrid()));
Close(); Close();
} }
@ -63,7 +63,7 @@ namespace ProjectLibrary.Forms
{ {
continue; continue;
} }
list.Add(BookIssue.CreateElement(string.Empty, list.Add(BookIssue.CreateElement(Convert.ToInt32(comboBoxSelectLibrarian.SelectedValue),string.Empty,
Convert.ToInt32(row.Cells["ColumnBook"].Value))); Convert.ToInt32(row.Cells["ColumnBook"].Value)));
} }
return list; return list;

View File

@ -30,8 +30,8 @@
{ {
dataGridView = new DataGridView(); dataGridView = new DataGridView();
panel1 = new Panel(); panel1 = new Panel();
buttonDel = new Button();
buttonAdd = new Button(); buttonAdd = new Button();
ButtonDel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
panel1.SuspendLayout(); panel1.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -56,7 +56,7 @@
// //
// panel1 // panel1
// //
panel1.Controls.Add(buttonDel); 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 +64,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;
@ -86,6 +75,17 @@
buttonAdd.UseVisualStyleBackColor = true; buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click; buttonAdd.Click += ButtonAdd_Click;
// //
// 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 = 2;
ButtonDel.UseVisualStyleBackColor = true;
ButtonDel.Click += ButtonDel_Click;
//
// FormIssues // FormIssues
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -105,7 +105,7 @@
private DataGridView dataGridView; private DataGridView dataGridView;
private Panel panel1; private Panel panel1;
private Button buttonDel;
private Button buttonAdd; private Button buttonAdd;
private Button ButtonDel;
} }
} }

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>

View File

@ -9,7 +9,9 @@ namespace ProjectLibrary.Repositories;
public interface IBookRestorationRepository public interface IBookRestorationRepository
{ {
IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId = null, int? bookId=null, string? description = null, DateTime? dateFrom = null, DateTime? dateTo = null); IEnumerable<BookRestoration> ReadBookRestorations(int? id = null, int? librarianId = null, int? bookId=null, string? description = null, DateTime? dateFrom = null, DateTime? dateTo = null);
void CreateBookRestoration(BookRestoration bookRestoration); void CreateBookRestoration(BookRestoration bookRestoration);
void DeleteBookRestoration(int id); 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
{
string ConnectionString { get; }
}

View File

@ -10,6 +10,8 @@ namespace ProjectLibrary.Repositories;
public interface IIssueRepository 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); void DeleteIssue(int id);
} }

View File

@ -1,33 +1,138 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
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;
namespace ProjectLibrary.Repositories.Implementations; 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
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Book (Title, Topic, IsIssued) VALUES (@Title, @Topic, @IsIssued)";
connection.Execute(queryInsert, 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
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Book
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
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Book
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
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Book";
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) public void UpdateBook(Book book)
{ {
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(book));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Book
SET
Title=@Title,
Topic=@Topic,
IsIssued=@IsIssued
WHERE Id=@Id";
connection.Execute(queryUpdate, book);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
} }

View File

@ -1,6 +1,11 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
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 +14,76 @@ namespace ProjectLibrary.Repositories.Implementations;
public class BookRestorationRepository : IBookRestorationRepository public class BookRestorationRepository : IBookRestorationRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<BookRestorationRepository> _logger;
public BookRestorationRepository(IConnectionString connectionString, ILogger<BookRestorationRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateBookRestoration(BookRestoration bookRestoration) public void CreateBookRestoration(BookRestoration bookRestoration)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(bookRestoration));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO BookRestoration (LibrarianId, BookId, RestorationDate, Description)
VALUES (@LibrarianId, @BookId, @RestorationDate, @Description)";
connection.Execute(queryInsert, bookRestoration);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeleteBookRestoration(int id) public void DeleteBookRestoration(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM BookRestoration
WHERE Id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public IEnumerable<BookRestoration> ReadBookRestorations(int? librarianId, int? bookId, string? description, DateTime? dateFrom = null, DateTime? dateTo = null) public IEnumerable<BookRestoration> ReadBookRestorations(int? id, int? librarianId, int? bookId, string? description, DateTime? dateFrom = null, DateTime? dateTo = null)
{ {
return []; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM BookRestoration";
var bookRestoration =
connection.Query<BookRestoration>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(bookRestoration));
return bookRestoration;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }

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.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Server=localhost;Port=5432;Username=postgres;Password=postgres;Database=library";
}

View File

@ -1,6 +1,11 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
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 +14,99 @@ namespace ProjectLibrary.Repositories.Implementations;
public class IssueRepository : IIssueRepository public class IssueRepository : IIssueRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<IssueRepository> _logger;
public IssueRepository(IConnectionString connectionString, ILogger<IssueRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateIssue(Issue issue) public void CreateIssue(Issue issue)
{ {
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(issue));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Issue (IssueDate, DueDate, ReturnDate, LibrarianId, ReaderId)
VALUES (@IssueDate, @DueDate, @ReturnDate, @LibrarianId, @ReaderId)
Returning Id";
var issueId =
connection.QueryFirst<int>(queryInsert, new
{
issue.IssueDate, issue.DueDate,issue.ReturnDate,issue.LibrarianId, issue.ReaderId
}, transaction);
var querySubInsert = @"
INSERT INTO BookIssue (Description, BookId, IssueId)
VALUES (@Description,@BookId, @IssueId)";
foreach (var elem in issue.BookIssue)
{
connection.Execute(querySubInsert, new
{
IssueId = issueId,
elem.Description,
elem.BookId
}, transaction); ;
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeleteIssue(int id) public void DeleteIssue(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM BookIssue
WHERE IssueId=@Id";
connection.Execute(queryDelete, new { id });
var queryDeleteIssue = @"
DELETE FROM Issue WHERE Id = @Id";
connection.Execute(queryDeleteIssue, new { id });
}
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
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Issue";
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,11 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
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 +14,125 @@ 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
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Librarian (Name, AllowedTopic) VALUES (@Name, @AllowedTopic)";
connection.Execute(queryInsert, 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
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Librarian
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
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Librarian
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
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Librarian";
var librarians = connection.Query<Librarian>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(librarians));
return librarians;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
public void UpdateLibrarian(Librarian librarian) public void UpdateLibrarian(Librarian librarian)
{ {
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(librarian));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Librarian
SET
Name=@Name,
AllowedTopic=@AllowedTopic
WHERE Id=@Id";
connection.Execute(queryUpdate, librarian);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
} }
} }

View File

@ -1,6 +1,11 @@
using ProjectLibrary.Entities; using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
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 +14,124 @@ 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
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" INSERT INTO Reader (Name, LibraryCard, CardValidity) VALUES (@Name, @LibraryCard, @CardValidity)";
connection.Execute(queryInsert, reader);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
} }
public void DeleteReader(int id) public void DeleteReader(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Reader
WHERE Id=@Id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
public Reader ReadReaderById(int id) public Reader ReadReaderById(int id)
{ {
return Reader.CreateEntity(0,string.Empty,0); _logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Reader
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() public IEnumerable<Reader> ReadReaders()
{ {
return []; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Reader";
var readers = connection.Query<Reader>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(readers));
return readers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
public void UpdateReader(Reader reader) public void UpdateReader(Reader reader)
{ {
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(reader));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Reader
SET
Name=@Name,
LibraryCard=@LibraryCard,
CardValidity=@CardValidity
WHERE Id=@Id";
connection.Execute(queryUpdate, reader);
}
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": "F:\\OTP2\\ProjectLibrary\\ProjectLibrary\\library_log.txt",
"rollingInterval": "Day"
}
}
]
}
}