diff --git a/BlogDataModels/BlogContracts/BindingModel/CommentBindingModel.cs b/BlogDataModels/BlogContracts/BindingModel/CommentBindingModel.cs index 0981a5d..807f638 100644 --- a/BlogDataModels/BlogContracts/BindingModel/CommentBindingModel.cs +++ b/BlogDataModels/BlogContracts/BindingModel/CommentBindingModel.cs @@ -11,7 +11,7 @@ namespace BlogContracts.BindingModel { public string Text { get; set; } = string.Empty; - public int NewId { get; set; } + public int NewsId { get; set; } public int Id { get; set; } } diff --git a/BlogDataModels/BlogContracts/BindingModel/NewsBindingModel.cs b/BlogDataModels/BlogContracts/BindingModel/NewsBindingModel.cs index ef75e48..f828036 100644 --- a/BlogDataModels/BlogContracts/BindingModel/NewsBindingModel.cs +++ b/BlogDataModels/BlogContracts/BindingModel/NewsBindingModel.cs @@ -11,10 +11,12 @@ namespace BlogContracts.BindingModel { public string Title { get; set; } = string.Empty; - public string Author { get; set; } = string.Empty; + public int UserId { get; set; } public int Id { get; set; } public string Text { get; set; } = string.Empty; + + public Dictionary NewsTag { get; set; } = new(); } } diff --git a/BlogDataModels/BlogContracts/BindingModel/TagBindingModel.cs b/BlogDataModels/BlogContracts/BindingModel/TagBindingModel.cs index ab59023..ca67c94 100644 --- a/BlogDataModels/BlogContracts/BindingModel/TagBindingModel.cs +++ b/BlogDataModels/BlogContracts/BindingModel/TagBindingModel.cs @@ -10,7 +10,7 @@ namespace BlogContracts.BindingModel { public class TagBindingModel : ITag { - public int NewId { get; set; } + public int NewsId { get; set; } public int Id { get; set; } diff --git a/BlogDataModels/BlogContracts/BindingModel/UserBindingModel.cs b/BlogDataModels/BlogContracts/BindingModel/UserBindingModel.cs index b9c1461..235ae10 100644 --- a/BlogDataModels/BlogContracts/BindingModel/UserBindingModel.cs +++ b/BlogDataModels/BlogContracts/BindingModel/UserBindingModel.cs @@ -11,7 +11,7 @@ namespace BlogContracts.BindingModel { public string Name { get; set; } = string.Empty; - public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); + public string DateCreate { get; set; } = string.Empty; public int Id { get; set; } } diff --git a/BlogDataModels/BlogContracts/BlogContracts.csproj b/BlogDataModels/BlogContracts/BlogContracts.csproj index e01c399..d209a2c 100644 --- a/BlogDataModels/BlogContracts/BlogContracts.csproj +++ b/BlogDataModels/BlogContracts/BlogContracts.csproj @@ -6,6 +6,13 @@ enable + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/BlogDataModels/BlogContracts/SearchModels/CommentSearchModel.cs b/BlogDataModels/BlogContracts/SearchModels/CommentSearchModel.cs index 5584e7a..3e4f03c 100644 --- a/BlogDataModels/BlogContracts/SearchModels/CommentSearchModel.cs +++ b/BlogDataModels/BlogContracts/SearchModels/CommentSearchModel.cs @@ -9,7 +9,7 @@ namespace BlogContracts.SearchModels public class CommentSearchModel { public int? Id { get; set; } - public int? NewId { get; set; } + public int? NewsId { get; set; } public string? Text { get; set; } } } diff --git a/BlogDataModels/BlogContracts/SearchModels/NewsSearchModel.cs b/BlogDataModels/BlogContracts/SearchModels/NewsSearchModel.cs index 1c42858..99439ec 100644 --- a/BlogDataModels/BlogContracts/SearchModels/NewsSearchModel.cs +++ b/BlogDataModels/BlogContracts/SearchModels/NewsSearchModel.cs @@ -10,8 +10,7 @@ namespace BlogContracts.SearchModels { public int? Id { get; set; } public string? Title { get; set; } - public string? Author { get; set; } - + public int? UserId { get; set; } } } diff --git a/BlogDataModels/BlogContracts/ViewModels/CommentViewModel.cs b/BlogDataModels/BlogContracts/ViewModels/CommentViewModel.cs index fd4ba90..6ad9910 100644 --- a/BlogDataModels/BlogContracts/ViewModels/CommentViewModel.cs +++ b/BlogDataModels/BlogContracts/ViewModels/CommentViewModel.cs @@ -14,7 +14,7 @@ namespace BlogContracts.ViewModels public int Id { get; set; } [DisplayName("Текст комментария")] public string Text { get; set; } = string.Empty; - public int NewId { get; set; } + public int NewsId { get; set; } } } diff --git a/BlogDataModels/BlogContracts/ViewModels/NewsViewModel.cs b/BlogDataModels/BlogContracts/ViewModels/NewsViewModel.cs index 6ec5f09..0f6420f 100644 --- a/BlogDataModels/BlogContracts/ViewModels/NewsViewModel.cs +++ b/BlogDataModels/BlogContracts/ViewModels/NewsViewModel.cs @@ -13,10 +13,12 @@ namespace BlogContracts.ViewModels [DisplayName("Название")] public string Title { get; set; } = string.Empty; [DisplayName("Автор")] - public string Author { get; set; } = string.Empty; + public int UserId { get; set; } [DisplayName("Номер")] public int Id { get; set; } [DisplayName("Текст")] public string Text { get; set; } = string.Empty; + + public Dictionary NewsTag { get; set; } = new(); } } diff --git a/BlogDataModels/BlogContracts/ViewModels/TagViewModel.cs b/BlogDataModels/BlogContracts/ViewModels/TagViewModel.cs index 40c9dca..a37673d 100644 --- a/BlogDataModels/BlogContracts/ViewModels/TagViewModel.cs +++ b/BlogDataModels/BlogContracts/ViewModels/TagViewModel.cs @@ -13,7 +13,7 @@ namespace BlogContracts.ViewModels [DisplayName("Номер")] public int Id { get; set; } [DisplayName("Номер новости")] - public int NewId { get; set; } + public int NewsId { get; set; } [DisplayName("Название")] public string Name { get; set; } = string.Empty; } diff --git a/BlogDataModels/BlogContracts/ViewModels/UserViewModel.cs b/BlogDataModels/BlogContracts/ViewModels/UserViewModel.cs index f2b6303..958aed5 100644 --- a/BlogDataModels/BlogContracts/ViewModels/UserViewModel.cs +++ b/BlogDataModels/BlogContracts/ViewModels/UserViewModel.cs @@ -15,7 +15,7 @@ namespace BlogContracts.ViewModels [DisplayName("Имя пользователя")] public string Name { get; set; } = string.Empty; [DisplayName("Дата регистрации")] - public DateTime DateCreate { get; set; } = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); - + public String DateCreate { get; set; } = string.Empty; + } } diff --git a/BlogDataModels/BlogDataModels.sln b/BlogDataModels/BlogDataModels.sln index cf7ccf1..943b759 100644 --- a/BlogDataModels/BlogDataModels.sln +++ b/BlogDataModels/BlogDataModels.sln @@ -5,7 +5,13 @@ VisualStudioVersion = 17.3.32901.215 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlogDataModels", "BlogDataModels\BlogDataModels.csproj", "{1031D282-ADC7-45D1-B177-B249AF60741F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlogContracts", "BlogContracts\BlogContracts.csproj", "{52620CAE-C105-47B1-8F07-456DB17E87B1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlogContracts", "BlogContracts\BlogContracts.csproj", "{52620CAE-C105-47B1-8F07-456DB17E87B1}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BusinessLogic", "BusinessLogic\BusinessLogic.csproj", "{7A56C58F-F558-48D7-92A1-07D02E3B2387}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlogDatabaseImplement", "BlogDatabaseImplement\BlogDatabaseImplement.csproj", "{EFBA4215-0B0B-4302-9465-89C723F9D975}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlogViewModel", "BlogViewModel\BlogViewModel.csproj", "{584E2CE9-1804-4A16-AA82-EED3F84531AC}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -21,6 +27,18 @@ Global {52620CAE-C105-47B1-8F07-456DB17E87B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {52620CAE-C105-47B1-8F07-456DB17E87B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {52620CAE-C105-47B1-8F07-456DB17E87B1}.Release|Any CPU.Build.0 = Release|Any CPU + {7A56C58F-F558-48D7-92A1-07D02E3B2387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7A56C58F-F558-48D7-92A1-07D02E3B2387}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7A56C58F-F558-48D7-92A1-07D02E3B2387}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7A56C58F-F558-48D7-92A1-07D02E3B2387}.Release|Any CPU.Build.0 = Release|Any CPU + {EFBA4215-0B0B-4302-9465-89C723F9D975}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EFBA4215-0B0B-4302-9465-89C723F9D975}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EFBA4215-0B0B-4302-9465-89C723F9D975}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EFBA4215-0B0B-4302-9465-89C723F9D975}.Release|Any CPU.Build.0 = Release|Any CPU + {584E2CE9-1804-4A16-AA82-EED3F84531AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {584E2CE9-1804-4A16-AA82-EED3F84531AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {584E2CE9-1804-4A16-AA82-EED3F84531AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {584E2CE9-1804-4A16-AA82-EED3F84531AC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/BlogDataModels/BlogDataModels/BlogDataModels.csproj b/BlogDataModels/BlogDataModels/BlogDataModels.csproj index 132c02c..a21058a 100644 --- a/BlogDataModels/BlogDataModels/BlogDataModels.csproj +++ b/BlogDataModels/BlogDataModels/BlogDataModels.csproj @@ -6,4 +6,11 @@ enable + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/BlogDataModels/BlogDataModels/Model/IComment.cs b/BlogDataModels/BlogDataModels/Model/IComment.cs index ff29241..11a5b5c 100644 --- a/BlogDataModels/BlogDataModels/Model/IComment.cs +++ b/BlogDataModels/BlogDataModels/Model/IComment.cs @@ -9,6 +9,6 @@ namespace BlogDataModels.Model public interface IComment : IId { string Text { get; } - int NewId { get; } + int NewsId { get; } } } diff --git a/BlogDataModels/BlogDataModels/Model/INews.cs b/BlogDataModels/BlogDataModels/Model/INews.cs index 26afbf1..f01ade3 100644 --- a/BlogDataModels/BlogDataModels/Model/INews.cs +++ b/BlogDataModels/BlogDataModels/Model/INews.cs @@ -10,6 +10,7 @@ namespace BlogDataModels.Model { string Title { get; } string Text { get; } - string Author { get; } + int UserId { get; } + Dictionary NewsTag { get; } } } diff --git a/BlogDataModels/BlogDataModels/Model/ITag.cs b/BlogDataModels/BlogDataModels/Model/ITag.cs index 827286f..35683f5 100644 --- a/BlogDataModels/BlogDataModels/Model/ITag.cs +++ b/BlogDataModels/BlogDataModels/Model/ITag.cs @@ -9,6 +9,6 @@ namespace BlogDataModels.Model public interface ITag : IId { string Name { get;} - int NewId { get;} + int NewsId { get;} } } diff --git a/BlogDataModels/BlogDataModels/Model/IUser.cs b/BlogDataModels/BlogDataModels/Model/IUser.cs index 19e8b49..e9eb4ec 100644 --- a/BlogDataModels/BlogDataModels/Model/IUser.cs +++ b/BlogDataModels/BlogDataModels/Model/IUser.cs @@ -9,6 +9,6 @@ namespace BlogDataModels.Model public interface IUser : IId { string Name { get;} - DateTime DateCreate { get;} + string DateCreate { get;} } } diff --git a/BlogDataModels/BlogDatabaseImplement/BlogDatabase.cs b/BlogDataModels/BlogDatabaseImplement/BlogDatabase.cs new file mode 100644 index 0000000..e048a7f --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/BlogDatabase.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using BlogDatabaseImplement.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel; + +namespace BlogDatabaseImplement +{ + public class BlogDatabase : DbContext + { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (optionsBuilder.IsConfigured == false) + { + optionsBuilder.UseNpgsql(@" + Host=localhost; + Port=5432; + Database=BlogDB; + Username=postgres; + Password=postgres"); + } + + base.OnConfiguring(optionsBuilder); + } + public virtual DbSet Tags { set; get; } + public virtual DbSet Users { set; get; } + public virtual DbSet News { set; get; } + public virtual DbSet Comments { set; get; } + public virtual DbSet NewsTags { set; get; } + + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/BlogDatabaseImplement.csproj b/BlogDataModels/BlogDatabaseImplement/BlogDatabaseImplement.csproj new file mode 100644 index 0000000..e180eaf --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/BlogDatabaseImplement.csproj @@ -0,0 +1,27 @@ + + + + net6.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/BlogDataModels/BlogDatabaseImplement/Implements/CommentStorage.cs b/BlogDataModels/BlogDatabaseImplement/Implements/CommentStorage.cs new file mode 100644 index 0000000..c48d443 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Implements/CommentStorage.cs @@ -0,0 +1,89 @@ +using BlogContracts.BindingModel; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using BlogDatabaseImplement.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Implements +{ + public class CommentStorage : ICommentStorage + { + public List GetFullList() + { + using var context = new BlogDatabase(); + return context.Comments + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(CommentSearchModel model) + { + if (string.IsNullOrEmpty(model.Text)) + { + return new(); + } + using var context = new BlogDatabase(); + return context.Comments + .Where(x => x.Text.Contains(model.Text)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public CommentViewModel? GetElement(CommentSearchModel model) + { + if (string.IsNullOrEmpty(model.Text) && !model.Id.HasValue) + { + return null; + } + using var context = new BlogDatabase(); + return context.Comments + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Text) && x.Text == model.Text) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + public CommentViewModel? Insert(CommentBindingModel model) + { + var newComment = Comment.Create(model); + if (newComment == null) + { + return null; + } + using var context = new BlogDatabase(); + context.Comments.Add(newComment); + context.SaveChanges(); + return newComment.GetViewModel; + } + + public CommentViewModel? Update(CommentBindingModel model) + { + using var context = new BlogDatabase(); + var component = context.Comments.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + + public CommentViewModel? Delete(CommentBindingModel model) + { + using var context = new BlogDatabase(); + var element = context.Comments.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Comments.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Implements/NewsStorage.cs b/BlogDataModels/BlogDatabaseImplement/Implements/NewsStorage.cs new file mode 100644 index 0000000..3c5e977 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Implements/NewsStorage.cs @@ -0,0 +1,106 @@ +using BlogContracts.BindingModel; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using BlogDatabaseImplement.Model; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Implements +{ + public class NewsStorage : INewsStorage + { + public NewsViewModel? Delete(NewsBindingModel model) + { + using var context = new BlogDatabase(); + var element = context.News.FirstOrDefault(rec => rec.Id == + model.Id); + + if (element != null) + { + context.News.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + + } + + public NewsViewModel? GetElement(NewsSearchModel model) + { + if (string.IsNullOrEmpty(model.Title) && + !model.Id.HasValue) + { + return null; + } + using var context = new BlogDatabase(); + return context.News + .Include(x => x.Tags) + .ThenInclude(x => x.Tag) + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Title) && + x.Title == model.Title) || + (model.Id.HasValue && x.Id == + model.Id)) + ?.GetViewModel; + } + + public List GetFilteredList(NewsSearchModel model) + { + if (string.IsNullOrEmpty(model.Title)) + { + return new(); + } + using var context = new BlogDatabase(); + return context.News + .Include(x => x.Tags) + .ThenInclude(x => x.Tag) + .Where(x => x.Title.Contains(model.Title)) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFullList() + { + using var context = new BlogDatabase(); + return context.News + .Include(x => x.User) + .Include(x => x.Tags) + .ThenInclude(x => x.Tag) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + public NewsViewModel? Insert(NewsBindingModel model) + { + using var context = new BlogDatabase(); + var newNews = News.Create(context, model); + if (newNews == null) + { + return null; + } + context.News.Add(newNews); + context.SaveChanges(); + return newNews.GetViewModel; + } + + public NewsViewModel? Update(NewsBindingModel model) + { + using var context = new BlogDatabase(); + var element = context.News + .FirstOrDefault(x => x.Id == model.Id); + if (element == null) + { + return null; + } + element.Update(model); + context.SaveChanges(); + return element.GetViewModel; + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Implements/TagStorage.cs b/BlogDataModels/BlogDatabaseImplement/Implements/TagStorage.cs new file mode 100644 index 0000000..b201db2 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Implements/TagStorage.cs @@ -0,0 +1,96 @@ +using BlogContracts.BindingModel; +using BlogContracts.SearchModels; +using BlogContracts.ViewModels; +using BlogDatabaseImplement.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Implements +{ + public class TagStorage + { + public List GetFullList() + { + using var context = new BlogDatabase(); + return context.Tags.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(TagSearchModel model) + { + using var context = new BlogDatabase(); + if (model.Id.HasValue) + { + return context.Tags + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + else if (model.Name != null) + { + return context.Tags + .Where(x => x.Name == model.Name) + .Select(x => x.GetViewModel) + .ToList(); + } + else + { + return new(); + } + } + + public TagViewModel? GetElement(TagSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new BlogDatabase(); + return context.Tags + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) + || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public TagViewModel? Insert(TagBindingModel model) + { + var newTag = Tag.Create(model); + if (newTag == null) + { + return null; + } + using var context = new BlogDatabase(); + context.Tags.Add(newTag); + context.SaveChanges(); + return newTag.GetViewModel; + } + + public TagViewModel? Update(TagBindingModel model) + { + using var context = new BlogDatabase(); + var Tag = context.Tags.FirstOrDefault(x => x.Id == model.Id); + if (Tag == null) + { + return null; + } + Tag.Update(model); + context.SaveChanges(); + return Tag.GetViewModel; + } + + public TagViewModel? Delete(TagBindingModel model) + { + using var context = new BlogDatabase(); + var element = context.Tags.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Tags.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Implements/UserStorage.cs b/BlogDataModels/BlogDatabaseImplement/Implements/UserStorage.cs new file mode 100644 index 0000000..c825689 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Implements/UserStorage.cs @@ -0,0 +1,89 @@ +using BlogContracts.BindingModel; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using BlogDatabaseImplement.Model; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Implements +{ + public class UserStorage : IUserStorage + { + public List GetFullList() + { + using var context = new BlogDatabase(); + return context.Users + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(UserSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new BlogDatabase(); + return context.Users + .Where(x => x.Name.Contains(model.Name)) + .Select(x => x.GetViewModel) + .ToList(); + } + + public UserViewModel? GetElement(UserSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new BlogDatabase(); + return context.Users + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + public UserViewModel? Insert(UserBindingModel model) + { + var newUser = User.Create(model); + if (newUser == null) + { + return null; + } + using var context = new BlogDatabase(); + context.Users.Add(newUser); + context.SaveChanges(); + return newUser.GetViewModel; + } + + public UserViewModel? Update(UserBindingModel model) + { + using var context = new BlogDatabase(); + var component = context.Users.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + context.SaveChanges(); + return component.GetViewModel; + } + + public UserViewModel? Delete(UserBindingModel model) + { + using var context = new BlogDatabase(); + var element = context.Users.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Users.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.Designer.cs b/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.Designer.cs new file mode 100644 index 0000000..e6d87d3 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.Designer.cs @@ -0,0 +1,197 @@ +// +using BlogDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BlogDatabaseImplement.Migrations +{ + [DbContext(typeof(BlogDatabase))] + [Migration("20230518164254_Start")] + partial class Start + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NewsId"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("News"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.NewsTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.Property("TagId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("NewsId"); + + b.HasIndex("TagId"); + + b.ToTable("NewsTags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Tags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateCreate") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Comment", b => + { + b.HasOne("BlogDatabaseImplement.Model.News", "News") + .WithMany("Comments") + .HasForeignKey("NewsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("News"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.HasOne("BlogDatabaseImplement.Model.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.NewsTag", b => + { + b.HasOne("BlogDatabaseImplement.Model.News", "News") + .WithMany("Tags") + .HasForeignKey("NewsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BlogDatabaseImplement.Model.Tag", "Tag") + .WithMany("News") + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("News"); + + b.Navigation("Tag"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.Navigation("Comments"); + + b.Navigation("Tags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Tag", b => + { + b.Navigation("News"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.cs b/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.cs new file mode 100644 index 0000000..fc4c6d7 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Migrations/20230518164254_Start.cs @@ -0,0 +1,150 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BlogDatabaseImplement.Migrations +{ + /// + public partial class Start : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Tags", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + NewsId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Tags", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + DateCreate = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "News", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Title = table.Column(type: "text", nullable: false), + Text = table.Column(type: "text", nullable: false), + UserId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_News", x => x.Id); + table.ForeignKey( + name: "FK_News_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Comments", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Text = table.Column(type: "text", nullable: false), + NewsId = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Comments", x => x.Id); + table.ForeignKey( + name: "FK_Comments_News_NewsId", + column: x => x.NewsId, + principalTable: "News", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "NewsTags", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + NewsId = table.Column(type: "integer", nullable: false), + TagId = table.Column(type: "integer", nullable: false), + Count = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_NewsTags", x => x.Id); + table.ForeignKey( + name: "FK_NewsTags_News_NewsId", + column: x => x.NewsId, + principalTable: "News", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_NewsTags_Tags_TagId", + column: x => x.TagId, + principalTable: "Tags", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Comments_NewsId", + table: "Comments", + column: "NewsId"); + + migrationBuilder.CreateIndex( + name: "IX_News_UserId", + table: "News", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_NewsTags_NewsId", + table: "NewsTags", + column: "NewsId"); + + migrationBuilder.CreateIndex( + name: "IX_NewsTags_TagId", + table: "NewsTags", + column: "TagId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Comments"); + + migrationBuilder.DropTable( + name: "NewsTags"); + + migrationBuilder.DropTable( + name: "News"); + + migrationBuilder.DropTable( + name: "Tags"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Migrations/BlogDatabaseModelSnapshot.cs b/BlogDataModels/BlogDatabaseImplement/Migrations/BlogDatabaseModelSnapshot.cs new file mode 100644 index 0000000..975f13e --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Migrations/BlogDatabaseModelSnapshot.cs @@ -0,0 +1,194 @@ +// +using BlogDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BlogDatabaseImplement.Migrations +{ + [DbContext(typeof(BlogDatabase))] + partial class BlogDatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.5") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Comment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NewsId"); + + b.ToTable("Comments"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("News"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.NewsTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.Property("TagId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("NewsId"); + + b.HasIndex("TagId"); + + b.ToTable("NewsTags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("NewsId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Tags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateCreate") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Comment", b => + { + b.HasOne("BlogDatabaseImplement.Model.News", "News") + .WithMany("Comments") + .HasForeignKey("NewsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("News"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.HasOne("BlogDatabaseImplement.Model.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.NewsTag", b => + { + b.HasOne("BlogDatabaseImplement.Model.News", "News") + .WithMany("Tags") + .HasForeignKey("NewsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BlogDatabaseImplement.Model.Tag", "Tag") + .WithMany("News") + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("News"); + + b.Navigation("Tag"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.News", b => + { + b.Navigation("Comments"); + + b.Navigation("Tags"); + }); + + modelBuilder.Entity("BlogDatabaseImplement.Model.Tag", b => + { + b.Navigation("News"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Model/Comment.cs b/BlogDataModels/BlogDatabaseImplement/Model/Comment.cs new file mode 100644 index 0000000..3f42bfd --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Model/Comment.cs @@ -0,0 +1,54 @@ +using BlogContracts.BindingModel; +using BlogContracts.ViewModels; +using BlogDataModels.Model; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Model +{ + public class Comment : IComment + { + [Required] + public string Text { get; set; } = string.Empty; + [Required] + public int NewsId { get; set; } + [Required] + public int Id { get; set; } + public virtual News News { get; set; } + public static Comment? Create(CommentBindingModel model) + { + if (model == null) + { + return null; + } + return new Comment() + { + Id = model.Id, + Text = model.Text, + NewsId = model.NewsId, + }; + } + + public void Update(CommentBindingModel model) + { + if (model == null) + { + return; + } + Text = model.Text; + NewsId = model.NewsId; + } + + public CommentViewModel GetViewModel => new() + { + Id = Id, + Text = Text, + NewsId = NewsId + }; + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Model/News.cs b/BlogDataModels/BlogDatabaseImplement/Model/News.cs new file mode 100644 index 0000000..2380db7 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Model/News.cs @@ -0,0 +1,109 @@ +using BlogDataModels.Model; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.ComponentModel.DataAnnotations.Schema; +using BlogContracts.BindingModel; + +namespace BlogDatabaseImplement.Model +{ + public class News : INews + { + public string Title { get; set; } = string.Empty; + + public string Text { get; set; } = string.Empty; + + public int UserId { get; set; } + + public int Id { get; set; } + public virtual User User { get; set; } + + private Dictionary? _NewsTag = null; + [NotMapped] + public Dictionary NewsTag + { + get + { + if (_NewsTag == null) + { + _NewsTag = Tags.ToDictionary(recPC => recPC.TagId, recPC => (recPC.Tag as ITag, recPC.Count)); + + } + return _NewsTag; + + } + } + [ForeignKey("NewsId")] + public virtual List Tags { get; set; } = new(); + + [ForeignKey("NewsId")] + public virtual List Comments { get; set; } = new(); + + + public static News Create(BlogDatabase context, NewsBindingModel model) + { + var news = new News() + { + Id = model.Id, + Title = model.Title, + Text = model.Text, + UserId = model.UserId + }; + + news.Tags = model.NewsTag.Select(x => new NewsTag + { + Tag = context.Tags.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList(); + + return news; + } + + + public void Update(NewsBindingModel model) + { + Title = model.Title; + Text = model.Text; + UserId = model.UserId; + } + public BlogContracts.ViewModels.NewsViewModel GetViewModel => new() + { + Id = Id, + Title = Title, + Text = Text, + UserId = UserId + }; + + public void UpdateTags(BlogDatabase context, NewsBindingModel model) + { + var NewsTags = context.NewsTags.Where(rec => rec.NewsId == model.Id).ToList(); + if (NewsTags != null && NewsTags.Count > 0) + { // удалили те, которых нет в модели + context.NewsTags.RemoveRange(NewsTags.Where(rec => !model.NewsTag.ContainsKey(rec.TagId))); + context.SaveChanges(); + // обновили количество у существующих записей + foreach (var updateTag in NewsTags) + { + updateTag.Count = model.NewsTag[updateTag.TagId].Item2; + model.NewsTag.Remove(updateTag.TagId); + } + context.SaveChanges(); + } + var News = context.News.First(x => x.Id == Id); + foreach (var pc in model.NewsTag) + { + context.NewsTags.Add(new NewsTag + { + News = News, + Tag = context.Tags.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _NewsTag = null; + } + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Model/NewsTag.cs b/BlogDataModels/BlogDatabaseImplement/Model/NewsTag.cs new file mode 100644 index 0000000..c5c3fb9 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Model/NewsTag.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Model +{ + public class NewsTag + { + public int Id { get; set; } + [Required] + public int NewsId { get; set; } + + [Required] + public int TagId { get; set; } + + public virtual News News{ get; set; } = new(); + [Required] + public int Count { get; set; } + public virtual Tag Tag { get; set; } = new(); + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Model/Tag.cs b/BlogDataModels/BlogDatabaseImplement/Model/Tag.cs new file mode 100644 index 0000000..56fdfe0 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Model/Tag.cs @@ -0,0 +1,68 @@ +using BlogContracts.BindingModel; +using BlogContracts.ViewModels; +using BlogDataModels.Model; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BlogDatabaseImplement.Model +{ + public class Tag : ITag + { + [Required] + public string Name { get; set; } = string.Empty; + [Required] + public int NewsId { get; set; } + [Required] + public int Id { get; set; } + + [ForeignKey("TagId")] + public virtual List News { get; set; } = new(); + + public static Tag? Create(TagBindingModel model) + { + if (model == null) + { + return null; + } + return new Tag() + { + Id = model.Id, + Name = model.Name, + NewsId = model.NewsId, + + }; + } + + public static Tag Create(TagViewModel model) + { + return new Tag + { + Id = model.Id, + Name = model.Name, + NewsId = model.NewsId, + }; + } + + public void Update(TagBindingModel model) + { + if (model == null) + { + return; + } + Name = model.Name; + NewsId = model.NewsId; + } + + public TagViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + NewsId = NewsId + }; + } +} diff --git a/BlogDataModels/BlogDatabaseImplement/Model/User.cs b/BlogDataModels/BlogDatabaseImplement/Model/User.cs new file mode 100644 index 0000000..b0de901 --- /dev/null +++ b/BlogDataModels/BlogDatabaseImplement/Model/User.cs @@ -0,0 +1,58 @@ +using BlogContracts.BindingModel; +using BlogContracts.ViewModels; +using BlogDataModels.Model; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace BlogDatabaseImplement.Model +{ + public class User : IUser + { + [Required] + public string Name { get; set; } = string.Empty; + + public string DateCreate { get; set; } = string.Empty; + [Required] + public int Id { get; set; } + + [ForeignKey("UserId")] + List News { get; set; } = new(); + + public static User? Create(UserBindingModel model) + { + if (model == null) + { + return null; + } + return new User() + { + Id = model.Id, + Name = model.Name, + DateCreate = model.DateCreate + }; + } + + public void Update(UserBindingModel model) + { + if (model == null) + { + return; + } + Name = model.Name; + DateCreate = model.DateCreate; + } + + public UserViewModel GetViewModel => new() + { + Id = Id, + Name = Name, + DateCreate = DateCreate + }; + } +} diff --git a/BlogDataModels/BlogViewModel/BlogViewModel.csproj b/BlogDataModels/BlogViewModel/BlogViewModel.csproj new file mode 100644 index 0000000..2d239b4 --- /dev/null +++ b/BlogDataModels/BlogViewModel/BlogViewModel.csproj @@ -0,0 +1,26 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + \ No newline at end of file diff --git a/BlogDataModels/BlogViewModel/FormMain.Designer.cs b/BlogDataModels/BlogViewModel/FormMain.Designer.cs new file mode 100644 index 0000000..f7e5180 --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormMain.Designer.cs @@ -0,0 +1,126 @@ +namespace BlogViewModel +{ + partial class FormMain + { + /// + /// 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.dataGridView = new System.Windows.Forms.DataGridView(); + this.MenuStrip = new System.Windows.Forms.MenuStrip(); + this.пользователиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.тегиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.комментарииРаботыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.новостиToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.MenuStrip.SuspendLayout(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.BackgroundColor = System.Drawing.SystemColors.Control; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 43); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(1108, 467); + this.dataGridView.TabIndex = 2; + // + // MenuStrip + // + this.MenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); + this.MenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.пользователиToolStripMenuItem, + this.тегиToolStripMenuItem, + this.комментарииРаботыToolStripMenuItem, + this.новостиToolStripMenuItem1, + this.письмаToolStripMenuItem}); + this.MenuStrip.Location = new System.Drawing.Point(0, 0); + this.MenuStrip.Name = "MenuStrip"; + this.MenuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3); + this.MenuStrip.Size = new System.Drawing.Size(1132, 30); + this.MenuStrip.TabIndex = 3; + this.MenuStrip.Text = "menuStrip1"; + // + // пользователиToolStripMenuItem + // + this.пользователиToolStripMenuItem.Name = "пользователиToolStripMenuItem"; + this.пользователиToolStripMenuItem.Size = new System.Drawing.Size(121, 24); + this.пользователиToolStripMenuItem.Text = "Пользователь"; + this.пользователиToolStripMenuItem.Click += new System.EventHandler(this.пользователиToolStripMenuItem_Click); + // + // тегиToolStripMenuItem + // + this.тегиToolStripMenuItem.Name = "тегиToolStripMenuItem"; + this.тегиToolStripMenuItem.Size = new System.Drawing.Size(54, 24); + this.тегиToolStripMenuItem.Text = "Теги"; + // + // комментарииРаботыToolStripMenuItem + // + this.комментарииРаботыToolStripMenuItem.Name = "комментарииРаботыToolStripMenuItem"; + this.комментарииРаботыToolStripMenuItem.Size = new System.Drawing.Size(121, 24); + this.комментарииРаботыToolStripMenuItem.Text = "Комментарии"; + // + // новостиToolStripMenuItem1 + // + this.новостиToolStripMenuItem1.Name = "новостиToolStripMenuItem1"; + this.новостиToolStripMenuItem1.Size = new System.Drawing.Size(82, 24); + this.новостиToolStripMenuItem1.Text = "Новости"; + // + // письмаToolStripMenuItem + // + this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem"; + this.письмаToolStripMenuItem.Size = new System.Drawing.Size(14, 24); + // + // FormMain + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1132, 522); + this.Controls.Add(this.MenuStrip); + this.Controls.Add(this.dataGridView); + this.Name = "FormMain"; + this.Text = "FormMain"; + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.MenuStrip.ResumeLayout(false); + this.MenuStrip.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private DataGridView dataGridView; + private MenuStrip MenuStrip; + private ToolStripMenuItem пользователиToolStripMenuItem; + private ToolStripMenuItem тегиToolStripMenuItem; + private ToolStripMenuItem комментарииРаботыToolStripMenuItem; + private ToolStripMenuItem новостиToolStripMenuItem1; + private ToolStripMenuItem письмаToolStripMenuItem; + } +} \ No newline at end of file diff --git a/BlogDataModels/BlogViewModel/FormMain.cs b/BlogDataModels/BlogViewModel/FormMain.cs new file mode 100644 index 0000000..a520e7d --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormMain.cs @@ -0,0 +1,30 @@ +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 BlogViewModel +{ + public partial class FormMain : Form + { + public FormMain() + { + InitializeComponent(); + } + + private void пользователиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormUsers)); + + if (service is FormUsers form) + { + form.ShowDialog(); + } + } + } +} diff --git a/BlogDataModels/BlogViewModel/FormMain.resx b/BlogDataModels/BlogViewModel/FormMain.resx new file mode 100644 index 0000000..a694815 --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormMain.resx @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + + \ No newline at end of file diff --git a/BlogDataModels/BlogViewModel/FormUser.Designer.cs b/BlogDataModels/BlogViewModel/FormUser.Designer.cs new file mode 100644 index 0000000..b7ec7de --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUser.Designer.cs @@ -0,0 +1,123 @@ +namespace BlogViewModel +{ + partial class FormUser + { + /// + /// 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.UserNameLabel = new System.Windows.Forms.Label(); + this.UserNameTextBox = new System.Windows.Forms.TextBox(); + this.DateCreateLabel = new System.Windows.Forms.Label(); + this.DateCreateTextBox = new System.Windows.Forms.TextBox(); + this.SaveButton = new System.Windows.Forms.Button(); + this.ButtonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // UserNameLabel + // + this.UserNameLabel.AutoSize = true; + this.UserNameLabel.Location = new System.Drawing.Point(73, 20); + this.UserNameLabel.Name = "UserNameLabel"; + this.UserNameLabel.Size = new System.Drawing.Size(84, 20); + this.UserNameLabel.TabIndex = 0; + this.UserNameLabel.Text = "Название: "; + // + // UserNameTextBox + // + this.UserNameTextBox.Location = new System.Drawing.Point(163, 17); + this.UserNameTextBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.UserNameTextBox.Name = "UserNameTextBox"; + this.UserNameTextBox.Size = new System.Drawing.Size(238, 27); + this.UserNameTextBox.TabIndex = 2; + // + // DateCreateLabel + // + this.DateCreateLabel.AutoSize = true; + this.DateCreateLabel.Location = new System.Drawing.Point(46, 72); + this.DateCreateLabel.Name = "DateCreateLabel"; + this.DateCreateLabel.Size = new System.Drawing.Size(121, 20); + this.DateCreateLabel.TabIndex = 3; + this.DateCreateLabel.Text = "Дата создания: "; + // + // DateCreateTextBox + // + this.DateCreateTextBox.Location = new System.Drawing.Point(163, 72); + this.DateCreateTextBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.DateCreateTextBox.Name = "DateCreateTextBox"; + this.DateCreateTextBox.Size = new System.Drawing.Size(238, 27); + this.DateCreateTextBox.TabIndex = 4; + // + // SaveButton + // + this.SaveButton.Location = new System.Drawing.Point(223, 120); + this.SaveButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.SaveButton.Name = "SaveButton"; + this.SaveButton.Size = new System.Drawing.Size(86, 31); + this.SaveButton.TabIndex = 5; + this.SaveButton.Text = "Сохранить"; + this.SaveButton.UseVisualStyleBackColor = true; + this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); + // + // ButtonCancel + // + this.ButtonCancel.Location = new System.Drawing.Point(315, 120); + this.ButtonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ButtonCancel.Name = "ButtonCancel"; + this.ButtonCancel.Size = new System.Drawing.Size(86, 31); + this.ButtonCancel.TabIndex = 6; + this.ButtonCancel.Text = "Отмена"; + this.ButtonCancel.UseVisualStyleBackColor = true; + this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // FormUser + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(413, 164); + this.Controls.Add(this.ButtonCancel); + this.Controls.Add(this.SaveButton); + this.Controls.Add(this.DateCreateTextBox); + this.Controls.Add(this.DateCreateLabel); + this.Controls.Add(this.UserNameTextBox); + this.Controls.Add(this.UserNameLabel); + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.Name = "FormUser"; + this.Text = "Пользователь"; + this.Load += new System.EventHandler(this.FormUser_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private Label UserNameLabel; + private TextBox UserNameTextBox; + private Label DateCreateLabel; + private TextBox DateCreateTextBox; + private Button SaveButton; + private Button ButtonCancel; + } +} \ No newline at end of file diff --git a/BlogDataModels/BlogViewModel/FormUser.cs b/BlogDataModels/BlogViewModel/FormUser.cs new file mode 100644 index 0000000..4911725 --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUser.cs @@ -0,0 +1,102 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.SearchModels; +using BlogContracts.BindingModel; + +namespace BlogViewModel +{ + public partial class FormUser : Form + { + private readonly ILogger _logger; + private readonly IUserLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + + public FormUser(ILogger logger, IUserLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormUser_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + try + { + _logger.LogInformation("Получение компонента"); + + var view = _logic.ReadElement(new UserSearchModel + { + Id = _id.Value + }); + + if (view != null) + { + UserNameTextBox.Text = view.Name; + DateCreateTextBox.Text = view.DateCreate; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка получения компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(UserNameTextBox.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _logger.LogInformation("Сохранение компонента"); + + try + { + var model = new UserBindingModel + { + Id = _id ?? 0, + Name = UserNameTextBox.Text, + DateCreate = DateCreateTextBox.Text, + //Cost = Convert.ToDouble(CostTextBox.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/BlogDataModels/BlogViewModel/FormUser.resx b/BlogDataModels/BlogViewModel/FormUser.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUser.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/BlogDataModels/BlogViewModel/FormUsers.Designer.cs b/BlogDataModels/BlogViewModel/FormUsers.Designer.cs new file mode 100644 index 0000000..ca7944b --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUsers.Designer.cs @@ -0,0 +1,128 @@ +namespace BlogViewModel +{ + partial class FormUsers + { + /// + /// 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 InitializeUser() + { + this.DataGridView = new System.Windows.Forms.DataGridView(); + this.AddButton = new System.Windows.Forms.Button(); + this.ChangeButton = new System.Windows.Forms.Button(); + this.DeleteButton = new System.Windows.Forms.Button(); + this.UpdateButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).BeginInit(); + this.SuspendLayout(); + // + // DataGridView + // + this.DataGridView.AllowUserToAddRows = false; + this.DataGridView.AllowUserToDeleteRows = false; + this.DataGridView.AllowUserToResizeColumns = false; + this.DataGridView.BackgroundColor = System.Drawing.SystemColors.Control; + this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.DataGridView.Dock = System.Windows.Forms.DockStyle.Left; + this.DataGridView.Location = new System.Drawing.Point(0, 0); + this.DataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.DataGridView.Name = "DataGridView"; + this.DataGridView.ReadOnly = true; + this.DataGridView.RowHeadersVisible = false; + this.DataGridView.RowHeadersWidth = 51; + this.DataGridView.RowTemplate.Height = 25; + this.DataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.DataGridView.Size = new System.Drawing.Size(630, 736); + this.DataGridView.TabIndex = 0; + // + // AddButton + // + this.AddButton.Location = new System.Drawing.Point(653, 35); + this.AddButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.AddButton.Name = "AddButton"; + this.AddButton.Size = new System.Drawing.Size(162, 60); + this.AddButton.TabIndex = 1; + this.AddButton.Text = "Добавить"; + this.AddButton.UseVisualStyleBackColor = true; + this.AddButton.Click += new System.EventHandler(this.AddButton_Click); + // + // ChangeButton + // + this.ChangeButton.Location = new System.Drawing.Point(653, 124); + this.ChangeButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.ChangeButton.Name = "ChangeButton"; + this.ChangeButton.Size = new System.Drawing.Size(162, 60); + this.ChangeButton.TabIndex = 2; + this.ChangeButton.Text = "Изменить"; + this.ChangeButton.UseVisualStyleBackColor = true; + this.ChangeButton.Click += new System.EventHandler(this.ChangeButton_Click); + // + // DeleteButton + // + this.DeleteButton.Location = new System.Drawing.Point(653, 216); + this.DeleteButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.DeleteButton.Name = "DeleteButton"; + this.DeleteButton.Size = new System.Drawing.Size(162, 60); + this.DeleteButton.TabIndex = 3; + this.DeleteButton.Text = "Удалить"; + this.DeleteButton.UseVisualStyleBackColor = true; + this.DeleteButton.Click += new System.EventHandler(this.DeleteButton_Click); + // + // UpdateButton + // + this.UpdateButton.Location = new System.Drawing.Point(653, 307); + this.UpdateButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.UpdateButton.Name = "UpdateButton"; + this.UpdateButton.Size = new System.Drawing.Size(162, 60); + this.UpdateButton.TabIndex = 4; + this.UpdateButton.Text = "Обновить"; + this.UpdateButton.UseVisualStyleBackColor = true; + this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click); + // + // FormUsers + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(829, 736); + this.Controls.Add(this.UpdateButton); + this.Controls.Add(this.DeleteButton); + this.Controls.Add(this.ChangeButton); + this.Controls.Add(this.AddButton); + this.Controls.Add(this.DataGridView); + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.Name = "FormUsers"; + this.Text = "Компоненты"; + this.Load += new System.EventHandler(this.FormUsers_Load); + ((System.ComponentModel.ISupportInitialize)(this.DataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + private DataGridView DataGridView; + private Button AddButton; + private Button ChangeButton; + private Button DeleteButton; + private Button UpdateButton; + } +} \ No newline at end of file diff --git a/BlogDataModels/BlogViewModel/FormUsers.cs b/BlogDataModels/BlogViewModel/FormUsers.cs new file mode 100644 index 0000000..8710c45 --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUsers.cs @@ -0,0 +1,119 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.BindingModel; + +namespace BlogViewModel +{ + public partial class FormUsers : Form + { + private readonly ILogger _logger; + private readonly IUserLogic _logic; + + public FormUsers(ILogger logger, IUserLogic logic) + { + InitializeUser(); + _logger = logger; + _logic = logic; + } + + private void FormUsers_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["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + DataGridView.Columns["DateCreate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + + _logger.LogInformation("Загрузка компонентов"); + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки компонентов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void AddButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormUser)); + + if (service is FormUser form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + private void ChangeButton_Click(object sender, EventArgs e) + { + if (DataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormUser)); + + if (service is FormUser form) + { + form.Id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value); + + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + private void DeleteButton_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 UserBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления компонента"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + private void UpdateButton_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/BlogDataModels/BlogViewModel/FormUsers.resx b/BlogDataModels/BlogViewModel/FormUsers.resx new file mode 100644 index 0000000..f298a7b --- /dev/null +++ b/BlogDataModels/BlogViewModel/FormUsers.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/BlogDataModels/BlogViewModel/Program.cs b/BlogDataModels/BlogViewModel/Program.cs new file mode 100644 index 0000000..4ce553c --- /dev/null +++ b/BlogDataModels/BlogViewModel/Program.cs @@ -0,0 +1,51 @@ +using BlogContracts.BusinessLogicContracts; +using BlogContracts.StorageContracts; +using BlogDatabaseImplement.Implements; +using BlogDatabaseImplement.Model; +using BlogDataModels.Model; +using BusinessLogic; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + +namespace BlogViewModel +{ + internal static class Program + { + private static ServiceProvider? _serviceProvider; + public static ServiceProvider? ServiceProvider => _serviceProvider; + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + 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(); + + } + } +} \ No newline at end of file diff --git a/BlogDataModels/BusinessLogic/BusinessLogic.csproj b/BlogDataModels/BusinessLogic/BusinessLogic.csproj new file mode 100644 index 0000000..5874de7 --- /dev/null +++ b/BlogDataModels/BusinessLogic/BusinessLogic.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/BlogDataModels/BusinessLogic/CommentLogic.cs b/BlogDataModels/BusinessLogic/CommentLogic.cs new file mode 100644 index 0000000..b71e879 --- /dev/null +++ b/BlogDataModels/BusinessLogic/CommentLogic.cs @@ -0,0 +1,95 @@ +using BlogContracts.BindingModel; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class CommentLogic : ICommentLogic + { + private readonly ICommentStorage _commentStorage; + public CommentLogic(ICommentStorage CommentStorage) + { + _commentStorage = CommentStorage ?? throw new ArgumentNullException(nameof(CommentStorage)); + } + + public bool Create(CommentBindingModel model) + { + CheckModel(model); + if (_commentStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Delete(CommentBindingModel model) + { + CheckModel(model); + if (_commentStorage.Delete(model) == null) + { + return false; + } + return true; + } + + public CommentViewModel? ReadElement(CommentSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _commentStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public List? ReadList(CommentSearchModel? model) + { + var list = model == null ? _commentStorage.GetFullList() : _commentStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public bool Update(CommentBindingModel model) + { + CheckModel(model); + if (_commentStorage.Update(model) == null) + { + return false; + } + return true; + } + private void CheckModel(CommentBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (string.IsNullOrEmpty(model.Text)) + { + throw new ArgumentException("Отсутвует текст", + nameof(model.Text)); + } + if (_commentStorage.GetElement(new CommentSearchModel + { + Text = model.Text, + }) != null) + { + throw new InvalidOperationException("Такой тег уже существует"); + } + } + } +} diff --git a/BlogDataModels/BusinessLogic/NewsLogic.cs b/BlogDataModels/BusinessLogic/NewsLogic.cs new file mode 100644 index 0000000..17fdb74 --- /dev/null +++ b/BlogDataModels/BusinessLogic/NewsLogic.cs @@ -0,0 +1,107 @@ +using BlogContracts.BindingModel; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class NewsLogic : INewsLogic + { + private readonly INewsStorage _newsStorage; + public NewsLogic(INewsStorage newsStorage) + { + _newsStorage = newsStorage ?? throw new ArgumentNullException(nameof(newsStorage)); + } + + public bool Create(NewsBindingModel model) + { + CheckModel(model); + if (_newsStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Delete(NewsBindingModel model) + { + CheckModel(model); + if (_newsStorage.Delete(model) == null) + { + return false; + } + return true; + } + + public NewsViewModel? ReadElement(NewsSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _newsStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public List? ReadList(NewsSearchModel? model) + { + var list = model == null ? _newsStorage.GetFullList() : _newsStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public bool Update(NewsBindingModel model) + { + CheckModel(model); + if (_newsStorage.Update(model) == null) + { + return false; + } + return true; + } + private void CheckModel(NewsBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (string.IsNullOrEmpty(model.Title)) + { + throw new ArgumentException("Отсутвует название", + nameof(model.Title)); + } + if (string.IsNullOrEmpty(model.Text)) + { + throw new ArgumentException("Отсутвует текст", + nameof(model.Text)); + } + if (string.IsNullOrEmpty(model.UserId.ToString())) + { + throw new ArgumentException("Отсутвует автор", + nameof(model.UserId)); + } + if (_newsStorage.GetElement(new NewsSearchModel + { + Title = model.Title, + UserId = model.UserId, + + }) != null) + { + throw new InvalidOperationException("Такая новость уже существует"); + } + } + } +} diff --git a/BlogDataModels/BusinessLogic/TagLogic.cs b/BlogDataModels/BusinessLogic/TagLogic.cs new file mode 100644 index 0000000..e66d325 --- /dev/null +++ b/BlogDataModels/BusinessLogic/TagLogic.cs @@ -0,0 +1,95 @@ +using BlogContracts.BindingModel; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class TagLogic : ITagLogic + { + private readonly ITagStorage _tagStorage; + public TagLogic(ITagStorage TagStorage) + { + _tagStorage = TagStorage ?? throw new ArgumentNullException(nameof(TagStorage)); + } + + public bool Create(TagBindingModel model) + { + CheckModel(model); + if (_tagStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Delete(TagBindingModel model) + { + CheckModel(model); + if (_tagStorage.Delete(model) == null) + { + return false; + } + return true; + } + + public TagViewModel? ReadElement(TagSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _tagStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public List? ReadList(TagSearchModel? model) + { + var list = model == null ? _tagStorage.GetFullList() : _tagStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public bool Update(TagBindingModel model) + { + CheckModel(model); + if (_tagStorage.Update(model) == null) + { + return false; + } + return true; + } + private void CheckModel(TagBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentException("Отсутвует название тега", + nameof(model.Name)); + } + if (_tagStorage.GetElement(new TagSearchModel + { + Name = model.Name, + }) != null) + { + throw new InvalidOperationException("Такой тег уже существует"); + } + } + } +} diff --git a/BlogDataModels/BusinessLogic/UserLogic.cs b/BlogDataModels/BusinessLogic/UserLogic.cs new file mode 100644 index 0000000..f5a74cc --- /dev/null +++ b/BlogDataModels/BusinessLogic/UserLogic.cs @@ -0,0 +1,100 @@ +using BlogContracts.BindingModel; +using BlogContracts.BusinessLogicContracts; +using BlogContracts.SearchModels; +using BlogContracts.StorageContracts; +using BlogContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic +{ + public class UserLogic : IUserLogic + { + private readonly IUserStorage _userStorage; + public UserLogic(IUserStorage UserStorage) + { + _userStorage = UserStorage ?? throw new ArgumentNullException(nameof(UserStorage)); + } + + public bool Create(UserBindingModel model) + { + CheckModel(model); + if (_userStorage.Insert(model) == null) + { + return false; + } + return true; + } + + public bool Delete(UserBindingModel model) + { + CheckModel(model); + if (_userStorage.Delete(model) == null) + { + return false; + } + return true; + } + + public UserViewModel? ReadElement(UserSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + var element = _userStorage.GetElement(model); + if (element == null) + { + return null; + } + return element; + } + + public List? ReadList(UserSearchModel? model) + { + var list = model == null ? _userStorage.GetFullList() : _userStorage.GetFilteredList(model); + if (list == null) + { + return null; + } + return list; + } + + public bool Update(UserBindingModel model) + { + CheckModel(model); + if (_userStorage.Update(model) == null) + { + return false; + } + return true; + } + private void CheckModel(UserBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentException("Отсутвует имя", + nameof(model.Name)); + } + if (string.IsNullOrEmpty(model.DateCreate)) + { + throw new ArgumentException("Отсутвует дата создания аккаунта", + nameof(model.DateCreate)); + } + if (_userStorage.GetElement(new UserSearchModel + { + Name = model.Name, + }) != null) + { + throw new InvalidOperationException("Такой пользователь уже существует"); + } + } + } +}