From f18b475248aa6e8120640d947f767b06360ad92f Mon Sep 17 00:00:00 2001 From: "a.puchkina" Date: Mon, 11 Nov 2024 19:40:06 +0400 Subject: [PATCH] =?UTF-8?q?=D1=83=D1=80=D0=B0=20=D1=83=D1=80=D0=B0=203=20?= =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BusinessLogic/AuthorLogic.cs | 96 ++-- .../BusinessLogic/BookLogic.cs | 100 ++-- .../BindingModels/AuthorBindingModel.cs | 10 +- .../BindingModels/BookBindingModel.cs | 10 +- .../BusinessLogicsContracts/IAuthorLogic.cs | 9 +- .../BusinessLogicsContracts/IBookLogic.cs | 9 +- .../SearchModels/AuthorSearchModel.cs | 7 + .../Contracts/SearchModels/BookSearchModel.cs | 7 + .../StorageContracts/IAuthorStorage.cs | 12 +- .../StorageContracts/IBookStorage.cs | 12 +- .../Contracts/ViewModels/AuthorViewModel.cs | 12 +- .../Contracts/ViewModels/BookViewModel.cs | 16 +- .../DataModels/IBookModel.cs | 4 +- .../Implements/AuthorStorage.cs | 123 ++--- .../Implements/BookStorage.cs | 140 +++--- .../DatabaseImplement/LibraryDatabase.cs | 2 +- .../DatabaseImplement/Models/Author.cs | 44 +- .../DatabaseImplement/Models/Book.cs | 58 ++- .../DatabaseImplement/Models/BookForExcel.cs | 3 +- .../FormAuthor.Designer.cs | 86 ++-- COP_5/LibraryAccountingApp_lab3/FormAuthor.cs | 83 +++- .../FormBook.Designer.cs | 169 +++++++ COP_5/LibraryAccountingApp_lab3/FormBook.cs | 148 ++++++ COP_5/LibraryAccountingApp_lab3/FormBook.resx | 120 +++++ .../FormLibrary.Designer.cs | 293 ++++-------- .../LibraryAccountingApp_lab3/FormLibrary.cs | 427 ++++++++++-------- .../FormLibrary.resx | 3 + ....cs => 20241111111934_Initial.Designer.cs} | 22 +- ...ialCreate.cs => 20241111111934_Initial.cs} | 19 +- .../LibraryDatabaseModelSnapshot.cs | 18 +- COP_5/LibraryAccountingApp_lab3/Program.cs | 1 + 31 files changed, 1300 insertions(+), 763 deletions(-) create mode 100644 COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/AuthorSearchModel.cs create mode 100644 COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/BookSearchModel.cs create mode 100644 COP_5/LibraryAccountingApp_lab3/FormBook.Designer.cs create mode 100644 COP_5/LibraryAccountingApp_lab3/FormBook.cs create mode 100644 COP_5/LibraryAccountingApp_lab3/FormBook.resx rename COP_5/LibraryAccountingApp_lab3/Migrations/{20241028164711_InitialCreate.Designer.cs => 20241111111934_Initial.Designer.cs} (77%) rename COP_5/LibraryAccountingApp_lab3/Migrations/{20241028164711_InitialCreate.cs => 20241111111934_Initial.cs} (74%) diff --git a/COP_5/LibraryAccountingApp_lab3/BusinessLogic/AuthorLogic.cs b/COP_5/LibraryAccountingApp_lab3/BusinessLogic/AuthorLogic.cs index 11bb4cf..5cfd72f 100644 --- a/COP_5/LibraryAccountingApp_lab3/BusinessLogic/AuthorLogic.cs +++ b/COP_5/LibraryAccountingApp_lab3/BusinessLogic/AuthorLogic.cs @@ -1,5 +1,6 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.StorageContracts; using LibraryAccountingApp_lab3.Contracts.ViewModels; @@ -14,48 +15,73 @@ namespace LibraryAccountingApp_lab3.BusinessLogic _authorStorage = authorStorage; } - public List Read(AuthorBindingModel model) + public List? ReadList(AuthorSearchModel? model) + { + var list = model == null ? _authorStorage.GetFullList() : _authorStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public AuthorViewModel? ReadElement(AuthorSearchModel model) { if (model == null) { - return _authorStorage.GetFullList(); + throw new ArgumentNullException(nameof(model)); } - if (model.Id.HasValue) - { - return new List { _authorStorage.GetElement(model) }; - } - return _authorStorage.GetFilteredList(model); - } - - public void CreateOrUpdate(AuthorBindingModel model) - { - var element = _authorStorage.GetElement( - new AuthorBindingModel - { - Name = model.Name - }); - if (element != null && element.Id != model.Id) - { - throw new Exception("Такой автор уже существует"); - } - if (model.Id.HasValue) - { - _authorStorage.Update(model); - } - else - { - _authorStorage.Insert(model); - } - } - - public void Delete(AuthorBindingModel model) - { - var element = _authorStorage.GetElement(new AuthorBindingModel { Id = model.Id }); + var element = _authorStorage.GetElement(model); if (element == null) { - throw new Exception("Автор не найден"); + return null; + } + return element; + } + + public bool Create(AuthorBindingModel model) + { + CheckModel(model); + if (_authorStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Update(AuthorBindingModel model) + { + CheckModel(model); + if (_authorStorage.Update(model) == null) + { + return false; + } + return true; + } + public bool Delete(AuthorBindingModel model) + { + CheckModel(model, false); + if (_authorStorage.Delete(model) == null) + { + return false; + } + return true; + } + + private void CheckModel(AuthorBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentNullException("Нет автора", nameof(model.Name)); } - _authorStorage.Delete(model); } } } diff --git a/COP_5/LibraryAccountingApp_lab3/BusinessLogic/BookLogic.cs b/COP_5/LibraryAccountingApp_lab3/BusinessLogic/BookLogic.cs index 389370f..5f13c91 100644 --- a/COP_5/LibraryAccountingApp_lab3/BusinessLogic/BookLogic.cs +++ b/COP_5/LibraryAccountingApp_lab3/BusinessLogic/BookLogic.cs @@ -1,5 +1,6 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.StorageContracts; using LibraryAccountingApp_lab3.Contracts.ViewModels; @@ -13,48 +14,77 @@ namespace LibraryAccountingApp_lab3.BusinessLogic _bookStorage = bookStorage; } - public List Read(BookBindingModel model) + public List? ReadList(BookSearchModel? model) + { + var list = model == null ? _bookStorage.GetFullList() : _bookStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public BookViewModel? ReadElement(BookSearchModel model) { if (model == null) { - return _bookStorage.GetFullList(); + throw new ArgumentNullException(nameof(model)); } - if (model.Id.HasValue) - { - return new List { _bookStorage.GetElement(model) }; - } - return _bookStorage.GetFilteredList(model); - } - - public void CreateOrUpdate(BookBindingModel model) - { - var element = _bookStorage.GetElement( - new BookBindingModel - { - Title = model.Title - }); - if (element != null && element.Id != model.Id) - { - throw new Exception("Книга с таким названием уже существует"); - } - if (model.Id.HasValue) - { - _bookStorage.Update(model); - } - else - { - _bookStorage.Insert(model); - } - } - - public void Delete(BookBindingModel model) - { - var element = _bookStorage.GetElement(new BookBindingModel { Id = model.Id }); + var element = _bookStorage.GetElement(model); if (element == null) { - throw new Exception("Книга не найдена"); + return null; + } + return element; + } + + public bool Create(BookBindingModel model) + { + CheckModel(model); + if (_bookStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Update(BookBindingModel model) + { + CheckModel(model); + if (_bookStorage.Update(model) == null) + { + return false; + } + return true; + } + public bool Delete(BookBindingModel model) + { + CheckModel(model, false); + if (_bookStorage.Delete(model) == null) + { + return false; + } + return true; + } + + private void CheckModel(BookBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Title)) + { + throw new ArgumentNullException("Нет названия книги", nameof(model.Title)); + } + if (string.IsNullOrEmpty(model.Date)) + { + throw new ArgumentNullException("Нет даты", nameof(model.Date)); } - _bookStorage.Delete(model); } } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/AuthorBindingModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/AuthorBindingModel.cs index 4546b01..09aa04a 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/AuthorBindingModel.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/AuthorBindingModel.cs @@ -1,12 +1,10 @@ -using System.ComponentModel.DataAnnotations; +using LibraryAccountingApp_lab3.DataModels; namespace LibraryAccountingApp_lab3.Contracts.BindingModels { - public class AuthorBindingModel + public class AuthorBindingModel : IAuthorModel { - public int? Id { get; set; } - - [Required] - public string Name { get; set; } + public int Id { get; set; } + public string Name { get; set; } = String.Empty; } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/BookBindingModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/BookBindingModel.cs index b8269ab..5019e3a 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/BookBindingModel.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/BindingModels/BookBindingModel.cs @@ -1,16 +1,16 @@ -using System.ComponentModel.DataAnnotations; +using LibraryAccountingApp_lab3.DataModels; namespace LibraryAccountingApp_lab3.Contracts.BindingModels { - public class BookBindingModel + public class BookBindingModel : IBookModel { - public int? Id { get; set; } + public int Id { get; set; } public string Title { get; set; } - public string Author { get; set; } + public int AuthorId { get; set; } public string Date { get; set; } - public byte[] Image { get; set; } + public byte[] Image { get; set; } } } \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IAuthorLogic.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IAuthorLogic.cs index 80db1e4..7bfa9f8 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IAuthorLogic.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IAuthorLogic.cs @@ -1,12 +1,15 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.ViewModels; namespace LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts { public interface IAuthorLogic { - List Read(AuthorBindingModel model); - void CreateOrUpdate(AuthorBindingModel model); - void Delete(AuthorBindingModel model); + List? ReadList(AuthorSearchModel? model); + AuthorViewModel? ReadElement(AuthorSearchModel model); + bool Create(AuthorBindingModel model); + bool Update(AuthorBindingModel model); + bool Delete(AuthorBindingModel model); } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IBookLogic.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IBookLogic.cs index 8455f41..5c938e1 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IBookLogic.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/BusinessLogicsContracts/IBookLogic.cs @@ -1,12 +1,15 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.ViewModels; namespace LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts { public interface IBookLogic { - List? Read(BookBindingModel? model); - void CreateOrUpdate(BookBindingModel model); - void Delete(BookBindingModel model); + List? ReadList(BookSearchModel? model); + BookViewModel? ReadElement(BookSearchModel model); + bool Create(BookBindingModel model); + bool Update(BookBindingModel model); + bool Delete(BookBindingModel model); } } \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/AuthorSearchModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/AuthorSearchModel.cs new file mode 100644 index 0000000..4b13917 --- /dev/null +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/AuthorSearchModel.cs @@ -0,0 +1,7 @@ +namespace LibraryAccountingApp_lab3.Contracts.SearchModels +{ + public class AuthorSearchModel + { + public int? Id { get; set; } + } +} diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/BookSearchModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/BookSearchModel.cs new file mode 100644 index 0000000..4ba6001 --- /dev/null +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/SearchModels/BookSearchModel.cs @@ -0,0 +1,7 @@ +namespace LibraryAccountingApp_lab3.Contracts.SearchModels +{ + public class BookSearchModel + { + public int? Id { get; set; } + } +} diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IAuthorStorage.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IAuthorStorage.cs index d7ae88d..4200939 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IAuthorStorage.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IAuthorStorage.cs @@ -1,4 +1,5 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.ViewModels; namespace LibraryAccountingApp_lab3.Contracts.StorageContracts @@ -6,11 +7,10 @@ namespace LibraryAccountingApp_lab3.Contracts.StorageContracts public interface IAuthorStorage { List GetFullList(); - List GetFilteredList(AuthorBindingModel model); - AuthorViewModel GetElement(AuthorBindingModel model); - - void Insert(AuthorBindingModel model); - void Update(AuthorBindingModel model); - void Delete(AuthorBindingModel model); + List GetFilteredList(AuthorSearchModel model); + AuthorViewModel? GetElement(AuthorSearchModel model); + AuthorViewModel? Insert(AuthorBindingModel model); + AuthorViewModel? Update(AuthorBindingModel model); + AuthorViewModel? Delete(AuthorBindingModel model); } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IBookStorage.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IBookStorage.cs index 616a121..9e92695 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IBookStorage.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/StorageContracts/IBookStorage.cs @@ -1,4 +1,5 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.ViewModels; namespace LibraryAccountingApp_lab3.Contracts.StorageContracts @@ -6,11 +7,10 @@ namespace LibraryAccountingApp_lab3.Contracts.StorageContracts public interface IBookStorage { List GetFullList(); - List GetFilteredList(BookBindingModel model); - BookViewModel GetElement(BookBindingModel model); - - void Insert(BookBindingModel model); - void Update(BookBindingModel model); - void Delete(BookBindingModel model); + List GetFilteredList(BookSearchModel model); + BookViewModel? GetElement(BookSearchModel model); + BookViewModel? Insert(BookBindingModel model); + BookViewModel? Update(BookBindingModel model); + BookViewModel? Delete(BookBindingModel model); } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/AuthorViewModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/AuthorViewModel.cs index e783109..94557cf 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/AuthorViewModel.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/AuthorViewModel.cs @@ -1,14 +1,14 @@ -using System.ComponentModel.DataAnnotations; +using LibraryAccountingApp_lab3.DataModels; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; namespace LibraryAccountingApp_lab3.Contracts.ViewModels { - public class AuthorViewModel + public class AuthorViewModel : IAuthorModel { public int Id { get; set; } - [Required] - public string Name { get; set; } - - public List Books { get; set; } + [DisplayName("Имя")] + public string Name { get; set; } = string.Empty; } } diff --git a/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/BookViewModel.cs b/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/BookViewModel.cs index c65aec4..aa6ca3a 100644 --- a/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/BookViewModel.cs +++ b/COP_5/LibraryAccountingApp_lab3/Contracts/ViewModels/BookViewModel.cs @@ -1,19 +1,23 @@ -using System.ComponentModel; +using LibraryAccountingApp_lab3.DataModels; +using System.ComponentModel; namespace LibraryAccountingApp_lab3.Contracts.ViewModels { - public class BookViewModel + public class BookViewModel : IBookModel { - public int? Id { get; set; } + [DisplayName("Id")] + public int Id { get; set; } [DisplayName("Название")] - public string Title { get; set; } + public string Title { get; set; } = string.Empty; + public int AuthorId { get; set; } [DisplayName("Автор")] - public string Author { get; set; } + public string AuthorName { get; set; } = string.Empty; [DisplayName("Дата издания")] - public string Date { get; set; } + public string Date { get; set; } = string.Empty; + [DisplayName("Обложка")] public byte[] Image { get; set; } } } diff --git a/COP_5/LibraryAccountingApp_lab3/DataModels/IBookModel.cs b/COP_5/LibraryAccountingApp_lab3/DataModels/IBookModel.cs index da5f777..626282b 100644 --- a/COP_5/LibraryAccountingApp_lab3/DataModels/IBookModel.cs +++ b/COP_5/LibraryAccountingApp_lab3/DataModels/IBookModel.cs @@ -3,8 +3,8 @@ public interface IBookModel : IId { string Title { get; } - string Author { get; } + public int AuthorId { get; } string Date { get; } - byte[] Image { get; } + public byte[] Image { get; } } } diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/AuthorStorage.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/AuthorStorage.cs index e81a5c5..f1a5eed 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/AuthorStorage.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/AuthorStorage.cs @@ -1,4 +1,5 @@ using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.StorageContracts; using LibraryAccountingApp_lab3.Contracts.ViewModels; using LibraryAccountingApp_lab3.DatabaseImplement.Models; @@ -11,106 +12,72 @@ namespace LibraryAccountingApp_lab3.DatabaseImplement.Implements { using var context = new LibraryDatabase(); return context.Authors - .Select(CreateModel) + .Select(x => x.GetViewModel) .ToList(); } - public List GetFilteredList(AuthorBindingModel model) + public List GetFilteredList(AuthorSearchModel model) { - if (model == null) + if (!model.Id.HasValue) + { + return new(); + } + using var context = new LibraryDatabase(); + return context.Authors + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + + public AuthorViewModel? GetElement(AuthorSearchModel model) + { + if (!model.Id.HasValue) { return null; } using var context = new LibraryDatabase(); return context.Authors - .Where(rec => rec.Name.Contains(model.Name)) - .Select(CreateModel) - .ToList(); + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; } - public AuthorViewModel GetElement(AuthorBindingModel model) + public AuthorViewModel? Insert(AuthorBindingModel model) { - if (model == null) + var newAuthor = Author.Create(model); + if (newAuthor == null) { return null; } using var context = new LibraryDatabase(); - - var author = context.Authors - .ToList() - .FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name); - return author != null ? CreateModel(author) : null; - + context.Authors.Add(newAuthor); + context.SaveChanges(); + return newAuthor.GetViewModel; } - public void Insert(AuthorBindingModel model) + public AuthorViewModel? Update(AuthorBindingModel model) { - var context = new LibraryDatabase(); - var transaction = context.Database.BeginTransaction(); - try + using var context = new LibraryDatabase(); + var component = context.Authors.FirstOrDefault(x => x.Id == model.Id); + if (component == null) { - context.Authors.Add(CreateModel(model, new Author())); + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + + public AuthorViewModel? Delete(AuthorBindingModel model) + { + using var context = new LibraryDatabase(); + var element = context.Authors.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Authors.Remove(element); context.SaveChanges(); - transaction.Commit(); + return element.GetViewModel; } - catch - { - transaction.Rollback(); - throw; - } - } - - public void Update(AuthorBindingModel model) - { - var context = new LibraryDatabase(); - var transaction = context.Database.BeginTransaction(); - try - { - var author = context.Authors.FirstOrDefault(rec => rec.Id == model.Id); - if (author == null) - { - throw new Exception("Автор не найден"); - } - CreateModel(model, author); - context.SaveChanges(); - transaction.Commit(); - } - catch - { - transaction.Rollback(); - throw; - } - } - - - public void Delete(AuthorBindingModel model) - { - var context = new LibraryDatabase(); - var shape = context.Authors.FirstOrDefault(rec => rec.Id == model.Id); - if (shape != null) - { - context.Authors.Remove(shape); - context.SaveChanges(); - } - else - { - throw new Exception("Автор не найден"); - } - } - - private static Author CreateModel(AuthorBindingModel model, Author author) - { - author.Name = model.Name; - return author; - } - - private static AuthorViewModel CreateModel(Author author) - { - return new AuthorViewModel - { - Id = author.Id, - Name = author.Name - }; + return null; } } } diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/BookStorage.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/BookStorage.cs index b602063..f304eb0 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/BookStorage.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Implements/BookStorage.cs @@ -1,7 +1,10 @@ -using LibraryAccountingApp_lab3.Contracts.BindingModels; +using DocumentFormat.OpenXml.Bibliography; +using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.StorageContracts; using LibraryAccountingApp_lab3.Contracts.ViewModels; using LibraryAccountingApp_lab3.DatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; namespace LibraryAccountingApp_lab3.DatabaseImplement.Implements { @@ -12,109 +15,80 @@ namespace LibraryAccountingApp_lab3.DatabaseImplement.Implements using (var context = new LibraryDatabase()) { return context.Books - .ToList() - .Select(CreateModel) + .Include(x => x.Author) + .Select(x => x.GetViewModel) .ToList(); } } - public List GetFilteredList(BookBindingModel model) + public List GetFilteredList(BookSearchModel model) { + if (!model.Id.HasValue) + { + return new(); + } + var context = new LibraryDatabase(); return context.Books - .Where(book => book.Title.Contains(model.Title) && book.Author.Contains(model.Author)) - .ToList() - .Select(CreateModel) + .Include(x => x.Author) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) .ToList(); } - public BookViewModel GetElement(BookBindingModel model) + public BookViewModel? GetElement(BookSearchModel model) { - if (model == null) + if (!model.Id.HasValue) { return null; } + using var context = new LibraryDatabase(); - var book = context.Books - .ToList() - .FirstOrDefault(rec => rec.Title == model.Title || rec.Id == model.Id); - return book != null ? CreateModel(book) : null; + return context.Books + .Include(x => x.Author) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; } - public void Insert(BookBindingModel model) + public BookViewModel? Insert(BookBindingModel model) { - var context = new LibraryDatabase(); - var transaction = context.Database.BeginTransaction(); - try + using var context = new LibraryDatabase(); + var newBook = Book.Create(context, model); + if (newBook == null) { - context.Books.Add(CreateModel(model, new Book())); + return null; + } + context.Books.Add(newBook); + context.SaveChanges(); + return newBook.GetViewModel; + } + + public BookViewModel? Update(BookBindingModel model) + { + using var context = new LibraryDatabase(); + var book = context.Books.FirstOrDefault(x => x.Id == model.Id); + if (book == null) + { + return null; + } + book.Update(model, context); + context.SaveChanges(); + return book.GetViewModel; + } + + public BookViewModel? Delete(BookBindingModel model) + { + using var context = new LibraryDatabase(); + var element = context.Books + .Include (x => x.Author) + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Books.Remove(element); context.SaveChanges(); - transaction.Commit(); + return element.GetViewModel; } - catch - { - transaction.Rollback(); - throw; - } - } - - public void Update(BookBindingModel model) - { - var context = new LibraryDatabase(); - var transaction = context.Database.BeginTransaction(); - try - { - var book = context.Books.FirstOrDefault(rec => rec.Id == model.Id); - if (book == null) - { - throw new Exception("Книга не найдена"); - } - CreateModel(model, book); - context.SaveChanges(); - transaction.Commit(); - } - catch - { - transaction.Rollback(); - throw; - } - } - - - public void Delete(BookBindingModel model) - { - var context = new LibraryDatabase(); - var book = context.Books.FirstOrDefault(rec => rec.Id == model.Id); - if (book != null) - { - context.Books.Remove(book); - context.SaveChanges(); - } - else - { - throw new Exception("Книга не найдена"); - } - } - - private static Book CreateModel(BookBindingModel model, Book book) - { - book.Title = model.Title; - book.Author = model.Author; - book.Date = model.Date; - book.Image = model.Image; - return book; - } - - private BookViewModel CreateModel(Book book) - { - return new BookViewModel - { - Id = book.Id, - Title = book.Title, - Author = book.Author, - Date = book.Date, - Image = book.Image - }; + return null; } } } diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/LibraryDatabase.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/LibraryDatabase.cs index fbe94c9..3778f94 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/LibraryDatabase.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/LibraryDatabase.cs @@ -9,7 +9,7 @@ namespace LibraryAccountingApp_lab3.DatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=PC-Anna\SQLEXPRESS;Initial Catalog=LibraryAppCOP4;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=PC-Anna\SQLEXPRESS;Initial Catalog=LibraryAppCOP5;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); //optionsBuilder.UseNpgsql("Host=localhost;Database=LibraryAppCOP;Username=postgres;Password=postgres"); } base.OnConfiguring(optionsBuilder); diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Author.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Author.cs index d31cba4..dd0572c 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Author.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Author.cs @@ -1,12 +1,48 @@ -using System.ComponentModel.DataAnnotations; +using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.ViewModels; +using LibraryAccountingApp_lab3.DataModels; +using System.ComponentModel.DataAnnotations; namespace LibraryAccountingApp_lab3.DatabaseImplement.Models { - public class Author + public class Author : IAuthorModel { - public int Id { get; set; } + public int Id { get; private set; } [Required] - public string Name { get; set; } + public string Name { get; set; } = string.Empty; + public static Author? Create(AuthorBindingModel? model) + { + if (model == null) + { + return null; + } + return new Author() + { + Id = model.Id, + Name = model.Name, + }; + } + public static Author? Create(AuthorViewModel? model) + { + return new Author() + { + Id = model.Id, + Name = model.Name, + }; + } + public void Update(AuthorBindingModel? model) + { + if (model == null) + { + return; + } + Name = model.Name; + } + public AuthorViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + }; } } diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Book.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Book.cs index 2b22107..995f417 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Book.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/Book.cs @@ -1,21 +1,63 @@ -using System.ComponentModel.DataAnnotations; +using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.ViewModels; +using LibraryAccountingApp_lab3.DataModels; +using System.ComponentModel.DataAnnotations; namespace LibraryAccountingApp_lab3.DatabaseImplement.Models { - public class Book + public class Book : IBookModel { - public int Id { get; set; } + public int Id { get; private set; } [Required] - public string Title { get; set; } + public string Title { get; set; } = string.Empty; + public int AuthorId { get; set; } + public virtual Author Author { get; set; } = new(); [Required] - public string Author { get; set; } - - [Required] - public string Date { get; set; } + public string Date { get; set; } = string.Empty; [Required] public byte[] Image { get; set; } + + public static Book? Create(LibraryDatabase context, BookBindingModel? model) + { + if (model == null) + { + return null; + } + return new Book() + { + Id = model.Id, + Title = model.Title, + Date = model.Date, + AuthorId = model.AuthorId, + Author = context.Authors.First(x => x.Id == model.AuthorId), + Image = model.Image, + }; + } + + public void Update(BookBindingModel? model, LibraryDatabase context) + { + if (model == null) + { + return; + } + Title = model.Title; + AuthorId = model.AuthorId; + Date = model.Date; + Author = context.Authors.First(x => x.Id == model.AuthorId); + Image = model.Image; + } + + public BookViewModel GetViewModel => new() + { + Id = Id, + Title = Title, + Date = Date, + AuthorId = AuthorId, + AuthorName = Author.Name, + Image = Image, + }; } } diff --git a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/BookForExcel.cs b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/BookForExcel.cs index 6e4deb1..56b1804 100644 --- a/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/BookForExcel.cs +++ b/COP_5/LibraryAccountingApp_lab3/DatabaseImplement/Models/BookForExcel.cs @@ -9,8 +9,7 @@ namespace LibraryAccountingApp_lab3.DatabaseImplement.Models [Required] public string Title { get; set; } - [Required] - public string Author { get; set; } + public string AuthorName { get; set; } [Required] public string Date { get; set; } diff --git a/COP_5/LibraryAccountingApp_lab3/FormAuthor.Designer.cs b/COP_5/LibraryAccountingApp_lab3/FormAuthor.Designer.cs index 0fb9250..8dd93ff 100644 --- a/COP_5/LibraryAccountingApp_lab3/FormAuthor.Designer.cs +++ b/COP_5/LibraryAccountingApp_lab3/FormAuthor.Designer.cs @@ -28,70 +28,62 @@ /// private void InitializeComponent() { - textBoxAuthor = new TextBox(); - label1 = new Label(); - buttonAdd = new Button(); - buttonCancel = new Button(); + dataGridView = new DataGridView(); + NameCol = new DataGridViewTextBoxColumn(); + Id = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // - // textBoxAuthor + // dataGridView // - textBoxAuthor.Location = new Point(12, 27); - textBoxAuthor.Name = "textBoxAuthor"; - textBoxAuthor.Size = new Size(277, 23); - textBoxAuthor.TabIndex = 0; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { NameCol, Id }); + dataGridView.Dock = DockStyle.Fill; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(625, 357); + dataGridView.TabIndex = 0; + dataGridView.CellValueChanged += dataGridView_CellValueChanged; + dataGridView.UserDeletingRow += dataGridView_UserDeletingRow; + dataGridView.KeyUp += dataGridView_KeyUp; // - // label1 + // NameCol // - label1.AutoSize = true; - label1.Location = new Point(12, 9); - label1.Name = "label1"; - label1.Size = new Size(34, 15); - label1.TabIndex = 1; - label1.Text = "Имя:"; + NameCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + NameCol.HeaderText = "Имя"; + NameCol.MinimumWidth = 6; + NameCol.Name = "NameCol"; // - // buttonAdd + // Id // - buttonAdd.BackColor = Color.LightGreen; - buttonAdd.Location = new Point(50, 76); - buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(88, 23); - buttonAdd.TabIndex = 2; - buttonAdd.Text = "Добавить"; - buttonAdd.UseVisualStyleBackColor = false; - buttonAdd.Click += buttonAdd_Click; - // - // buttonCancel - // - buttonCancel.BackColor = Color.Salmon; - buttonCancel.Location = new Point(165, 76); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new Size(88, 23); - buttonCancel.TabIndex = 3; - buttonCancel.Text = "Отмена"; - buttonCancel.UseVisualStyleBackColor = false; - buttonCancel.Click += buttonCancel_Click; + Id.HeaderText = "Id"; + Id.MinimumWidth = 6; + Id.Name = "Id"; + Id.Visible = false; + Id.Width = 125; // // FormAuthor // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(301, 114); - Controls.Add(buttonCancel); - Controls.Add(buttonAdd); - Controls.Add(label1); - Controls.Add(textBoxAuthor); + BackColor = Color.White; + ClientSize = new Size(536, 228); + Controls.Add(dataGridView); + Margin = new Padding(3, 2, 3, 2); Name = "FormAuthor"; - Text = "Добавление автора"; + Text = "Авторы"; + Load += FormAuthor_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); - PerformLayout(); } #endregion - private TextBox textBoxAuthor; - private Label label1; - private Button buttonAdd; - private Button buttonCancel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn NameCol; + private DataGridViewTextBoxColumn Id; } } \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/FormAuthor.cs b/COP_5/LibraryAccountingApp_lab3/FormAuthor.cs index e338689..f3b6f7e 100644 --- a/COP_5/LibraryAccountingApp_lab3/FormAuthor.cs +++ b/COP_5/LibraryAccountingApp_lab3/FormAuthor.cs @@ -8,8 +8,7 @@ namespace LibraryAccountingApp_lab3 { private readonly IAuthorLogic _logic; private readonly IAuthorStorage _storage; - private int? _id; - public int Id { set { _id = value; } } + private bool loading = false; public FormAuthor(IAuthorLogic logic, IAuthorStorage storage) { InitializeComponent(); @@ -17,32 +16,82 @@ namespace LibraryAccountingApp_lab3 _storage = storage; } - private void buttonAdd_Click(object sender, EventArgs e) + private void FormAuthor_Load(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxAuthor.Text)) - MessageBox.Show("Введите имя автора!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + LoadData(); + } + private void LoadData() + { + loading = true; try { - _logic.CreateOrUpdate(new AuthorBindingModel + var list = _logic.ReadList(null); + if (list != null) { - Id = _id, - Name = textBoxAuthor.Text, - }); - MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - Close(); + foreach (var interest in list) + { + int rowIndex = dataGridView.Rows.Add(); + dataGridView.Rows[rowIndex].Cells[0].Value = interest.Name; + dataGridView.Rows[rowIndex].Cells[1].Value = interest.Id; + } + } } - catch + catch (Exception ex) { - MessageBox.Show("Ошибка при добавлении!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + finally + { + loading = false; } } - private void buttonCancel_Click(object sender, EventArgs e) + private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) { - DialogResult = DialogResult.Cancel; - Close(); + if (loading || e.RowIndex < 0 || e.ColumnIndex != 0) return; + if (dataGridView.Rows[e.RowIndex].Cells[1].Value != null && !string.IsNullOrEmpty(dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString())) + { + var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + if (name is null) return; + _logic.Update(new AuthorBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), Name = name.ToString() }); + } + else + { + var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + if (name is null) return; + _logic.Create(new AuthorBindingModel { Id = 0, Name = name.ToString() }); + int newCategoryId = _logic.ReadList(null).ToList().Last().Id; + dataGridView.Rows[e.RowIndex].Cells[1].Value = newCategoryId; + } + } + + private void dataGridView_KeyUp(object sender, KeyEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Insert: + dataGridView.Rows.Add(); + break; + } + } + + private void deleteRows(DataGridViewSelectedRowCollection rows) + { + for (int i = 0; i < rows.Count; i++) + { + DataGridViewRow row = rows[i]; + if (!_logic.Delete(new AuthorBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) })) continue; + dataGridView.Rows.Remove(row); + } + } + + private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) + { + e.Cancel = true; + if (dataGridView.SelectedRows == null) return; + if (MessageBox.Show("Удалить записи?", "Подтвердите действие", MessageBoxButtons.YesNo) == DialogResult.No) return; + deleteRows(dataGridView.SelectedRows); } } } diff --git a/COP_5/LibraryAccountingApp_lab3/FormBook.Designer.cs b/COP_5/LibraryAccountingApp_lab3/FormBook.Designer.cs new file mode 100644 index 0000000..b21cdd9 --- /dev/null +++ b/COP_5/LibraryAccountingApp_lab3/FormBook.Designer.cs @@ -0,0 +1,169 @@ +namespace LibraryAccountingApp_lab3 +{ + partial class FormBook + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + textBoxTitle = new TextBox(); + buttonBookAdd = new Button(); + buttonClearImage = new Button(); + textBoxImage = new TextBox(); + label2 = new Label(); + controlSelectedComboBoxSingleAuthor = new ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle(); + dateTextBoxDate = new FedComponentLib.DateTextBox(); + label1 = new Label(); + buttonChooseImage = new Button(); + SuspendLayout(); + // + // textBoxTitle + // + textBoxTitle.Anchor = AnchorStyles.Left | AnchorStyles.Right; + textBoxTitle.Location = new Point(18, 38); + textBoxTitle.Name = "textBoxTitle"; + textBoxTitle.Size = new Size(243, 23); + textBoxTitle.TabIndex = 27; + // + // buttonBookAdd + // + buttonBookAdd.Anchor = AnchorStyles.Left | AnchorStyles.Right; + buttonBookAdd.BackColor = Color.YellowGreen; + buttonBookAdd.Location = new Point(31, 389); + buttonBookAdd.Name = "buttonBookAdd"; + buttonBookAdd.Size = new Size(231, 36); + buttonBookAdd.TabIndex = 28; + buttonBookAdd.Text = "Сохранить книгу"; + buttonBookAdd.UseVisualStyleBackColor = false; + buttonBookAdd.Click += buttonBookAdd_Click; + // + // buttonClearImage + // + buttonClearImage.Anchor = AnchorStyles.Left | AnchorStyles.Right; + buttonClearImage.BackColor = Color.Silver; + buttonClearImage.Font = new Font("Segoe UI", 7F, FontStyle.Regular, GraphicsUnit.Point); + buttonClearImage.Location = new Point(151, 323); + buttonClearImage.Name = "buttonClearImage"; + buttonClearImage.Size = new Size(127, 27); + buttonClearImage.TabIndex = 29; + buttonClearImage.Text = "Очистить"; + buttonClearImage.UseVisualStyleBackColor = false; + buttonClearImage.Click += buttonClearImage_Click; + // + // textBoxImage + // + textBoxImage.Anchor = AnchorStyles.Left | AnchorStyles.Right; + textBoxImage.Location = new Point(18, 294); + textBoxImage.Name = "textBoxImage"; + textBoxImage.ReadOnly = true; + textBoxImage.Size = new Size(243, 23); + textBoxImage.TabIndex = 34; + // + // label2 + // + label2.Anchor = AnchorStyles.Left | AnchorStyles.Right; + label2.AutoSize = true; + label2.Location = new Point(18, 162); + label2.Name = "label2"; + label2.Size = new Size(43, 15); + label2.TabIndex = 33; + label2.Text = "Автор:"; + // + // controlSelectedComboBoxSingleAuthor + // + controlSelectedComboBoxSingleAuthor.Anchor = AnchorStyles.Left | AnchorStyles.Right; + controlSelectedComboBoxSingleAuthor.Location = new Point(18, 180); + controlSelectedComboBoxSingleAuthor.Margin = new Padding(5, 3, 5, 3); + controlSelectedComboBoxSingleAuthor.Name = "controlSelectedComboBoxSingleAuthor"; + controlSelectedComboBoxSingleAuthor.SelectedElement = ""; + controlSelectedComboBoxSingleAuthor.Size = new Size(243, 28); + controlSelectedComboBoxSingleAuthor.TabIndex = 30; + // + // dateTextBoxDate + // + dateTextBoxDate.Anchor = AnchorStyles.Left | AnchorStyles.Right; + dateTextBoxDate.DatePattern = null; + dateTextBoxDate.Location = new Point(18, 78); + dateTextBoxDate.Margin = new Padding(3, 4, 3, 4); + dateTextBoxDate.Name = "dateTextBoxDate"; + dateTextBoxDate.Size = new Size(243, 57); + dateTextBoxDate.TabIndex = 32; + // + // label1 + // + label1.Anchor = AnchorStyles.Left | AnchorStyles.Right; + label1.AutoSize = true; + label1.Location = new Point(18, 20); + label1.Name = "label1"; + label1.Size = new Size(62, 15); + label1.TabIndex = 31; + label1.Text = "Название:"; + // + // buttonChooseImage + // + buttonChooseImage.Anchor = AnchorStyles.Left | AnchorStyles.Right; + buttonChooseImage.Location = new Point(64, 264); + buttonChooseImage.Margin = new Padding(3, 2, 3, 2); + buttonChooseImage.Name = "buttonChooseImage"; + buttonChooseImage.Size = new Size(176, 24); + buttonChooseImage.TabIndex = 26; + buttonChooseImage.Text = "Выбрать обложку"; + buttonChooseImage.UseVisualStyleBackColor = true; + buttonChooseImage.Click += buttonChooseImage_Click; + // + // FormBook + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(290, 467); + Controls.Add(textBoxTitle); + Controls.Add(buttonBookAdd); + Controls.Add(buttonClearImage); + Controls.Add(textBoxImage); + Controls.Add(label2); + Controls.Add(controlSelectedComboBoxSingleAuthor); + Controls.Add(dateTextBoxDate); + Controls.Add(label1); + Controls.Add(buttonChooseImage); + Margin = new Padding(3, 2, 3, 2); + Name = "FormBook"; + Text = "Книги"; + Load += FormBook_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + private TextBox textBoxTitle; + private Button buttonBookAdd; + private Button buttonClearImage; + private TextBox textBoxImage; + private Label label2; + private ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle controlSelectedComboBoxSingleAuthor; + private FedComponentLib.DateTextBox dateTextBoxDate; + private Label label1; + private Button buttonChooseImage; + } +} \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/FormBook.cs b/COP_5/LibraryAccountingApp_lab3/FormBook.cs new file mode 100644 index 0000000..2b88776 --- /dev/null +++ b/COP_5/LibraryAccountingApp_lab3/FormBook.cs @@ -0,0 +1,148 @@ +using LibraryAccountingApp_lab3.Contracts.BindingModels; +using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts; +using LibraryAccountingApp_lab3.Contracts.SearchModels; +using LibraryAccountingApp_lab3.Contracts.StorageContracts; +using LibraryAccountingApp_lab3.Contracts.ViewModels; + +namespace LibraryAccountingApp_lab3 +{ + public partial class FormBook : Form + { + private byte[]? selectedImage = new byte[16]; + private readonly IBookLogic _bookLogic; + private readonly IAuthorLogic _authorLogic; + public readonly IBookStorage _bookStorage; + private List _authors; + private int? _id; + public int Id { set { _id = value; } } + public FormBook(IBookLogic bookLogic, IAuthorLogic authorLogic) + { + InitializeComponent(); + _bookLogic = bookLogic; + _authorLogic = authorLogic; + _authors = new List(); + FillControlSelectedComboBoxSingle(); + dateTextBoxDate.DatePattern = @"^(0[1-9]|[12][0-9]|3[01])\s+(январь|февраль|март|апрель|май|июнь|июль|август|сентябрь|октябрь|ноябрь|декабрь)\s+\d{4}$"; + } + private void FormBook_Load(object sender, EventArgs e) + { + _authors = _authorLogic.ReadList(null); + if (_id.HasValue) + { + try + { + var view = _bookLogic.ReadElement(new BookSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxTitle.Text = view.Title; + dateTextBoxDate.TextBoxValue = view.Date; + textBoxImage.Text = "Обложка выбрана"; + + controlSelectedComboBoxSingleAuthor.SelectedElement = view.AuthorName; + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void FillControlSelectedComboBoxSingle() + { + controlSelectedComboBoxSingleAuthor.Clear(); + try + { + var list = _authorLogic.ReadList(null); + + if (list != null) + { + foreach (var author in list) + { + controlSelectedComboBoxSingleAuthor.AddElement(author.Name); + } + } + } + catch (Exception ex) + { + MessageBox.Show($"Ошибка загрузки данных: {ex.Message}"); + } + } + + + private void buttonBookAdd_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxTitle.Text)) + MessageBox.Show("Введите название!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + try + { + if (string.IsNullOrEmpty(dateTextBoxDate.TextBoxValue)) + MessageBox.Show("Введите дату издания!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + if (string.IsNullOrEmpty(controlSelectedComboBoxSingleAuthor.SelectedElement)) + MessageBox.Show("Выберите автора!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (string.IsNullOrEmpty(textBoxImage.Text)) + MessageBox.Show("Выберите обложку!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + + try + { + var model = new BookBindingModel + { + Id = _id ?? 0, + Title = textBoxTitle.Text, + Date = dateTextBoxDate.TextBoxValue, + AuthorId = _authors.First(x => x.Name == controlSelectedComboBoxSingleAuthor.SelectedElement).Id, + Image = selectedImage, + + }; + var operationResult = _id.HasValue ? _bookLogic.Update(model) : _bookLogic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch + { + MessageBox.Show("Ошибка при добавлении!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonChooseImage_Click(object sender, EventArgs e) + { + using OpenFileDialog openFileDialog = new OpenFileDialog + { + Multiselect = true, + Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp" + }; + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + ClearImage(); + + foreach (string filePath in openFileDialog.FileNames) + { + selectedImage = File.ReadAllBytes(filePath); + textBoxImage.Text = Path.GetFileName(filePath); + } + } + } + + private void ClearImage() + { + selectedImage = null; + textBoxImage.Clear(); + } + + private void buttonClearImage_Click(object sender, EventArgs e) + { + ClearImage(); + } + + } +} diff --git a/COP_5/LibraryAccountingApp_lab3/FormBook.resx b/COP_5/LibraryAccountingApp_lab3/FormBook.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/COP_5/LibraryAccountingApp_lab3/FormBook.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/FormLibrary.Designer.cs b/COP_5/LibraryAccountingApp_lab3/FormLibrary.Designer.cs index 93948cf..9bf30ac 100644 --- a/COP_5/LibraryAccountingApp_lab3/FormLibrary.Designer.cs +++ b/COP_5/LibraryAccountingApp_lab3/FormLibrary.Designer.cs @@ -29,258 +29,139 @@ private void InitializeComponent() { components = new System.ComponentModel.Container(); - buttonChooseImage = new Button(); - groupBox1 = new GroupBox(); - buttonAddAuthor = new Button(); - textBoxTitle = new TextBox(); - buttonBookAdd = new Button(); - buttonClearImage = new Button(); - textBoxImage = new TextBox(); - label2 = new Label(); - controlSelectedComboBoxSingleAuthor = new ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle(); - dateTextBoxDate = new FedComponentLib.DateTextBox(); - label1 = new Label(); - groupBox2 = new GroupBox(); - controlDataTableCellBooks = new ControlsLibraryNet60.Data.ControlDataTableCell(); pdfForImages = new COP_5.PdfForImages(components); componentDocumentWithChartBarWord = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components); tableComponent = new FedComponentLib.NonVisualComponents.TableComponent(components); - buttonPdfCreate = new Button(); - groupBox3 = new GroupBox(); - buttonChartBarCreate = new Button(); - buttonExcelCreate = new Button(); - groupBox1.SuspendLayout(); - groupBox2.SuspendLayout(); - groupBox3.SuspendLayout(); + менюToolStripMenuItem = new ToolStripMenuItem(); + авторыToolStripMenuItem = new ToolStripMenuItem(); + книгиToolStripMenuItem = new ToolStripMenuItem(); + отчетыToolStripMenuItem = new ToolStripMenuItem(); + pDFСОбложкамиToolStripMenuItem = new ToolStripMenuItem(); + excelПоВсемКнигамToolStripMenuItem = new ToolStripMenuItem(); + гистограммаВWordToolStripMenuItem = new ToolStripMenuItem(); + menuStrip1 = new MenuStrip(); + удалитьToolStripMenuItem = new ToolStripMenuItem(); + controlDataTableCellBooks = new ControlsLibraryNet60.Data.ControlDataTableCell(); + редактироватьToolStripMenuItem = new ToolStripMenuItem(); + menuStrip1.SuspendLayout(); SuspendLayout(); // - // buttonChooseImage + // менюToolStripMenuItem // - buttonChooseImage.Anchor = AnchorStyles.None; - buttonChooseImage.Location = new Point(52, 274); - buttonChooseImage.Margin = new Padding(3, 2, 3, 2); - buttonChooseImage.Name = "buttonChooseImage"; - buttonChooseImage.Size = new Size(176, 24); - buttonChooseImage.TabIndex = 17; - buttonChooseImage.Text = "Выбрать обложку"; - buttonChooseImage.UseVisualStyleBackColor = true; - buttonChooseImage.Click += buttonChooseImage_Click; + менюToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { авторыToolStripMenuItem, книгиToolStripMenuItem }); + менюToolStripMenuItem.Name = "менюToolStripMenuItem"; + менюToolStripMenuItem.Size = new Size(86, 20); + менюToolStripMenuItem.Text = "Добавление"; // - // groupBox1 + // авторыToolStripMenuItem // - groupBox1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - groupBox1.Controls.Add(buttonAddAuthor); - groupBox1.Controls.Add(textBoxTitle); - groupBox1.Controls.Add(buttonBookAdd); - groupBox1.Controls.Add(buttonClearImage); - groupBox1.Controls.Add(textBoxImage); - groupBox1.Controls.Add(label2); - groupBox1.Controls.Add(controlSelectedComboBoxSingleAuthor); - groupBox1.Controls.Add(dateTextBoxDate); - groupBox1.Controls.Add(label1); - groupBox1.Controls.Add(buttonChooseImage); - groupBox1.Location = new Point(12, 12); - groupBox1.Name = "groupBox1"; - groupBox1.Size = new Size(272, 465); - groupBox1.TabIndex = 18; - groupBox1.TabStop = false; - groupBox1.Text = "Загрузка книги"; + авторыToolStripMenuItem.Name = "авторыToolStripMenuItem"; + авторыToolStripMenuItem.Size = new Size(116, 22); + авторыToolStripMenuItem.Text = "Авторы"; + авторыToolStripMenuItem.Click += авторыToolStripMenuItem_Click; // - // buttonAddAuthor + // книгиToolStripMenuItem // - buttonAddAuthor.Anchor = AnchorStyles.None; - buttonAddAuthor.BackColor = Color.PaleTurquoise; - buttonAddAuthor.Location = new Point(6, 216); - buttonAddAuthor.Margin = new Padding(3, 2, 3, 2); - buttonAddAuthor.Name = "buttonAddAuthor"; - buttonAddAuthor.Size = new Size(111, 24); - buttonAddAuthor.TabIndex = 25; - buttonAddAuthor.Text = "Добавить автора"; - buttonAddAuthor.UseVisualStyleBackColor = false; - buttonAddAuthor.Click += buttonAddAuthor_Click; + книгиToolStripMenuItem.Name = "книгиToolStripMenuItem"; + книгиToolStripMenuItem.Size = new Size(116, 22); + книгиToolStripMenuItem.Text = "Книги"; + книгиToolStripMenuItem.Click += книгиToolStripMenuItem_Click; // - // textBoxTitle + // отчетыToolStripMenuItem // - textBoxTitle.Anchor = AnchorStyles.None; - textBoxTitle.Location = new Point(6, 48); - textBoxTitle.Name = "textBoxTitle"; - textBoxTitle.Size = new Size(243, 23); - textBoxTitle.TabIndex = 19; + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pDFСОбложкамиToolStripMenuItem, excelПоВсемКнигамToolStripMenuItem, гистограммаВWordToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 20); + отчетыToolStripMenuItem.Text = "Отчеты"; // - // buttonBookAdd + // pDFСОбложкамиToolStripMenuItem // - buttonBookAdd.Anchor = AnchorStyles.None; - buttonBookAdd.BackColor = Color.YellowGreen; - buttonBookAdd.Location = new Point(18, 399); - buttonBookAdd.Name = "buttonBookAdd"; - buttonBookAdd.Size = new Size(231, 36); - buttonBookAdd.TabIndex = 19; - buttonBookAdd.Text = "Добавить книгу"; - buttonBookAdd.UseVisualStyleBackColor = false; - buttonBookAdd.Click += buttonBookAdd_Click; + pDFСОбложкамиToolStripMenuItem.Name = "pDFСОбложкамиToolStripMenuItem"; + pDFСОбложкамиToolStripMenuItem.Size = new Size(194, 22); + pDFСОбложкамиToolStripMenuItem.Text = "PDF с обложками"; + pDFСОбложкамиToolStripMenuItem.Click += pDFСОбложкамиToolStripMenuItem_Click; // - // buttonClearImage + // excelПоВсемКнигамToolStripMenuItem // - buttonClearImage.Anchor = AnchorStyles.None; - buttonClearImage.BackColor = Color.Silver; - buttonClearImage.Font = new Font("Segoe UI", 7F, FontStyle.Regular, GraphicsUnit.Point); - buttonClearImage.Location = new Point(139, 333); - buttonClearImage.Name = "buttonClearImage"; - buttonClearImage.Size = new Size(127, 27); - buttonClearImage.TabIndex = 19; - buttonClearImage.Text = "Очистить"; - buttonClearImage.UseVisualStyleBackColor = false; - buttonClearImage.Click += buttonClearImage_Click; + excelПоВсемКнигамToolStripMenuItem.Name = "excelПоВсемКнигамToolStripMenuItem"; + excelПоВсемКнигамToolStripMenuItem.Size = new Size(194, 22); + excelПоВсемКнигамToolStripMenuItem.Text = "Excel по всем книгам "; + excelПоВсемКнигамToolStripMenuItem.Click += excelПоВсемКнигамToolStripMenuItem_Click; // - // textBoxImage + // гистограммаВWordToolStripMenuItem // - textBoxImage.Anchor = AnchorStyles.None; - textBoxImage.Location = new Point(6, 304); - textBoxImage.Name = "textBoxImage"; - textBoxImage.ReadOnly = true; - textBoxImage.Size = new Size(243, 23); - textBoxImage.TabIndex = 24; + гистограммаВWordToolStripMenuItem.Name = "гистограммаВWordToolStripMenuItem"; + гистограммаВWordToolStripMenuItem.Size = new Size(194, 22); + гистограммаВWordToolStripMenuItem.Text = "Гистограмма в Word"; + гистограммаВWordToolStripMenuItem.Click += гистограммаВWordToolStripMenuItem_Click; // - // label2 + // menuStrip1 // - label2.Anchor = AnchorStyles.None; - label2.AutoSize = true; - label2.Location = new Point(6, 172); - label2.Name = "label2"; - label2.Size = new Size(43, 15); - label2.TabIndex = 22; - label2.Text = "Автор:"; + menuStrip1.ImageScalingSize = new Size(20, 20); + menuStrip1.Items.AddRange(new ToolStripItem[] { менюToolStripMenuItem, отчетыToolStripMenuItem, удалитьToolStripMenuItem, редактироватьToolStripMenuItem }); + menuStrip1.Location = new Point(0, 0); + menuStrip1.Name = "menuStrip1"; + menuStrip1.Padding = new Padding(5, 2, 0, 2); + menuStrip1.Size = new Size(609, 24); + menuStrip1.TabIndex = 26; + menuStrip1.Text = "menuStrip1"; // - // controlSelectedComboBoxSingleAuthor + // удалитьToolStripMenuItem // - controlSelectedComboBoxSingleAuthor.Anchor = AnchorStyles.None; - controlSelectedComboBoxSingleAuthor.Location = new Point(6, 190); - controlSelectedComboBoxSingleAuthor.Margin = new Padding(5, 3, 5, 3); - controlSelectedComboBoxSingleAuthor.Name = "controlSelectedComboBoxSingleAuthor"; - controlSelectedComboBoxSingleAuthor.SelectedElement = ""; - controlSelectedComboBoxSingleAuthor.Size = new Size(243, 28); - controlSelectedComboBoxSingleAuthor.TabIndex = 19; - // - // dateTextBoxDate - // - dateTextBoxDate.Anchor = AnchorStyles.None; - dateTextBoxDate.DatePattern = null; - dateTextBoxDate.Location = new Point(6, 88); - dateTextBoxDate.Name = "dateTextBoxDate"; - dateTextBoxDate.Size = new Size(243, 57); - dateTextBoxDate.TabIndex = 21; - // - // label1 - // - label1.Anchor = AnchorStyles.None; - label1.AutoSize = true; - label1.Location = new Point(6, 29); - label1.Name = "label1"; - label1.Size = new Size(62, 15); - label1.TabIndex = 19; - label1.Text = "Название:"; - // - // groupBox2 - // - groupBox2.Controls.Add(controlDataTableCellBooks); - groupBox2.Location = new Point(288, 12); - groupBox2.Name = "groupBox2"; - groupBox2.Size = new Size(527, 330); - groupBox2.TabIndex = 19; - groupBox2.TabStop = false; - groupBox2.Text = "Вывод книг"; + удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem"; + удалитьToolStripMenuItem.Size = new Size(63, 20); + удалитьToolStripMenuItem.Text = "Удалить"; + удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click; // // controlDataTableCellBooks // + controlDataTableCellBooks.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; controlDataTableCellBooks.AutoSize = true; - controlDataTableCellBooks.Location = new Point(3, 19); + controlDataTableCellBooks.Location = new Point(12, 34); controlDataTableCellBooks.Margin = new Padding(4, 3, 4, 3); controlDataTableCellBooks.Name = "controlDataTableCellBooks"; controlDataTableCellBooks.SelectedRowIndex = -1; - controlDataTableCellBooks.Size = new Size(517, 311); + controlDataTableCellBooks.Size = new Size(578, 328); controlDataTableCellBooks.TabIndex = 0; // - // buttonPdfCreate + // редактироватьToolStripMenuItem // - buttonPdfCreate.Location = new Point(31, 35); - buttonPdfCreate.Name = "buttonPdfCreate"; - buttonPdfCreate.Size = new Size(140, 48); - buttonPdfCreate.TabIndex = 20; - buttonPdfCreate.Text = "Создать PDF с обложками"; - buttonPdfCreate.UseVisualStyleBackColor = true; - buttonPdfCreate.Click += buttonPdfCreate_Click; - // - // groupBox3 - // - groupBox3.Controls.Add(buttonChartBarCreate); - groupBox3.Controls.Add(buttonExcelCreate); - groupBox3.Controls.Add(buttonPdfCreate); - groupBox3.Location = new Point(291, 370); - groupBox3.Name = "groupBox3"; - groupBox3.Size = new Size(524, 107); - groupBox3.TabIndex = 21; - groupBox3.TabStop = false; - groupBox3.Text = "Формирование отчётов"; - // - // buttonChartBarCreate - // - buttonChartBarCreate.Location = new Point(356, 35); - buttonChartBarCreate.Name = "buttonChartBarCreate"; - buttonChartBarCreate.Size = new Size(140, 48); - buttonChartBarCreate.TabIndex = 22; - buttonChartBarCreate.Text = "Создать гистограмму в Word"; - buttonChartBarCreate.UseVisualStyleBackColor = true; - buttonChartBarCreate.Click += buttonChartBarCreate_Click; - // - // buttonExcelCreate - // - buttonExcelCreate.Location = new Point(194, 35); - buttonExcelCreate.Name = "buttonExcelCreate"; - buttonExcelCreate.Size = new Size(140, 48); - buttonExcelCreate.TabIndex = 21; - buttonExcelCreate.Text = "Создать Excel таблицу по всем книгам"; - buttonExcelCreate.UseVisualStyleBackColor = true; - buttonExcelCreate.Click += buttonExcelCreate_Click; + редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem"; + редактироватьToolStripMenuItem.Size = new Size(99, 20); + редактироватьToolStripMenuItem.Text = "Редактировать"; + редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click; // // FormLibrary // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(821, 489); - Controls.Add(groupBox3); - Controls.Add(groupBox2); - Controls.Add(groupBox1); + ClientSize = new Size(609, 373); + Controls.Add(controlDataTableCellBooks); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; Name = "FormLibrary"; Text = "Библиотека"; Load += FormLibrary_Load; - groupBox1.ResumeLayout(false); - groupBox1.PerformLayout(); - groupBox2.ResumeLayout(false); - groupBox2.PerformLayout(); - groupBox3.ResumeLayout(false); + menuStrip1.ResumeLayout(false); + menuStrip1.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion - private Button buttonChooseImage; - private GroupBox groupBox1; - private FedComponentLib.DateTextBox dateTextBoxDate; - private Label label1; - private Label label2; - private ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle controlSelectedComboBoxSingleAuthor; - private TextBox textBoxImage; - private Button buttonClearImage; - private Button buttonBookAdd; - private TextBox textBoxTitle; - private GroupBox groupBox2; - private ControlsLibraryNet60.Data.ControlDataTableCell controlDataTableCellBooks; - private Button buttonAddAuthor; private COP_5.PdfForImages pdfForImages; private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord; private FedComponentLib.NonVisualComponents.TableComponent tableComponent; - private Button buttonPdfCreate; - private GroupBox groupBox3; - private Button buttonExcelCreate; - private Button buttonChartBarCreate; + private ToolStripMenuItem менюToolStripMenuItem; + private ToolStripMenuItem авторыToolStripMenuItem; + private ToolStripMenuItem книгиToolStripMenuItem; + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem pDFСОбложкамиToolStripMenuItem; + private ToolStripMenuItem excelПоВсемКнигамToolStripMenuItem; + private ToolStripMenuItem гистограммаВWordToolStripMenuItem; + private MenuStrip menuStrip1; + private ControlsLibraryNet60.Data.ControlDataTableCell controlDataTableCellBooks; + private ToolStripMenuItem удалитьToolStripMenuItem; + private ToolStripMenuItem редактироватьToolStripMenuItem; } } \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/FormLibrary.cs b/COP_5/LibraryAccountingApp_lab3/FormLibrary.cs index b846edd..9165fe0 100644 --- a/COP_5/LibraryAccountingApp_lab3/FormLibrary.cs +++ b/COP_5/LibraryAccountingApp_lab3/FormLibrary.cs @@ -1,21 +1,14 @@ -using ComponentsLibraryNet60.Heplers; -using ControlsLibraryNet60.Data; +using ComponentsLibraryNet60.Models; +using ControlsLibraryNet60.Core; using ControlsLibraryNet60.Models; -using COP_5; using COP_5.PdfHelper; -using COP_5.TestClasses; -using DocumentFormat.OpenXml.Office2010.Excel; -using FedComponentLib; using FedComponentLib.NonVisualComponents.HelperModels; -using FedComponentLib.NonVisualComponents; using LibraryAccountingApp_lab3.Contracts.BindingModels; using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts; +using LibraryAccountingApp_lab3.Contracts.SearchModels; using LibraryAccountingApp_lab3.Contracts.StorageContracts; using LibraryAccountingApp_lab3.Contracts.ViewModels; using LibraryAccountingApp_lab3.DatabaseImplement.Models; -using Microsoft.IdentityModel.Abstractions; -using System.Windows.Forms; -using ComponentsLibraryNet60.Models; namespace LibraryAccountingApp_lab3 { @@ -27,7 +20,7 @@ namespace LibraryAccountingApp_lab3 public readonly IBookStorage _bookStorage; private List BooksImages = new List(); int rowIndex = 0; - private int? _id; + private int _id; public int Id { set { _id = value; } } public FormLibrary(IBookLogic bookLogic, IAuthorLogic authorLogic) @@ -37,8 +30,6 @@ namespace LibraryAccountingApp_lab3 _authorLogic = authorLogic; InitializeTableBooks(); LoadDataInTable(); - FillControlSelectedComboBoxSingle(); - dateTextBoxDate.DatePattern = @"^(0[1-9]|[12][0-9]|3[01])\s+(|||||||||||)\s+\d{4}$"; } private void FormLibrary_Load(object sender, EventArgs e) { @@ -46,39 +37,21 @@ namespace LibraryAccountingApp_lab3 } - private void FillControlSelectedComboBoxSingle() - { - controlSelectedComboBoxSingleAuthor.Clear(); - try - { - var list = _authorLogic.Read(null); - - if (list != null) - { - foreach (var author in list) - { - controlSelectedComboBoxSingleAuthor.AddElement(author.Name); - } - } - } - catch (Exception ex) - { - MessageBox.Show($" : {ex.Message}"); - } - } - public void AddBook(int rowIndex, BookViewModel book) { + controlDataTableCellBooks.AddCell(rowIndex, 0, book); controlDataTableCellBooks.AddCell(rowIndex, 1, book); controlDataTableCellBooks.AddCell(rowIndex, 2, book); controlDataTableCellBooks.AddCell(rowIndex, 3, book); } - private void LoadDataInTable() + public void LoadDataInTable() { try { - var list = _bookLogic.Read(null); + controlDataTableCellBooks.Clear(); + + var list = _bookLogic.ReadList(null); if (list != null) { @@ -109,119 +82,100 @@ namespace LibraryAccountingApp_lab3 }; DataTableColumnConfig item2 = new DataTableColumnConfig { - ColumnHeader = "Title", + ColumnHeader = "", PropertyName = "Title", - Width = 150, + Width = 250, Visible = true, }; DataTableColumnConfig item3 = new DataTableColumnConfig { - ColumnHeader = "Author", - PropertyName = "Author", - Width = 150, + ColumnHeader = "", + PropertyName = "AuthorName", + Width = 180, Visible = true, }; DataTableColumnConfig item4 = new DataTableColumnConfig { - ColumnHeader = "Date", + ColumnHeader = " ", PropertyName = "Date", Width = 150, Visible = true, }; + columns.Add(item1); columns.Add(item2); columns.Add(item3); columns.Add(item4); controlDataTableCellBooks.LoadColumns(columns); } - private void buttonBookAdd_Click(object sender, EventArgs e) + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (string.IsNullOrEmpty(textBoxTitle.Text)) - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); - try + if (keyData == (Keys.Control | Keys.A)) { - if (string.IsNullOrEmpty(dateTextBoxDate.TextBoxValue)) - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); + ToolStripMenuItem_Click(null, null); + return true; } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - if (string.IsNullOrEmpty(controlSelectedComboBoxSingleAuthor.SelectedElement)) - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); - if (string.IsNullOrEmpty(textBoxImage.Text)) - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); - try + if (keyData == (Keys.Control | Keys.U)) { - _bookLogic.CreateOrUpdate(new BookBindingModel - { - Id = _id, - Title = textBoxTitle.Text, - Author = controlSelectedComboBoxSingleAuthor.SelectedElement, - Date = dateTextBoxDate.TextBoxValue, - Image = selectedImage, - }); - LoadDataInTable(); - textBoxTitle.Clear(); - controlSelectedComboBoxSingleAuthor.SelectedElement = null; - textBoxImage.Clear(); + ToolStripMenuItem_Click(null, null); + return true; + } - MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - DialogResult = DialogResult.OK; - } - catch + if (keyData == (Keys.Control | Keys.D)) { - MessageBox.Show(" !", "", MessageBoxButtons.OK, MessageBoxIcon.Error); + ToolStripMenuItem_Click(null, null); + return true; } + + if (keyData == (Keys.Control | Keys.S)) + { + pDFToolStripMenuItem_Click(null, null); + return true; + } + + if (keyData == (Keys.Control | Keys.T)) + { + excelToolStripMenuItem_Click(null, null); + return true; + } + + if (keyData == (Keys.Control | Keys.C)) + { + WordToolStripMenuItem_Click(null, null); + return true; + } + + return base.ProcessCmdKey(ref msg, keyData); } - private void buttonChooseImage_Click(object sender, EventArgs e) - { - using OpenFileDialog openFileDialog = new OpenFileDialog - { - Multiselect = true, - Filter = "|*.jpg;*.jpeg;*.png;*.bmp" - }; - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - ClearImage(); - foreach (string filePath in openFileDialog.FileNames) - { - selectedImage = File.ReadAllBytes(filePath); - textBoxImage.Text = Path.GetFileName(filePath); - } - } - } - - private void ClearImage() - { - selectedImage = null; - textBoxImage.Clear(); - } - - private void buttonClearImage_Click(object sender, EventArgs e) - { - ClearImage(); - } - - private void buttonAddAuthor_Click(object sender, EventArgs e) + private void ToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormAuthor)); if (service is FormAuthor form) { form.ShowDialog(); } - FillControlSelectedComboBoxSingle(); } - private void buttonPdfCreate_Click(object sender, EventArgs e) + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormBook)); + if (service is FormBook form) + { + form.ShowDialog(); + } + + LoadDataInTable(); + } + + private void pDFToolStripMenuItem_Click(object sender, EventArgs e) { try { - var list = _bookLogic.Read(null); - + var list = _bookLogic.ReadList(null); if (list != null) { BooksImages.Clear(); @@ -231,66 +185,30 @@ namespace LibraryAccountingApp_lab3 } } - var config = new ImagePdfInfo + using SaveFileDialog saveFileDialog = new SaveFileDialog { - FilePath = "D:\\ULSTU\\COP\\PdfWithImageBooks.pdf", - Header = " ", - Images = BooksImages + Filter = "PDF Files|*.pdf", + DefaultExt = "pdf", + AddExtension = true }; - pdfForImages.CreatePdf(config); - - MessageBox.Show("PDF !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - MessageBox.Show($" : {ex.Message}"); - } - } - - private void buttonExcelCreate_Click(object sender, EventArgs e) - { - try - { - string filepath = "D:\\ULSTU\\COP\\ExcelWithBooks.xlsx"; - string title = " "; - List mergeCells = new List() + if (saveFileDialog.ShowDialog() == DialogResult.OK) { - new MergeCells("", new int[] { 1, 2 }), - }; - List columns = new List() - { - new ColumnInfo("Id", "Id", 10), - new ColumnInfo("Title", "", 30), - new ColumnInfo("Author", "", 30), - new ColumnInfo("Date", "", 20), - }; - - var list = _bookLogic.Read(null); - List data = new List(); - - if (list != null) - { - foreach (var book in list) + var config = new ImagePdfInfo { - data.Add(new BookForExcel - { - Id = book.Id, - Title = book.Title, - Author = book.Author, - Date = book.Date - }); - } - controlDataTableCellBooks.Update(); + FilePath = saveFileDialog.FileName, + Header = " ", + Images = BooksImages + }; + + pdfForImages.CreatePdf(config); + + MessageBox.Show("PDF !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show(" .", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } - - - tableComponent.CreateDocument(filepath, title, - mergeCells, columns, - data); - - MessageBox.Show("Excel !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); - } catch (Exception ex) { @@ -298,51 +216,176 @@ namespace LibraryAccountingApp_lab3 } } - private void buttonChartBarCreate_Click(object sender, EventArgs e) + private void excelToolStripMenuItem_Click(object sender, EventArgs e) { try { - List<(int AuthorId, double Value)> listData = new List<(int AuthorId, double Value)>(); - (int AuthorId, double Value) item = default; - - // - var authors = _authorLogic.Read(null); - if (authors != null) + // Excel + using SaveFileDialog saveFileDialog = new SaveFileDialog { - // - var books = _bookLogic.Read(null); - if (books != null) + Filter = "Excel Files|*.xlsx", + DefaultExt = "xlsx", + AddExtension = true + }; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + string filepath = saveFileDialog.FileName; + string title = " "; + List mergeCells = new List() { - // - foreach (var author in authors) + new MergeCells("", new int[] { 1, 2 }), + }; + List columns = new List() + { + new ColumnInfo("Id", "Id", 10), + new ColumnInfo("Title", "", 30), + new ColumnInfo("AuthorName", "", 30), + new ColumnInfo("Date", "", 20), + }; + + var list = _bookLogic.ReadList(null); + List data = new List(); + + if (list != null) + { + foreach (var book in list) { - int bookCount = books.Count(book => book.Author == author.Name); - listData.Add((author.Id, bookCount)); + data.Add(new BookForExcel + { + Id = book.Id, + Title = book.Title, + AuthorName = book.AuthorName, + Date = book.Date + }); + } + controlDataTableCellBooks.Update(); + } + + tableComponent.CreateDocument(filepath, title, mergeCells, columns, data); + + MessageBox.Show("Excel !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show(" .", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + catch (Exception ex) + { + MessageBox.Show($" : {ex.Message}"); + } + } + + private void WordToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + // Word + using SaveFileDialog saveFileDialog = new SaveFileDialog + { + Filter = "Word Files|*.docx", + DefaultExt = "docx", + AddExtension = true + }; + + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + List<(int AuthorId, double Value)> listData = new List<(int AuthorId, double Value)>(); + (int AuthorId, double Value) item = default; + + // + var authors = _authorLogic.ReadList(null); + if (authors != null) + { + // + var books = _bookLogic.ReadList(null); + if (books != null) + { + // + foreach (var author in authors) + { + int bookCount = books.Count(book => book.AuthorName == author.Name); + listData.Add((author.Id, bookCount)); + } } } + + Dictionary> data = new() + { + { "", listData } + }; + + var config = new ComponentDocumentWithChartConfig + { + ChartTitle = " ", + FilePath = saveFileDialog.FileName, + Header = " Word", + Data = data, + LegendLocation = ComponentsLibraryNet60.Models.Location.Rigth, + }; + + componentDocumentWithChartBarWord.CreateDoc(config); + MessageBox.Show("Word !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } - - Dictionary> data = new() + else { - { "", listData } - }; - - var config = new ComponentDocumentWithChartConfig - { - ChartTitle = " ", - FilePath = "D:\\ULSTU\\COP\\WordChartBar.docx", - Header = " Word", - Data = data, - LegendLocation = ComponentsLibraryNet60.Models.Location.Rigth, - }; - - componentDocumentWithChartBarWord.CreateDoc(config); - MessageBox.Show("Word !", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show(" .", "", MessageBoxButtons.OK, MessageBoxIcon.Information); + } } catch (Exception ex) { MessageBox.Show($" : {ex.Message}"); } } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + if (MessageBox.Show(" ?", "", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + var test = controlDataTableCellBooks.GetSelectedObject().Title; + int test2 = controlDataTableCellBooks.GetSelectedObject().Id; + var test3 = controlDataTableCellBooks.GetSelectedObject(); + var test4 = controlDataTableCellBooks.GetSelectedObject(); + var test5 = controlDataTableCellBooks.GetSelectedObject(); + if (_bookLogic.Delete(new BookBindingModel { Id = controlDataTableCellBooks.GetSelectedObject().Id })) + { + LoadDataInTable(); + } + else + { + MessageBox.Show(" ", "", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + //if (MessageBox.Show(" ", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + //{ + // int id = Convert.ToInt32(controlDataTableCellBooks.GetSelectedObject().Id); + // var test = controlDataTableCellBooks.GetSelectedObject().Title; + // try + // { + // _bookLogic.Delete(new BookBindingModel { Id = id }); + // } + // catch (Exception ex) + // { + // MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error); + // } + // LoadDataInTable(); + //} + + } + + private void ToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormBook)); + if (service is FormBook form) + { + form.Id = controlDataTableCellBooks.GetSelectedObject().Id; + if (form.ShowDialog() == DialogResult.OK) + { + LoadDataInTable(); + } + } + } } } \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/FormLibrary.resx b/COP_5/LibraryAccountingApp_lab3/FormLibrary.resx index 36b8175..69b300b 100644 --- a/COP_5/LibraryAccountingApp_lab3/FormLibrary.resx +++ b/COP_5/LibraryAccountingApp_lab3/FormLibrary.resx @@ -126,4 +126,7 @@ 428, 17 + + 596, 17 + \ No newline at end of file diff --git a/COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.Designer.cs b/COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.Designer.cs similarity index 77% rename from COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.Designer.cs rename to COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.Designer.cs index 6adf031..0ab7669 100644 --- a/COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.Designer.cs +++ b/COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.Designer.cs @@ -11,8 +11,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace LibraryAccountingApp_lab3.Migrations { [DbContext(typeof(LibraryDatabase))] - [Migration("20241028164711_InitialCreate")] - partial class InitialCreate + [Migration("20241111111934_Initial")] + partial class Initial { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -49,9 +49,8 @@ namespace LibraryAccountingApp_lab3.Migrations SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("Author") - .IsRequired() - .HasColumnType("nvarchar(max)"); + b.Property("AuthorId") + .HasColumnType("int"); b.Property("Date") .IsRequired() @@ -67,8 +66,21 @@ namespace LibraryAccountingApp_lab3.Migrations b.HasKey("Id"); + b.HasIndex("AuthorId"); + b.ToTable("Books"); }); + + modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b => + { + b.HasOne("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", "Author") + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + }); #pragma warning restore 612, 618 } } diff --git a/COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.cs b/COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.cs similarity index 74% rename from COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.cs rename to COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.cs index 04a7fda..292a3fa 100644 --- a/COP_5/LibraryAccountingApp_lab3/Migrations/20241028164711_InitialCreate.cs +++ b/COP_5/LibraryAccountingApp_lab3/Migrations/20241111111934_Initial.cs @@ -5,7 +5,7 @@ namespace LibraryAccountingApp_lab3.Migrations { /// - public partial class InitialCreate : Migration + public partial class Initial : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) @@ -30,24 +30,35 @@ namespace LibraryAccountingApp_lab3.Migrations Id = table.Column(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column(type: "nvarchar(max)", nullable: false), - Author = table.Column(type: "nvarchar(max)", nullable: false), + AuthorId = table.Column(type: "int", nullable: false), Date = table.Column(type: "nvarchar(max)", nullable: false), Image = table.Column(type: "varbinary(max)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Books", x => x.Id); + table.ForeignKey( + name: "FK_Books_Authors_AuthorId", + column: x => x.AuthorId, + principalTable: "Authors", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); }); + + migrationBuilder.CreateIndex( + name: "IX_Books_AuthorId", + table: "Books", + column: "AuthorId"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( - name: "Authors"); + name: "Books"); migrationBuilder.DropTable( - name: "Books"); + name: "Authors"); } } } diff --git a/COP_5/LibraryAccountingApp_lab3/Migrations/LibraryDatabaseModelSnapshot.cs b/COP_5/LibraryAccountingApp_lab3/Migrations/LibraryDatabaseModelSnapshot.cs index eaa95c6..0f7e42e 100644 --- a/COP_5/LibraryAccountingApp_lab3/Migrations/LibraryDatabaseModelSnapshot.cs +++ b/COP_5/LibraryAccountingApp_lab3/Migrations/LibraryDatabaseModelSnapshot.cs @@ -46,9 +46,8 @@ namespace LibraryAccountingApp_lab3.Migrations SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("Author") - .IsRequired() - .HasColumnType("nvarchar(max)"); + b.Property("AuthorId") + .HasColumnType("int"); b.Property("Date") .IsRequired() @@ -64,8 +63,21 @@ namespace LibraryAccountingApp_lab3.Migrations b.HasKey("Id"); + b.HasIndex("AuthorId"); + b.ToTable("Books"); }); + + modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b => + { + b.HasOne("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", "Author") + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + }); #pragma warning restore 612, 618 } } diff --git a/COP_5/LibraryAccountingApp_lab3/Program.cs b/COP_5/LibraryAccountingApp_lab3/Program.cs index c02f003..39c82ac 100644 --- a/COP_5/LibraryAccountingApp_lab3/Program.cs +++ b/COP_5/LibraryAccountingApp_lab3/Program.cs @@ -36,6 +36,7 @@ namespace LibraryAccountingApp_lab3 services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file