Ejemplo n.º 1
0
        public async Task <IActionResult> Create(PostsVm posts, string[] TagPosts)
        {
            if (TagPosts != null)
            {
                posts.TagPosts = new List <TagPosts>();
                foreach (var tag in TagPosts)
                {
                    var tagToAdd = new TagPosts {
                        TagId = Convert.ToInt32(tag), PostId = posts.PostId
                    };
                    posts.TagPosts.Add(tagToAdd);
                }
            }

            if (ModelState.IsValid)
            {
                Posts    model = _mapper.Map <Posts>(posts);
                DateTime date  = DateTime.Now;
                model.DateCreated = date;
                _context.AddPost(model);
                _context.Commit();
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(_context.GetCategoryList(), "CategoryId", "Title", posts.CategoryId);
            ViewData["Tags"]       = new MultiSelectList(_context.GetTagList().AsEnumerable(), "TagId", "Title", posts.TagPosts.Select(e => e.TagId).AsEnumerable());
            return(View(posts));
        }
Ejemplo n.º 2
0
        public void DeleteTagPost(TagPosts tag)
        {
            if (tag == null)
            {
                throw new ArgumentNullException(nameof(tag));
            }

            _context.TagPosts.Remove(tag);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Edit(int id, PostsVm posts, string[] SelectedTags)
        {
            if (id != posts.PostId)
            {
                return(NotFound());
            }
            var model = _context.GetPost(id);


            if (SelectedTags != null)
            {
                var tags         = model.TagPosts;
                var remove_items = _context.GetTagPostList().Where(e => e.PostId == model.PostId);
                foreach (var tag in remove_items)
                {
                    _context.DeleteTagPost(tag);
                }

                _context.Commit();
                foreach (var tag in SelectedTags)
                {
                    var tagToAdd = new TagPosts {
                        TagId = Convert.ToInt32(tag), PostId = posts.PostId
                    };
                    model.TagPosts.Add(tagToAdd);
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    DateTime date = DateTime.Now;
                    model.DateCreated = date;
                    _context.UpdatePost(model);
                    _context.Commit();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PostsExists(posts.PostId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(_context.GetCategoryList(), "CategoryId", "Title", posts.CategoryId);
            ViewData["Tags"]       = new SelectList(_context.GetTagList(), "TagId", "Title");
            return(View(posts));
        }
Ejemplo n.º 4
0
 public object CommentsViewModel(int userId) => new
 {
     Id,
     Author     = Author?.ViewModel,
     Comments   = Comments.Select(c => c.ViewModel),
     LikesCount = Likes.Count,
     Tags       = TagPosts.Select(tp => tp.Tag.EmptyViewModel),
     Badges     = BadgePosts.Select(bp => bp.Badge),
     PublishDate,
     Title,
     Content,
     SavesCount = UserPosts.Count,
     Liked      = Likes.Any(l => l.UserId == userId),
     Saved      = UserPosts.Any(up => up.UserId == userId)
 };
        public static async void SeedData(this IServiceScopeFactory scopeFactory)
        {
            using (var serviceScope = scopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();

                var adminRole = new ApplicationRole
                {
                    Name        = "Administrator",
                    Description = "Website Administrator",
                    Created     = DateTime.Now
                };

                var userRole = new ApplicationRole
                {
                    Name        = "User",
                    Description = "User",
                    Created     = DateTime.Now
                };

                if (!context.Roles.Any())
                {
                    var roleStore = new RoleStore <ApplicationRole>(context);
                    var result    = roleStore.CreateAsync(adminRole);
                    var result2   = roleStore.CreateAsync(userRole);

                    context.SaveChanges();
                }

                if (!context.Users.Any())
                {
                    var adminUser = new ApplicationUser
                    {
                        Email                = "*****@*****.**",
                        NormalizedEmail      = "*****@*****.**",
                        UserName             = "******",
                        NormalizedUserName   = "******",
                        PhoneNumber          = "+61405054401",
                        EmailConfirmed       = true,
                        PhoneNumberConfirmed = true,
                        SecurityStamp        = Guid.NewGuid().ToString("D"),
                        Posts                = new List <Post>()
                    };

                    var standardUser = new ApplicationUser
                    {
                        Email                = "*****@*****.**",
                        NormalizedEmail      = "*****@*****.**",
                        UserName             = "******",
                        NormalizedUserName   = "******",
                        PhoneNumber          = "+61405054401",
                        EmailConfirmed       = true,
                        PhoneNumberConfirmed = true,
                        SecurityStamp        = Guid.NewGuid().ToString("D"),
                        Posts                = new List <Post>()
                    };

                    var userStore = new UserStore <ApplicationUser>(context);

                    if (!context.Users.Any(u => u.UserName == standardUser.UserName))
                    {
                        var passwordUser = new PasswordHasher <ApplicationUser>();
                        var hashedUser   = passwordUser.HashPassword(standardUser, "password");
                        standardUser.PasswordHash = hashedUser;

                        var resultStandard = userStore.CreateAsync(standardUser);
                        await userStore.AddToRoleAsync(standardUser, userRole.Name);

                        await context.SaveChangesAsync();
                    }
                    if (!context.Users.Any(u => u.UserName == adminUser.UserName))
                    {
                        var passwordAdmin = new PasswordHasher <ApplicationUser>();
                        var hashedAdmin   = passwordAdmin.HashPassword(adminUser, "secret");
                        adminUser.PasswordHash = hashedAdmin;

                        var resultAdmin = userStore.CreateAsync(adminUser);
                        await userStore.AddToRoleAsync(adminUser, adminRole.Name);

                        await context.SaveChangesAsync();
                    }
                }
                if (!context.Categories.Any())
                {
                    var categories = new List <Category>
                    {
                        new Category
                        {
                            Name        = "System Engineering",
                            Description = "System Engineering posts",
                            UrlSlug     = "SystemEngineering"
                        },
                        new Category
                        {
                            Name        = "Network Engineering",
                            Description = "Network Engineering posts",
                            UrlSlug     = "NetworkEngineering"
                        },
                        new Category
                        {
                            Name        = "Servers",
                            Description = "Servers",
                            UrlSlug     = "Servers"
                        },
                    };
                    context.AddRange(categories);
                    context.SaveChanges();
                }
                if (!context.Tags.Any())
                {
                    var tags = new List <Tag>
                    {
                        new Tag
                        {
                            Name        = "MVC",
                            Description = "Model View Controller",
                            UrlSlug     = "MVC"
                        },
                        new Tag
                        {
                            Name        = "Drones",
                            Description = "RC Drones",
                            UrlSlug     = "Drones"
                        },
                        new Tag
                        {
                            Name        = "asp.net",
                            Description = "Microsoft's ASP.Net",
                            UrlSlug     = "aspnet"
                        },
                        new Tag
                        {
                            Name        = "Exchange",
                            Description = "Microsoft Exchange",
                            UrlSlug     = "Exchange"
                        },
                        new Tag
                        {
                            Name        = "Outlook",
                            Description = "Microsoft Outlook",
                            UrlSlug     = "Outlook"
                        }
                    };
                    context.AddRange(tags);
                    context.SaveChanges();
                }
                if (!context.Posts.Any())
                {
                    var post1 = new Post
                    {
                        Title            = "My First Post",
                        Category         = context.Categories.First(c => c.Name == "System Engineering"),
                        published        = true,
                        Created          = DateTime.Now,
                        ShortDescription = "This is my first post",
                        UrlSlug          = "My-First-Post",
                        Owner            = context.Users.First(u => u.UserName == "*****@*****.**"),
                        HeaderImageUrl   = "",
                        Meta             = "",
                        SummaryImageUrl  = "http://placehold.it/300x250",
                        TagPosts         = new List <TagPosts>()
                    };

                    var post2 = new Post
                    {
                        Title            = "My second Post",
                        Category         = context.Categories.First(c => c.Name == "System Engineering"),
                        published        = true,
                        Created          = DateTime.Now,
                        ShortDescription = "This is my second post",
                        UrlSlug          = "My-second-Post",
                        Owner            = context.Users.First(u => u.UserName == "*****@*****.**"),
                        HeaderImageUrl   = "",
                        Meta             = "",
                        SummaryImageUrl  = "http://placehold.it/300x250",
                        TagPosts         = new List <TagPosts>()
                    };

                    context.SaveChanges();

                    // find the tags to add to the post
                    Tag tag1 = context.Tags.First(t => t.Name == "Outlook");
                    Tag tag2 = context.Tags.First(t => t.Name == "Exchange");

                    // create the mapping objects
                    var TagPosts = new TagPosts
                    {
                        Tag    = tag1,
                        Post   = post1,
                        TagId  = tag1.Id,
                        PostId = post1.Id
                    };

                    var TagPosts2 = new TagPosts
                    {
                        Tag    = tag2,
                        Post   = post1,
                        TagId  = tag2.Id,
                        PostId = post1.Id
                    };

                    // create the mapping objects
                    var TagPosts3 = new TagPosts
                    {
                        Tag    = tag1,
                        Post   = post2,
                        TagId  = tag1.Id,
                        PostId = post2.Id
                    };

                    var TagPosts4 = new TagPosts
                    {
                        Tag    = tag2,
                        Post   = post2,
                        TagId  = tag2.Id,
                        PostId = post2.Id
                    };

                    // add the tagposts to the post
                    post1.TagPosts.Add(TagPosts);
                    post1.TagPosts.Add(TagPosts2);
                    post2.TagPosts.Add(TagPosts3);
                    post2.TagPosts.Add(TagPosts4);
                    context.Add(post1);
                    context.Add(post2);

                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 6
0
        public async Task CreatePost(PostInputViewModel model)
        {
            var authorId = this.userRepo.All().SingleOrDefault(u => u.UserName == model.Author).Id;

            var content = model.FullContent.Trim();

            var title = model.Title.Trim();

            if (string.IsNullOrWhiteSpace(title))
            {
                throw new NullReferenceException("Title is required.");
            }

            var inputTags = model.Tags.Trim();

            if (string.IsNullOrWhiteSpace(inputTags))
            {
                throw new NullReferenceException("Tag is required.");
            }

            var dataTags = this.tagPostsRepo.All().AsNoTracking().Select(t => t.Tag.Name).ToList();

            var tags = model.Tags.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var tag in tags)
            {
                if (!dataTags.Any(t => t.Equals(tag, StringComparison.InvariantCultureIgnoreCase)))
                {
                    throw new InvalidOperationException($"Invalid tag {tag}");
                }
            }

            var post = new Post
            {
                AuthorId    = authorId,
                CreatedOn   = model.CreatedOn,
                FullContent = model.FullContent,
                Title       = model.Title,
            };

            if (postRepo.All().Any(p => p.Title == post.Title && p.IsDeleted == false))
            {
                throw new InvalidOperationException("Post with such title already exists.");
            }

            this.postRepo.Add(post);

            try
            {
                await this.postRepo.SaveChangesAsync();

                foreach (var tag in tags)
                {
                    var tagId = tagRepo.All().SingleOrDefault(t => t.Name == tag).Id;

                    var tagPosts = new TagPosts
                    {
                        TagId  = tagId,
                        PostId = post.Id
                    };

                    post.Tags.Add(tagPosts);
                }

                await this.postRepo.SaveChangesAsync();
            }
            catch (Exception e)
            {
                this.logger.LogDebug(e.Message);

                throw new InvalidOperationException("Sorry. An error occurred while creating a post.");
            }
        }