diff --git a/Bookshop/BookshopDatabaseImplement/Implemets/OrderStorage.cs b/Bookshop/BookshopDatabaseImplement/Implemets/OrderStorage.cs index b07926d..c32a82c 100644 --- a/Bookshop/BookshopDatabaseImplement/Implemets/OrderStorage.cs +++ b/Bookshop/BookshopDatabaseImplement/Implemets/OrderStorage.cs @@ -18,37 +18,28 @@ namespace BookshopDatabaseImplement.Implemets { using var context = new BookshopDatabase(); return context.Orders - .Include(x => x.Author) - .Include(x => x.Genre) + .Include(x => x.Book) + .Include(x => x.User) .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(OrderSearchModel model) { - if (string.IsNullOrEmpty(model.Title)) - { - return new(); - } using var context = new BookshopDatabase(); return context.Orders - .Include(x => x.Author) - .Include(x => x.Genre) - .Where(x => x.Title.Contains(model.Title)) + .Include(x => x.Book) + .Include(x => x.User) .Select(x => x.GetViewModel) .ToList(); } public OrderViewModel? GetElement(OrderSearchModel model) { - if (string.IsNullOrEmpty(model.Title) && !model.Id.HasValue) - { - return null; - } using var context = new BookshopDatabase(); return context.Orders - .Include(x => x.Author) - .Include(x => x.Genre) + .Include(x => x.Book) + .Include(x => x.User) .FirstOrDefault(x => x.Id.Equals(model.Id)) ?.GetViewModel; } diff --git a/Bookshop/BookshopDatabaseImplement/Implemets/PublisherStorage.cs b/Bookshop/BookshopDatabaseImplement/Implemets/PublisherStorage.cs index 09a8c0b..195d0bf 100644 --- a/Bookshop/BookshopDatabaseImplement/Implemets/PublisherStorage.cs +++ b/Bookshop/BookshopDatabaseImplement/Implemets/PublisherStorage.cs @@ -8,10 +8,82 @@ using BookshopContracts.ViewModels; using BookshopContracts.SearchModels; using BookshopContracts.BindingModels; using BookshopDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; namespace BookshopDatabaseImplement.Implemets { - internal class PublisherStorage + public class PublisherStorage : IPublisherStorage { + public List GetFullList() + { + using var context = new BookshopDatabase(); + return context.Publishers + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(PublisherSearchModel model) + { + if (string.IsNullOrEmpty(model.PublisherName)) + { + return new(); + } + using var context = new BookshopDatabase(); + return context.Publishers + .Where(x => x.PublisherName.Contains(model.PublisherName)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public PublisherViewModel? GetElement(PublisherSearchModel model) + { + if (string.IsNullOrEmpty(model.PublisherName) && !model.Id.HasValue) + { + return null; + } + using var context = new BookshopDatabase(); + return context.Publishers + .FirstOrDefault(x => x.Id.Equals(model.Id)) + ?.GetViewModel; + } + + public PublisherViewModel? Insert(PublisherBindingModel model) + { + var newPublisher = Publisher.Create(model); + if (newPublisher == null) + { + return null; + } + using var context = new BookshopDatabase(); + context.Publishers.Add(newPublisher); + context.SaveChanges(); + return newPublisher.GetViewModel; + } + + public PublisherViewModel? Update(PublisherBindingModel model) + { + using var context = new BookshopDatabase(); + var client = context.Publishers.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + client.Update(model); + context.SaveChanges(); + return client.GetViewModel; + } + + public PublisherViewModel? Delete(PublisherBindingModel model) + { + using var context = new BookshopDatabase(); + var element = context.Publishers.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Publishers.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } } } diff --git a/Bookshop/BookshopDatabaseImplement/Implemets/ReviewStorage.cs b/Bookshop/BookshopDatabaseImplement/Implemets/ReviewStorage.cs index 73bc7a1..5aa08c2 100644 --- a/Bookshop/BookshopDatabaseImplement/Implemets/ReviewStorage.cs +++ b/Bookshop/BookshopDatabaseImplement/Implemets/ReviewStorage.cs @@ -8,10 +8,79 @@ using BookshopContracts.ViewModels; using BookshopContracts.SearchModels; using BookshopContracts.BindingModels; using BookshopDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; namespace BookshopDatabaseImplement.Implemets { - internal class ReviewStorage + public class ReviewStorage : IReviewStorage { + public List GetFullList() + { + using var context = new BookshopDatabase(); + return context.Reviews + .Include(x => x.Book) + .Include(x => x.User) + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(ReviewSearchModel model) + { + using var context = new BookshopDatabase(); + return context.Reviews + .Include(x => x.Book) + .Include(x => x.User) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ReviewViewModel? GetElement(ReviewSearchModel model) + { + using var context = new BookshopDatabase(); + return context.Reviews + .Include(x => x.Book) + .Include(x => x.User) + .FirstOrDefault(x => x.Id.Equals(model.Id)) + ?.GetViewModel; + } + + public ReviewViewModel? Insert(ReviewBindingModel model) + { + var newReview = Review.Create(model); + if (newReview == null) + { + return null; + } + using var context = new BookshopDatabase(); + context.Reviews.Add(newReview); + context.SaveChanges(); + return newReview.GetViewModel; + } + + public ReviewViewModel? Update(ReviewBindingModel model) + { + using var context = new BookshopDatabase(); + var client = context.Reviews.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + client.Update(model); + context.SaveChanges(); + return client.GetViewModel; + } + + public ReviewViewModel? Delete(ReviewBindingModel model) + { + using var context = new BookshopDatabase(); + var element = context.Reviews.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Reviews.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } } } diff --git a/Bookshop/BookshopDatabaseImplement/Implemets/UserStorage.cs b/Bookshop/BookshopDatabaseImplement/Implemets/UserStorage.cs index 390c631..89f9756 100644 --- a/Bookshop/BookshopDatabaseImplement/Implemets/UserStorage.cs +++ b/Bookshop/BookshopDatabaseImplement/Implemets/UserStorage.cs @@ -8,10 +8,82 @@ using BookshopContracts.ViewModels; using BookshopContracts.SearchModels; using BookshopContracts.BindingModels; using BookshopDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; namespace BookshopDatabaseImplement.Implemets { - internal class UserStorage + public class UserStorage : IUserStorage { + public List GetFullList() + { + using var context = new BookshopDatabase(); + return context.Users + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(UserSearchModel model) + { + if (string.IsNullOrEmpty(model.Username)) + { + return new(); + } + using var context = new BookshopDatabase(); + return context.Users + .Where(x => x.Username.Contains(model.Username)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public UserViewModel? GetElement(UserSearchModel model) + { + if (string.IsNullOrEmpty(model.Username) && string.IsNullOrEmpty(model.UserEmail) && !model.Id.HasValue) + { + return null; + } + using var context = new BookshopDatabase(); + return context.Users + .FirstOrDefault(x => x.Id.Equals(model.Id)) + ?.GetViewModel; + } + + public UserViewModel? Insert(UserBindingModel model) + { + var newUser = User.Create(model); + if (newUser == null) + { + return null; + } + using var context = new BookshopDatabase(); + context.Users.Add(newUser); + context.SaveChanges(); + return newUser.GetViewModel; + } + + public UserViewModel? Update(UserBindingModel model) + { + using var context = new BookshopDatabase(); + var client = context.Users.FirstOrDefault(x => x.Id == model.Id); + if (client == null) + { + return null; + } + client.Update(model); + context.SaveChanges(); + return client.GetViewModel; + } + + public UserViewModel? Delete(UserBindingModel model) + { + using var context = new BookshopDatabase(); + var element = context.Users.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Users.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } } } diff --git a/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.Designer.cs b/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.Designer.cs new file mode 100644 index 0000000..a3d6bef --- /dev/null +++ b/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.Designer.cs @@ -0,0 +1,264 @@ +// +using System; +using BookshopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BookshopDatabaseImplement.Migrations +{ + [DbContext(typeof(BookshopDatabase))] + [Migration("20240521183229_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.19") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Author", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthorName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Country") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Authors"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Book", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthorId") + .HasColumnType("int"); + + b.Property("GenreId") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("YearOfPublication") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("GenreId"); + + b.ToTable("Books"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Genre", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("GenreName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Genres"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BookId") + .HasColumnType("int"); + + b.Property("OrderDate") + .HasColumnType("datetime2"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BookId"); + + b.HasIndex("UserId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Publisher", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PublisherName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Publishers"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Review", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BookId") + .HasColumnType("int"); + + b.Property("ReviewDate") + .HasColumnType("datetime2"); + + b.Property("ReviewText") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BookId"); + + b.HasIndex("UserId"); + + b.ToTable("Reviews"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("UserEmail") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Book", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Author", "Author") + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.Genre", "Genre") + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("Genre"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Order", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Book", "Book") + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Book"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Review", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Book", "Book") + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Book"); + + b.Navigation("User"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.cs b/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.cs new file mode 100644 index 0000000..352936e --- /dev/null +++ b/Bookshop/BookshopDatabaseImplement/Migrations/20240521183229_InitialCreate.cs @@ -0,0 +1,211 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BookshopDatabaseImplement.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Authors", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + AuthorName = table.Column(type: "nvarchar(max)", nullable: false), + Country = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Authors", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Genres", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + GenreName = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Genres", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Publishers", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PublisherName = table.Column(type: "nvarchar(max)", nullable: false), + Address = table.Column(type: "nvarchar(max)", nullable: false), + PhoneNumber = table.Column(type: "nvarchar(max)", nullable: false), + Email = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Publishers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Username = table.Column(type: "nvarchar(max)", nullable: false), + UserEmail = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Books", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Title = table.Column(type: "nvarchar(max)", nullable: false), + YearOfPublication = table.Column(type: "int", nullable: false), + AuthorId = table.Column(type: "int", nullable: false), + GenreId = table.Column(type: "int", 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); + table.ForeignKey( + name: "FK_Books_Genres_GenreId", + column: x => x.GenreId, + principalTable: "Genres", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + OrderDate = table.Column(type: "datetime2", nullable: false), + Quantity = table.Column(type: "int", nullable: false), + BookId = table.Column(type: "int", nullable: false), + UserId = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + table.ForeignKey( + name: "FK_Orders_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Reviews", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ReviewText = table.Column(type: "nvarchar(max)", nullable: false), + ReviewDate = table.Column(type: "datetime2", nullable: false), + BookId = table.Column(type: "int", nullable: false), + UserId = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Reviews", x => x.Id); + table.ForeignKey( + name: "FK_Reviews_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Reviews_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Books_AuthorId", + table: "Books", + column: "AuthorId"); + + migrationBuilder.CreateIndex( + name: "IX_Books_GenreId", + table: "Books", + column: "GenreId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_BookId", + table: "Orders", + column: "BookId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_UserId", + table: "Orders", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_Reviews_BookId", + table: "Reviews", + column: "BookId"); + + migrationBuilder.CreateIndex( + name: "IX_Reviews_UserId", + table: "Reviews", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Orders"); + + migrationBuilder.DropTable( + name: "Publishers"); + + migrationBuilder.DropTable( + name: "Reviews"); + + migrationBuilder.DropTable( + name: "Books"); + + migrationBuilder.DropTable( + name: "Users"); + + migrationBuilder.DropTable( + name: "Authors"); + + migrationBuilder.DropTable( + name: "Genres"); + } + } +} diff --git a/Bookshop/BookshopDatabaseImplement/Migrations/BookshopDatabaseModelSnapshot.cs b/Bookshop/BookshopDatabaseImplement/Migrations/BookshopDatabaseModelSnapshot.cs new file mode 100644 index 0000000..cb9d6d8 --- /dev/null +++ b/Bookshop/BookshopDatabaseImplement/Migrations/BookshopDatabaseModelSnapshot.cs @@ -0,0 +1,261 @@ +// +using System; +using BookshopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BookshopDatabaseImplement.Migrations +{ + [DbContext(typeof(BookshopDatabase))] + partial class BookshopDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.19") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Author", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthorName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Country") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Authors"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Book", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthorId") + .HasColumnType("int"); + + b.Property("GenreId") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("YearOfPublication") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("GenreId"); + + b.ToTable("Books"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Genre", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("GenreName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Genres"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BookId") + .HasColumnType("int"); + + b.Property("OrderDate") + .HasColumnType("datetime2"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BookId"); + + b.HasIndex("UserId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Publisher", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PublisherName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Publishers"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Review", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BookId") + .HasColumnType("int"); + + b.Property("ReviewDate") + .HasColumnType("datetime2"); + + b.Property("ReviewText") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BookId"); + + b.HasIndex("UserId"); + + b.ToTable("Reviews"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("UserEmail") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Book", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Author", "Author") + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.Genre", "Genre") + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Author"); + + b.Navigation("Genre"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Order", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Book", "Book") + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Book"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("BookshopDatabaseImplement.Models.Review", b => + { + b.HasOne("BookshopDatabaseImplement.Models.Book", "Book") + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BookshopDatabaseImplement.Models.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Book"); + + b.Navigation("User"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Bookshop/BookshopView/BookshopView.csproj b/Bookshop/BookshopView/BookshopView.csproj index b57c89e..10ab4f6 100644 --- a/Bookshop/BookshopView/BookshopView.csproj +++ b/Bookshop/BookshopView/BookshopView.csproj @@ -8,4 +8,19 @@ enable + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + \ No newline at end of file diff --git a/Bookshop/BookshopView/Form1.cs b/Bookshop/BookshopView/Form1.cs deleted file mode 100644 index fbbf4fc..0000000 --- a/Bookshop/BookshopView/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace BookshopView -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormAuthor.Designer.cs b/Bookshop/BookshopView/FormAuthor.Designer.cs new file mode 100644 index 0000000..d43c5c5 --- /dev/null +++ b/Bookshop/BookshopView/FormAuthor.Designer.cs @@ -0,0 +1,119 @@ +namespace BookshopView +{ + partial class FormAuthor + { + /// + /// 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() + { + this.ButtonCancel = new System.Windows.Forms.Button(); + this.ButtonSave = new System.Windows.Forms.Button(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.labelName = new System.Windows.Forms.Label(); + this.textBoxCountry = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // ButtonCancel + // + this.ButtonCancel.Location = new System.Drawing.Point(317, 126); + this.ButtonCancel.Name = "ButtonCancel"; + this.ButtonCancel.Size = new System.Drawing.Size(94, 29); + this.ButtonCancel.TabIndex = 15; + this.ButtonCancel.Text = "Отмена"; + this.ButtonCancel.UseVisualStyleBackColor = true; + this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // ButtonSave + // + this.ButtonSave.Location = new System.Drawing.Point(105, 126); + this.ButtonSave.Name = "ButtonSave"; + this.ButtonSave.Size = new System.Drawing.Size(94, 29); + this.ButtonSave.TabIndex = 14; + this.ButtonSave.Text = "Сохранить"; + this.ButtonSave.UseVisualStyleBackColor = true; + this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(174, 24); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(295, 27); + this.textBoxName.TabIndex = 13; + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(55, 27); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(94, 20); + this.labelName.TabIndex = 12; + this.labelName.Text = "Имя автора:"; + // + // textBoxCountry + // + this.textBoxCountry.Location = new System.Drawing.Point(174, 71); + this.textBoxCountry.Name = "textBoxCountry"; + this.textBoxCountry.Size = new System.Drawing.Size(295, 27); + this.textBoxCountry.TabIndex = 17; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(55, 74); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(61, 20); + this.label1.TabIndex = 16; + this.label1.Text = "Страна:"; + // + // FormAuthor + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(555, 172); + this.Controls.Add(this.textBoxCountry); + this.Controls.Add(this.label1); + this.Controls.Add(this.ButtonCancel); + this.Controls.Add(this.ButtonSave); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelName); + this.Name = "FormAuthor"; + this.Text = "Автор"; + this.Load += new System.EventHandler(this.FormAuthor_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Button ButtonCancel; + private Button ButtonSave; + private TextBox textBoxName; + private Label labelName; + private TextBox textBoxCountry; + private Label label1; + } +} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormAuthor.cs b/Bookshop/BookshopView/FormAuthor.cs new file mode 100644 index 0000000..e36f27f --- /dev/null +++ b/Bookshop/BookshopView/FormAuthor.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using BookshopContracts.BindingModels; +using BookshopContracts.BusinessLogicsContracts; +using BookshopContracts.SearchModels; + +namespace BookshopView +{ + public partial class FormAuthor : Form + { + private readonly ILogger _logger; + private readonly IAuthorLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public FormAuthor(ILogger logger, IAuthorLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormAuthor_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + var view = _logic.ReadElement(new AuthorSearchModel + { + Id = + _id.Value + }); + if (view != null) + { + textBoxName.Text = view.AuthorName; + textBoxCountry.Text = view.Country; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new AuthorBindingModel + { + Id = _id ?? 0, + AuthorName = textBoxName.Text, + Country = textBoxCountry.Text + }; + var operationResult = _id.HasValue ? _logic.Update(model) : + _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/Bookshop/BookshopView/FormAuthor.resx b/Bookshop/BookshopView/FormAuthor.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Bookshop/BookshopView/FormAuthor.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Bookshop/BookshopView/FormAuthors.Designer.cs b/Bookshop/BookshopView/FormAuthors.Designer.cs new file mode 100644 index 0000000..c1bc8e2 --- /dev/null +++ b/Bookshop/BookshopView/FormAuthors.Designer.cs @@ -0,0 +1,110 @@ +namespace BookshopView +{ + partial class FormAuthors + { + /// + /// 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() + { + this.ButtonUpd = new System.Windows.Forms.Button(); + this.ButtonDel = new System.Windows.Forms.Button(); + this.ButtonRef = new System.Windows.Forms.Button(); + this.ButtonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ButtonUpd + // + this.ButtonUpd.Location = new System.Drawing.Point(543, 94); + this.ButtonUpd.Name = "ButtonUpd"; + this.ButtonUpd.Size = new System.Drawing.Size(111, 32); + this.ButtonUpd.TabIndex = 14; + this.ButtonUpd.Text = "Изменить"; + this.ButtonUpd.UseVisualStyleBackColor = true; + // + // ButtonDel + // + this.ButtonDel.Location = new System.Drawing.Point(543, 163); + this.ButtonDel.Name = "ButtonDel"; + this.ButtonDel.Size = new System.Drawing.Size(111, 32); + this.ButtonDel.TabIndex = 13; + this.ButtonDel.Text = "Удалить"; + this.ButtonDel.UseVisualStyleBackColor = true; + // + // ButtonRef + // + this.ButtonRef.Location = new System.Drawing.Point(543, 232); + this.ButtonRef.Name = "ButtonRef"; + this.ButtonRef.Size = new System.Drawing.Size(111, 32); + this.ButtonRef.TabIndex = 12; + this.ButtonRef.Text = "Обновить"; + this.ButtonRef.UseVisualStyleBackColor = true; + // + // ButtonAdd + // + this.ButtonAdd.Location = new System.Drawing.Point(543, 26); + this.ButtonAdd.Name = "ButtonAdd"; + this.ButtonAdd.Size = new System.Drawing.Size(111, 32); + this.ButtonAdd.TabIndex = 11; + this.ButtonAdd.Text = "Добавить"; + this.ButtonAdd.UseVisualStyleBackColor = true; + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(21, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(490, 426); + this.dataGridView.TabIndex = 10; + // + // FormAuthors + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(675, 450); + this.Controls.Add(this.ButtonUpd); + this.Controls.Add(this.ButtonDel); + this.Controls.Add(this.ButtonRef); + this.Controls.Add(this.ButtonAdd); + this.Controls.Add(this.dataGridView); + this.Name = "FormAuthors"; + this.Text = "Авторы"; + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button ButtonUpd; + private Button ButtonDel; + private Button ButtonRef; + private Button ButtonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormAuthors.cs b/Bookshop/BookshopView/FormAuthors.cs new file mode 100644 index 0000000..fa60cb2 --- /dev/null +++ b/Bookshop/BookshopView/FormAuthors.cs @@ -0,0 +1,118 @@ +using BookshopContracts.BindingModels; +using BookshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BookshopView +{ + public partial class FormAuthors : Form + { + private readonly ILogger _logger; + private readonly IAuthorLogic _logic; + public FormAuthors(ILogger logger, IAuthorLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormAuthors_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["AuthorName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Country"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormAuthor)); + if (service is FormAuthor form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = + Program.ServiceProvider?.GetService(typeof(FormAuthor)); + if (service is FormAuthor form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление компонента"); + try + { + if (!_logic.Delete(new AuthorBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/Bookshop/BookshopView/FormAuthors.resx b/Bookshop/BookshopView/FormAuthors.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Bookshop/BookshopView/FormAuthors.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Bookshop/BookshopView/FormCreateOrder.Designer.cs b/Bookshop/BookshopView/FormCreateOrder.Designer.cs new file mode 100644 index 0000000..796a6e1 --- /dev/null +++ b/Bookshop/BookshopView/FormCreateOrder.Designer.cs @@ -0,0 +1,39 @@ +namespace BookshopView +{ + partial class FormCreateOrder + { + /// + /// 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() + { + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "FormCreateOrder"; + } + + #endregion + } +} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormCreateOrder.cs b/Bookshop/BookshopView/FormCreateOrder.cs new file mode 100644 index 0000000..674cc6b --- /dev/null +++ b/Bookshop/BookshopView/FormCreateOrder.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BookshopView +{ + public partial class FormCreateOrder : Form + { + public FormCreateOrder() + { + InitializeComponent(); + } + } +} diff --git a/Bookshop/BookshopView/Form1.resx b/Bookshop/BookshopView/FormCreateOrder.resx similarity index 100% rename from Bookshop/BookshopView/Form1.resx rename to Bookshop/BookshopView/FormCreateOrder.resx diff --git a/Bookshop/BookshopView/FormGenre.Designer.cs b/Bookshop/BookshopView/FormGenre.Designer.cs new file mode 100644 index 0000000..55ad0de --- /dev/null +++ b/Bookshop/BookshopView/FormGenre.Designer.cs @@ -0,0 +1,97 @@ +namespace BookshopView +{ + partial class FormGenre + { + /// + /// 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() + { + this.ButtonCancel = new System.Windows.Forms.Button(); + this.ButtonSave = new System.Windows.Forms.Button(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.labelName = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // ButtonCancel + // + this.ButtonCancel.Location = new System.Drawing.Point(288, 127); + this.ButtonCancel.Name = "ButtonCancel"; + this.ButtonCancel.Size = new System.Drawing.Size(94, 29); + this.ButtonCancel.TabIndex = 11; + this.ButtonCancel.Text = "Отмена"; + this.ButtonCancel.UseVisualStyleBackColor = true; + this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // ButtonSave + // + this.ButtonSave.Location = new System.Drawing.Point(76, 127); + this.ButtonSave.Name = "ButtonSave"; + this.ButtonSave.Size = new System.Drawing.Size(94, 29); + this.ButtonSave.TabIndex = 10; + this.ButtonSave.Text = "Сохранить"; + this.ButtonSave.UseVisualStyleBackColor = true; + this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(145, 57); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(295, 27); + this.textBoxName.TabIndex = 8; + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(26, 60); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(80, 20); + this.labelName.TabIndex = 6; + this.labelName.Text = "Название:"; + // + // FormGenre + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(466, 184); + this.Controls.Add(this.ButtonCancel); + this.Controls.Add(this.ButtonSave); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelName); + this.Name = "FormGenre"; + this.Text = "Жанр"; + this.Load += new System.EventHandler(this.FormGenre_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Button ButtonCancel; + private Button ButtonSave; + private TextBox textBoxName; + private Label labelName; + } +} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormGenre.cs b/Bookshop/BookshopView/FormGenre.cs new file mode 100644 index 0000000..644b478 --- /dev/null +++ b/Bookshop/BookshopView/FormGenre.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using BookshopContracts.BindingModels; +using BookshopContracts.BusinessLogicsContracts; +using BookshopContracts.SearchModels; + +namespace BookshopView +{ + public partial class FormGenre : Form + { + + private readonly ILogger _logger; + private readonly IGenreLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + public FormGenre(ILogger logger, IGenreLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormGenre_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + var view = _logic.ReadElement(new GenreSearchModel + { + Id = + _id.Value + }); + if (view != null) + { + textBoxName.Text = view.GenreName; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение компонента"); + try + { + var model = new GenreBindingModel + { + Id = _id ?? 0, + GenreName = textBoxName.Text + }; + var operationResult = _id.HasValue ? _logic.Update(model) : + _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", + MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/Bookshop/BookshopView/FormGenre.resx b/Bookshop/BookshopView/FormGenre.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Bookshop/BookshopView/FormGenre.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Bookshop/BookshopView/FormGenres.Designer.cs b/Bookshop/BookshopView/FormGenres.Designer.cs new file mode 100644 index 0000000..18a667f --- /dev/null +++ b/Bookshop/BookshopView/FormGenres.Designer.cs @@ -0,0 +1,115 @@ +namespace BookshopView +{ + partial class FormGenres + { + /// + /// 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() + { + this.ButtonUpd = new System.Windows.Forms.Button(); + this.ButtonDel = new System.Windows.Forms.Button(); + this.ButtonRef = new System.Windows.Forms.Button(); + this.ButtonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ButtonUpd + // + this.ButtonUpd.Location = new System.Drawing.Point(535, 94); + this.ButtonUpd.Name = "ButtonUpd"; + this.ButtonUpd.Size = new System.Drawing.Size(111, 32); + this.ButtonUpd.TabIndex = 9; + this.ButtonUpd.Text = "Изменить"; + this.ButtonUpd.UseVisualStyleBackColor = true; + this.ButtonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // ButtonDel + // + this.ButtonDel.Location = new System.Drawing.Point(535, 163); + this.ButtonDel.Name = "ButtonDel"; + this.ButtonDel.Size = new System.Drawing.Size(111, 32); + this.ButtonDel.TabIndex = 8; + this.ButtonDel.Text = "Удалить"; + this.ButtonDel.UseVisualStyleBackColor = true; + this.ButtonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // ButtonRef + // + this.ButtonRef.Location = new System.Drawing.Point(535, 232); + this.ButtonRef.Name = "ButtonRef"; + this.ButtonRef.Size = new System.Drawing.Size(111, 32); + this.ButtonRef.TabIndex = 7; + this.ButtonRef.Text = "Обновить"; + this.ButtonRef.UseVisualStyleBackColor = true; + this.ButtonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // ButtonAdd + // + this.ButtonAdd.Location = new System.Drawing.Point(535, 26); + this.ButtonAdd.Name = "ButtonAdd"; + this.ButtonAdd.Size = new System.Drawing.Size(111, 32); + this.ButtonAdd.TabIndex = 6; + this.ButtonAdd.Text = "Добавить"; + this.ButtonAdd.UseVisualStyleBackColor = true; + this.ButtonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(13, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(490, 426); + this.dataGridView.TabIndex = 5; + // + // FormGenres + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(659, 450); + this.Controls.Add(this.ButtonUpd); + this.Controls.Add(this.ButtonDel); + this.Controls.Add(this.ButtonRef); + this.Controls.Add(this.ButtonAdd); + this.Controls.Add(this.dataGridView); + this.Name = "FormGenres"; + this.Text = "Жанры"; + this.Load += new System.EventHandler(this.FormGenres_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button ButtonUpd; + private Button ButtonDel; + private Button ButtonRef; + private Button ButtonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/Bookshop/BookshopView/FormGenres.cs b/Bookshop/BookshopView/FormGenres.cs new file mode 100644 index 0000000..995c364 --- /dev/null +++ b/Bookshop/BookshopView/FormGenres.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Microsoft.Extensions.Logging; +using BookshopContracts.BindingModels; +using BookshopContracts.BusinessLogicsContracts; +using BookshopContracts.SearchModels; + +namespace BookshopView +{ + public partial class FormGenres : Form + { + + private readonly ILogger _logger; + private readonly IGenreLogic _logic; + public FormGenres(ILogger logger, IGenreLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + private void FormGenres_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["GenreName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка компонентов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormGenre)); + if (service is FormGenre form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = + Program.ServiceProvider?.GetService(typeof(FormGenre)); + if (service is FormGenre form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление компонента"); + try + { + if (!_logic.Delete(new GenreBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/Bookshop/BookshopView/FormGenres.resx b/Bookshop/BookshopView/FormGenres.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/Bookshop/BookshopView/FormGenres.resx @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Bookshop/BookshopView/Form1.Designer.cs b/Bookshop/BookshopView/FormMain.Designer.cs similarity index 76% rename from Bookshop/BookshopView/Form1.Designer.cs rename to Bookshop/BookshopView/FormMain.Designer.cs index 09cf346..8e29d0b 100644 --- a/Bookshop/BookshopView/Form1.Designer.cs +++ b/Bookshop/BookshopView/FormMain.Designer.cs @@ -1,14 +1,14 @@ namespace BookshopView { - partial class Form1 + partial class FormMain { /// - /// Required designer variable. + /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// - /// Clean up any resources being used. + /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) @@ -23,15 +23,15 @@ #region Windows Form Designer generated code /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); - this.Text = "Form1"; + this.Text = "FormMain"; } #endregion diff --git a/Bookshop/BookshopView/FormMain.cs b/Bookshop/BookshopView/FormMain.cs new file mode 100644 index 0000000..299120f --- /dev/null +++ b/Bookshop/BookshopView/FormMain.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BookshopView +{ + public partial class FormMain : Form + { + public FormMain() + { + InitializeComponent(); + } + } +} diff --git a/Bookshop/BookshopView/FormMain.resx b/Bookshop/BookshopView/FormMain.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Bookshop/BookshopView/FormMain.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/Bookshop/BookshopView/Program.cs b/Bookshop/BookshopView/Program.cs index 16a6864..dd0613c 100644 --- a/Bookshop/BookshopView/Program.cs +++ b/Bookshop/BookshopView/Program.cs @@ -1,7 +1,18 @@ +using BookshopBusinessLogic.BusinessLogics; +using BookshopContracts.BusinessLogicsContracts; +using BookshopContracts.StorageContracts; +using BookshopDatabaseImplement.Implemets; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; +using System; + namespace BookshopView { internal static class Program { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; /// /// The main entry point for the application. /// @@ -11,7 +22,32 @@ namespace BookshopView // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); + var services = new ServiceCollection(); + ConfigureServices(services); + _serviceProvider = services.BuildServiceProvider(); + Application.Run(_serviceProvider.GetRequiredService()); + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file