diff --git a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestoration.cs b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestoration.cs index 3e4ea5d..4d7e8e3 100644 --- a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestoration.cs +++ b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestoration.cs @@ -49,6 +49,5 @@ namespace ProjectLibrary.Forms } private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - } } diff --git a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.Designer.cs b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.Designer.cs index 66f0fb4..b35a428 100644 --- a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.Designer.cs +++ b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.Designer.cs @@ -30,7 +30,6 @@ { dataGridView = new DataGridView(); panel1 = new Panel(); - buttonDel = new Button(); buttonAdd = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); panel1.SuspendLayout(); @@ -56,7 +55,6 @@ // // panel1 // - panel1.Controls.Add(buttonDel); panel1.Controls.Add(buttonAdd); panel1.Dock = DockStyle.Right; panel1.Location = new Point(656, 0); @@ -64,17 +62,6 @@ panel1.Size = new Size(144, 450); 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.BackgroundImage = Properties.Resources.plus; @@ -105,7 +92,6 @@ private DataGridView dataGridView; private Panel panel1; - private Button buttonDel; private Button buttonAdd; } } \ No newline at end of file diff --git a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.cs b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.cs index 91d1ee4..c9ad51e 100644 --- a/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.cs +++ b/ProjectLibrary/ProjectLibrary/Forms/FormBookRestorations.cs @@ -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 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; - } } } diff --git a/ProjectLibrary/ProjectLibrary/Forms/FormIssues.Designer.cs b/ProjectLibrary/ProjectLibrary/Forms/FormIssues.Designer.cs index 234a3ca..a8046dc 100644 --- a/ProjectLibrary/ProjectLibrary/Forms/FormIssues.Designer.cs +++ b/ProjectLibrary/ProjectLibrary/Forms/FormIssues.Designer.cs @@ -30,8 +30,6 @@ { dataGridView = new DataGridView(); panel1 = new Panel(); - buttonUpd = new Button(); - buttonDel = new Button(); buttonAdd = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); panel1.SuspendLayout(); @@ -57,8 +55,6 @@ // // panel1 // - panel1.Controls.Add(buttonUpd); - panel1.Controls.Add(buttonDel); panel1.Controls.Add(buttonAdd); panel1.Dock = DockStyle.Right; panel1.Location = new Point(656, 0); @@ -66,17 +62,6 @@ panel1.Size = new Size(144, 450); 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.BackgroundImage = Properties.Resources.plus; @@ -107,8 +92,6 @@ private DataGridView dataGridView; private Panel panel1; - private Button buttonUpd; - private Button buttonDel; private Button buttonAdd; } } \ No newline at end of file diff --git a/ProjectLibrary/ProjectLibrary/Forms/FormIssues.cs b/ProjectLibrary/ProjectLibrary/Forms/FormIssues.cs index 71840fa..825c927 100644 --- a/ProjectLibrary/ProjectLibrary/Forms/FormIssues.cs +++ b/ProjectLibrary/ProjectLibrary/Forms/FormIssues.cs @@ -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 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; - } } } diff --git a/ProjectLibrary/ProjectLibrary/Program.cs b/ProjectLibrary/ProjectLibrary/Program.cs index b699bb0..63de25c 100644 --- a/ProjectLibrary/ProjectLibrary/Program.cs +++ b/ProjectLibrary/ProjectLibrary/Program.cs @@ -2,6 +2,10 @@ using Unity.Lifetime; using Unity; using ProjectLibrary.Repositories; using ProjectLibrary.Repositories.Implementations; +using Microsoft.Extensions.Logging; +using Serilog; +using Microsoft.Extensions.Configuration; +using Unity.Microsoft.Logging; namespace ProjectLibrary { @@ -22,12 +26,26 @@ namespace ProjectLibrary private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); + container.RegisterType(new SingletonLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(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; + } } } \ No newline at end of file diff --git a/ProjectLibrary/ProjectLibrary/ProjectLibrary.csproj b/ProjectLibrary/ProjectLibrary/ProjectLibrary.csproj index accbdf0..ebed082 100644 --- a/ProjectLibrary/ProjectLibrary/ProjectLibrary.csproj +++ b/ProjectLibrary/ProjectLibrary/ProjectLibrary.csproj @@ -9,7 +9,19 @@ + + + + + + + + + + + + @@ -27,4 +39,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectLibrary/ProjectLibrary/Repositories/IBookRestorationRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/IBookRestorationRepository.cs index 04e1db3..7f5cf4d 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/IBookRestorationRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/IBookRestorationRepository.cs @@ -11,5 +11,4 @@ public interface IBookRestorationRepository { IEnumerable ReadBookRestorations(int? librarianId = null, string? description = null, DateTime? dateFrom = null, DateTime? dateTo = null); void CreateBookRestoration(BookRestoration bookRestoration); - void DeleteBookRestoration(int id); } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/IConnectionString.cs b/ProjectLibrary/ProjectLibrary/Repositories/IConnectionString.cs new file mode 100644 index 0000000..6c48d81 --- /dev/null +++ b/ProjectLibrary/ProjectLibrary/Repositories/IConnectionString.cs @@ -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; } +} diff --git a/ProjectLibrary/ProjectLibrary/Repositories/IIssueRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/IIssueRepository.cs index 46437b2..6a8744f 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/IIssueRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/IIssueRepository.cs @@ -11,5 +11,4 @@ public interface IIssueRepository { IEnumerable ReadIssue(int? id=null, int? librarianId = null, int? readerId = null, DateTime? dateFrom = null, DateTime? dateTo = null); void CreateIssue(Issue issue); - void DeleteIssue(int id); } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRepository.cs index ff34501..cd1f132 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRepository.cs @@ -1,6 +1,10 @@ -using ProjectLibrary.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using ProjectLibrary.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,25 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations; public class BookRepository : IBookRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public BookRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + 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) { + _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) { - 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(querySelect, new {id}); + + + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(book)); + return book; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadBooks() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + SqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Books"; + var books = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(books)); + return books; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } - public void UpdateBook(Book book) - { - } } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRestorationRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRestorationRepository.cs index bd6bb35..4502510 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRestorationRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/BookRestorationRepository.cs @@ -1,6 +1,10 @@ -using ProjectLibrary.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using ProjectLibrary.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,16 +13,55 @@ namespace ProjectLibrary.Repositories.Implementations; public class BookRestorationRepository : IBookRestorationRepository { - public void CreateBookRestoration(BookRestoration bookRestoration) + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public BookRestorationRepository(IConnectionString connectionString, ILogger 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 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(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(bookRestorations)); + return bookRestorations; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ConnectionString.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..12b4e6c --- /dev/null +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ConnectionString.cs @@ -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;"; +} diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/IssueRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/IssueRepository.cs index 13eb810..eddf062 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/IssueRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/IssueRepository.cs @@ -1,6 +1,10 @@ -using ProjectLibrary.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using ProjectLibrary.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,16 +13,72 @@ namespace ProjectLibrary.Repositories.Implementations; public class IssueRepository : IIssueRepository { - public void CreateIssue(Issue issue) + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public IssueRepository(IConnectionString connectionString, ILogger 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(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 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(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(issue)); + return issue; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/LibrarianRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/LibrarianRepository.cs index 36439ab..99bffbe 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/LibrarianRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/LibrarianRepository.cs @@ -1,6 +1,10 @@ -using ProjectLibrary.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using ProjectLibrary.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,26 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations; public class LibrarianRepository : ILibrarianRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public LibrarianRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + 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) { + _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) { - 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(querySelect, new { id }); + + + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(librarian)); + return librarian; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadLibrarians() { - return []; - } - - public void UpdateLibrarian(Librarian librarian) - { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + SqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Librarians"; + var librarians = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(librarians)); + return librarians; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ReaderRepository.cs b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ReaderRepository.cs index 7a8e857..302d0fa 100644 --- a/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ReaderRepository.cs +++ b/ProjectLibrary/ProjectLibrary/Repositories/Implementations/ReaderRepository.cs @@ -1,6 +1,10 @@ -using ProjectLibrary.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using ProjectLibrary.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,25 +13,122 @@ namespace ProjectLibrary.Repositories.Implementations; public class ReaderRepository : IReaderRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public ReaderRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + 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 ReadReaders() - { - return []; } 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(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(reader)); + return reader; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadReaders() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + SqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Readers"; + var readers = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(readers)); + return readers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectLibrary/ProjectLibrary/appsettings.json b/ProjectLibrary/ProjectLibrary/appsettings.json new file mode 100644 index 0000000..6a795ca --- /dev/null +++ b/ProjectLibrary/ProjectLibrary/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/library_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file