public void Delete_Topic_Deleted_If_Topic_Starter()
        {
            var postRepository = Substitute.For<IPostRepository>();
            var topicRepository = Substitute.For<ITopicRepository>();
            var roleService = Substitute.For<IRoleService>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();
            var localisationService = Substitute.For<ILocalizationService>();
            var postService = new PostService(membershipUserPointsService, settingsService, roleService, postRepository, topicRepository, localisationService, _api);

            var tags = new List<TopicTag>
                           {
                               new TopicTag{Tag = "Thor"},
                               new TopicTag{Tag = "Gambit"}
                           };
            var topic = new Topic { Name = "Captain America", Tags = tags };
            var post = new Post { Id = Guid.NewGuid(), Topic = topic, IsTopicStarter = true};
            topic.LastPost = post;
            topic.Posts = new List<Post>();
            post.IsTopicStarter = true;
            topic.Posts.Add(post);

            // Save
            var deleteTopic = postService.Delete(post);

            Assert.IsTrue(deleteTopic);
        }
        public void Delete_Post_Removed_From_TopicList_And_Last_Post()
        {
            var postRepository = Substitute.For<IPostRepository>();
            var topicRepository = Substitute.For<ITopicRepository>();
            var roleService = Substitute.For<IRoleService>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();
            var localisationService = Substitute.For<ILocalizationService>();
            var postService = new PostService(membershipUserPointsService, settingsService, roleService, postRepository, topicRepository, localisationService, _api);
            
            // Create topic
            var topic = new Topic { Name = "Captain America"};

            // Create some posts with one to delete
            var postToDelete = new Post { Id = Guid.NewGuid(), Topic = topic, IsTopicStarter = false, DateCreated = DateTime.UtcNow};
            var postToStay = new Post { Id = Guid.NewGuid(), Topic = topic, IsTopicStarter = false, DateCreated = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)) };
            var postToStayTwo = new Post { Id = Guid.NewGuid(), Topic = topic, IsTopicStarter = false, DateCreated = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)) };

            // set last post
            topic.LastPost = postToDelete;

            // Set the post list to the topic
            var posts = new List<Post> {postToDelete, postToStay, postToStayTwo};
            topic.Posts = posts;

            // Save
            postService.Delete(postToDelete);

            // Test that settings is no longer in cache
            Assert.IsTrue(topic.LastPost == postToStay);
            Assert.IsTrue(topic.Posts.Count == 2);         
        }
Exemple #3
0
 /// <summary>
 /// Create a new post
 /// </summary>
 /// <param name="post"></param>
 /// <returns></returns>
 public Post Create(Post post)
 {
     post.IsSolution = false;
     post.DateCreated = DateTime.UtcNow;
     post.DateEdited = DateTime.UtcNow;
     _postRepository.Add(post);
     return post;
 }
Exemple #4
0
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
                               {
                                   PostContent = postContent,
                                   User = user,
                                   Topic = topic,
                                   IpAddress = StringUtils.GetUsersIpAddress(),
                                   DateCreated = DateTime.UtcNow,
                                   DateEdited = DateTime.UtcNow
                               };

            newPost = SanitizePost(newPost);

            var category = topic.Category;
            if (category.ModeratePosts == true)
            {
                newPost.Pending = true;
            }

            var e = new PostMadeEventArgs { Post = newPost};
            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                                                     {
                                                         Points = _settingsService.GetSettings().PointsAddedPerPost,
                                                         User = user
                                                     });

                // add the last post to the topic
                topic.LastPost = newPost;

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost});

                return newPost;
            }

            return newPost;
        }
Exemple #5
0
        public Post SanitizePost(Post post)
        {
            post.PostContent = StringUtils.GetSafeHtml(post.PostContent);

            // Check settings
            if (_settingsService.GetSettings().EnableEmoticons == true)
            {
                post.PostContent = EmoticonUtils.Emotify(post.PostContent);   
            }

            return post;
        }
Exemple #6
0
 /// <summary>
 /// Map a post to the Lucene Model
 /// </summary>
 /// <param name="post"></param>
 /// <returns></returns>
 public LuceneSearchModel MapToModel(Post post)
 {
     var model = new LuceneSearchModel
         {
             Id = post.Id,
             PostContent = post.PostContent,
             DateCreated = post.DateCreated,
             TopicId = post.Topic.Id,
             TopicUrl = post.Topic.NiceUrl,
             Username = post.User.UserName,
             UserId = post.User.Id
         };
     if(post.IsTopicStarter)
     {
         model.TopicName = post.Topic.Name;
     }
     return model;
 }
Exemple #7
0
 /// <summary>
 /// Map a post to the Lucene Model
 /// </summary>
 /// <param name="post"></param>
 /// <returns></returns>
 public LuceneSearchModel MapToModel(Post post)
 {
     var model = new LuceneSearchModel
         {
             Id = post.Id,
             PostContent = post.PostContent,
             DateCreated = post.DateCreated,
             TopicId = post.Topic.Id,
             TopicUrl = post.Topic.NiceUrl,
             TopicTags = post.Topic.Tags.Aggregate("", (current, tag) => current + " " + tag.Tag),
             Username = post.User.UserName,
             UserId = post.User.Id
         };
     if(post.IsTopicStarter)
     {
         model.TopicName = post.Topic.Name;
     }
     return model;
 }
        /// <summary>
        /// Check whether a post is spam or not
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public bool IsSpam(Post post)
        {
            // If akisment is is not enable always return false
            if (_settingsService.GetSettings().EnableAkisment == null || _settingsService.GetSettings().EnableAkisment == false) return false;

            // Akisment must be enabled
            var comment = new Comment
            {
                blog = StringUtils.CheckLinkHasHttp(_settingsService.GetSettings().ForumUrl),
                comment_type = "comment",
                comment_author = post.User.UserName,
                comment_author_email = post.User.Email,
                comment_content = post.PostContent,
                permalink = String.Empty,
                referrer = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"],
                user_agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"],
                user_ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
            };
            var validator = new Validator(_settingsService.GetSettings().AkismentKey);
            return validator.IsSpam(comment);
        }
Exemple #9
0
        /// <summary>
        /// Add a last post to a topic. Must be part of a separate database update
        /// in EF because of circular dependencies. So save the topic before calling this.
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="postContent"></param>
        /// <returns></returns>
        public Post AddLastPost(Topic topic, string postContent)
        {
            topic = SanitizeTopic(topic);

            // Create the post
            var post = new Post
            {
                DateCreated = DateTime.UtcNow,
                IsTopicStarter = true,
                DateEdited = DateTime.UtcNow,
                PostContent = StringUtils.GetSafeHtml(postContent),
                User = topic.User,
                Topic = topic
            };

            // Add the post
            _postRepository.Add(post);

            topic.LastPost = post;

            return post;
        }
Exemple #10
0
        public static PostViewModel CreatePostViewModel(Post post, List<Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List<Favourite> favourites)
        {
            var allowedToVote = (loggedOnUser != null && loggedOnUser.Id != post.User.Id &&
                                 loggedOnUser.TotalPoints > settings.PointsAllowedToVoteAmount &&
                                 votes.All(x => x.User.Id != loggedOnUser.Id));

            var hasFavourited = false;
            if (loggedOnUser != null && loggedOnUser.Id != post.User.Id)
            {
                hasFavourited = favourites.Any(x => x.Member.Id == loggedOnUser.Id);
            }

            return new PostViewModel
            {
                Permissions = permission,
                Votes = votes,
                Post = post,
                ParentTopic = topic,
                AllowedToVote = allowedToVote,
                MemberHasFavourited = hasFavourited,
                Favourites = favourites,
                PermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", post.Id)
            };
        }
        public static PostViewModel CreatePostViewModel(Post post, List<Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List<Favourite> favourites)
        {
            var allowedToVote = (loggedOnUser != null && loggedOnUser.Id != post.User.Id &&
                                 loggedOnUser.TotalPoints >= settings.PointsAllowedToVoteAmount);

            // Remove votes where no VotedBy has been recorded
            votes.RemoveAll(x => x.VotedByMembershipUser == null);

            var hasVotedUp = false;
            var hasVotedDown = false;
            var hasFavourited = false;
            if (loggedOnUser != null && loggedOnUser.Id != post.User.Id)
            {
                hasFavourited = favourites.Any(x => x.Member.Id == loggedOnUser.Id);
                hasVotedUp = votes.Count(x => x.Amount > 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
                hasVotedDown = votes.Count(x => x.Amount < 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
            }

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-AppConstants.TimeSpanInMinutesToShowMembers);

            return new PostViewModel
            {
                Permissions = permission,
                Votes = votes,
                Post = post,
                ParentTopic = topic,
                AllowedToVote = allowedToVote,
                MemberHasFavourited = hasFavourited,
                Favourites = favourites,
                PermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", post.Id),
                MemberIsOnline = post.User.LastActivityDate > date,
                HasVotedDown = hasVotedDown,
                HasVotedUp = hasVotedUp
            };
        }
Exemple #12
0
        public void AfterBadgeAwarded()
        {
            EventManager.Instance.AfterBadgeAwarded += _EventManagerInstance_AfterBadgeAwarded;
            var badgeRepository = Substitute.For<IBadgeRepository>();
            var api = Substitute.For<IMVCForumAPI>();
            var loggingService = Substitute.For<ILoggingService>();
            var localisationService = Substitute.For<ILocalizationService>();
            var badgeService = new BadgeService(badgeRepository, api, loggingService, localisationService, _activityService);
            badgeService.SyncBadges();

            // Create a user with one post with one vote
            var post = new Post
            {
                Id = Guid.NewGuid(),
                Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } },
            };

            var user = new MembershipUser
            {
                Posts = new List<Post> { post },
                Badges = new List<Badge>(),
                BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked>
                { new BadgeTypeTimeLastChecked
                    { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = BadgeServiceTests.GetTimeAllowsBadgeUpdate()} }
            };

            badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge { Name = "PosterVoteUp" });
            badgeService.ProcessBadge(BadgeType.VoteUp, user);

            Assert.IsTrue(user.Badges.Count == 1);
            Assert.IsTrue(user.Badges[0].Name == "PosterVoteUp" || user.Badges[0].Name == BadgeServiceTests.NameTestVoteUp);

            // Event has been called test
            Assert.IsTrue(user.Email == TestString);
            EventManager.Instance.AfterBadgeAwarded -= _EventManagerInstance_AfterBadgeAwarded;
        }
Exemple #13
0
 public void DeletePost(Post post)
 {
     _api.Post.Delete(post);
 }
 /// <summary>
 /// Create a new post
 /// </summary>
 /// <param name="post"></param>
 /// <returns></returns>
 public Post Add(Post post)
 {
     post = SanitizePost(post);
     return _postRepository.Add(post);
 }
 /// <summary>
 /// Save / Update a post
 /// </summary>
 /// <param name="post"></param>
 public void SaveOrUpdate(Post post)
 {
     _postRepository.Update(post);
 }
        /// <summary>
        /// Delete a post
        /// </summary>
        /// <param name="post"></param>
        /// <param name="isTopicDelete"></param>
        /// <returns> True if parent topic should now be deleted (caller's responsibility)</returns>
        public bool Delete(Post post, bool isTopicDelete = false)
        {
            #region Deleting Points

            // Remove the points the user got for this post
            _membershipUserPointsService.Delete(post.User, PointsFor.Post, post.Id);

            // Also get all the votes and delete anything to do with those
            foreach (var postVote in post.Votes)
            {
                _membershipUserPointsService.Delete(PointsFor.Vote, postVote.Id);
            }

            // Also the mark as solution
            _membershipUserPointsService.Delete(PointsFor.Solution, post.Id);

            // remove likes
            var postLikes = post.Votes.ToList();
            foreach (var like in postLikes)
            {
                _voteService.Delete(like);
            }

            // remove favorites
            var postFavorites = post.Favourites.ToList();
            foreach (var favorite in postFavorites)
            {
                _favouriteService.Delete(favorite);
            }

            // remove uploaded files
            var postUploads = post.Files.ToList();
            foreach (var postUploadedFile in postUploads)
            {
                _uploadedFileService.Delete(postUploadedFile);
            }

            #endregion

            // If this is coming from a call that is deleting the entire topic, then just delete post
            if (isTopicDelete)
            {
                // now delete the post
                _postRepository.Delete(post);
                return true;
            }

            // Before we delete the post, we need to check if this is the last post in the topic
            // and if so update the topic
            var topic = post.Topic;
            var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();

            if (lastPost != null && lastPost.Id == post.Id)
            {
                // Get the new last post and update the topic
                topic.LastPost = topic.Posts.Where(x => x.Id != post.Id).OrderByDescending(x => x.DateCreated).FirstOrDefault();
            }

            if (topic.Solved && post.IsSolution)
            {
                topic.Solved = false;
            }

            topic.Posts.Remove(post);

            var deleteTopic = post.IsTopicStarter;

            // now delete the post
            _postRepository.Delete(post);

            // Topic should be deleted, so make sure it has no last post to avoid circular dependency
            if (deleteTopic)
            {
                topic.LastPost = null;
            }

            return deleteTopic;
        }
        public void PosterVoteUpAwardBadge2()
        {
            _badgeRepository = Substitute.For<IBadgeRepository>();
            _badgeService = new BadgeService(_badgeRepository,  _api, _loggingService, _localizationService, _activityService);

            // Create a user with one post with two votes BUT user has no badge yet so will be awarded
            var post = new Post
            {
                Id = Guid.NewGuid(),
                Votes = new List<Vote>
                            {
                                new Vote { Id = Guid.NewGuid() },
                                new Vote { Id = Guid.NewGuid() }
                            },
            };

            var user = new MembershipUser
            {
                Posts = new List<Post> { post },
                Badges = new List<Badge>(),
                BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> 
                { new BadgeTypeTimeLastChecked 
                    { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = GetTimeAllowsBadgeUpdate()} }
            };

            _badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge { Name = "testbadge" });
            _badgeService.ProcessBadge(BadgeType.VoteUp, user);

            Assert.IsTrue(user.Badges.Count == 2);

        }
Exemple #18
0
        /// <summary>
        /// Add a last post to a topic. Must be part of a separate database update
        /// in EF because of circular dependencies. So save the topic before calling this.
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="postContent"></param>
        /// <returns></returns>
        public Post AddLastPost(Topic topic, string postContent)
        {

            topic = SanitizeTopic(topic);

            // Create the post
            var post = new Post
            {
                DateCreated = DateTime.UtcNow,
                IsTopicStarter = true,
                DateEdited = DateTime.UtcNow,
                PostContent = postContent,
                User = topic.User,
                Topic = topic
            };

            // Add the post
            _postService.Add(post);

            topic.LastPost = post;

            return post;
        }
 public void Update(Post item)
 {
     // Check there's not an object with same identifier already in context
     if (_context.Post.Local.Select(x => x.Id == item.Id).Any())
     {
         throw new ApplicationException("Object already exists in context - you do not need to call Update. Save occurs on Commit");
     }
     _context.Entry(item).State = EntityState.Modified;  
 }
Exemple #20
0
 public Post SanitizePost(Post post)
 {
     post.PostContent = StringUtils.GetSafeHtml(post.PostContent);
     return post;
 }
Exemple #21
0
        /// <summary>
        /// Delete a post
        /// </summary>
        /// <param name="post"></param>
        /// <returns> True if parent topic should now be deleted (caller's responsibility)</returns>
        public bool Delete(Post post)
        {
            // Here is where we can check for reasons not to delete the post
            // And change the value below if not
            var okToDelete = true;
            var deleteTopic = false;

            if (okToDelete)
            {
                // Before we delete the post, we need to check if this is the last post in the topic
                // and if so update the topic
                var topic = post.Topic;
                var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault();

                if (lastPost != null && lastPost.Id == post.Id)
                {
                    // Get the new last post and update the topic
                    topic.LastPost = topic.Posts.Where(x => x.Id != post.Id).OrderByDescending(x => x.DateCreated).FirstOrDefault();
                }

                if (topic.Solved && post.IsSolution)
                {
                    topic.Solved = false;
                }

                topic.Posts.Remove(post);

                deleteTopic = post.IsTopicStarter;

                // now delete the post
                _postRepository.Delete(post);

                // Topic should be deleted, so make sure it has no last post to avoid circular dependency
                if (deleteTopic)
                {
                    topic.LastPost = null;
                }
            }

            return deleteTopic;
        }
Exemple #22
0
        private void MarkPostUpOrDown(Post post, MembershipUser postWriter, MembershipUser voter, PostType postType)
        {
            // Check this user is not the post owner
            if (voter.Id != postWriter.Id)
            {
                // Not the same person, now check they haven't voted on this post before
                if (post.Votes.All(x => x.User.Id != LoggedOnUser.Id))
                {

                    // Points to add or subtract to a user
                    var usersPoints = (postType == PostType.Negative) ?
                                        (-SettingsService.GetSettings().PointsDeductedNagativeVote) : (SettingsService.GetSettings().PointsAddedPostiveVote);

                    // Update the users points who wrote the post
                    _membershipUserPointsService.Add(new MembershipUserPoints { Points = usersPoints, User = postWriter });

                    // Update the post with the new vote of the voter
                    var vote = new Vote
                    {
                        Post = post,
                        User = voter,
                        Amount = (postType == PostType.Negative) ? (-1) : (1),
                        VotedByMembershipUser = LoggedOnUser,
                        DateVoted = DateTime.UtcNow
                    };
                    _voteService.Add(vote);

                    // Update the post with the new points amount
                    var newPointTotal = (postType == PostType.Negative) ? (post.VoteCount - 1) : (post.VoteCount + 1);
                    post.VoteCount = newPointTotal;
                }
            }
        }
        public void SolveTopicMarkerNotOwner()
        {
            var topicRepository = Substitute.For<ITopicRepository>();
            var postRepository = Substitute.For<IPostRepository>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();

            var topicService = new TopicService(membershipUserPointsService, settingsService, topicRepository, postRepository, _api, _topicNotificationService);
            var marker = new MembershipUser
            {
                UserName = "******",
                Id = Guid.NewGuid()            
            };

            var owner = new MembershipUser
            {
                UserName = "******",
                Id = Guid.NewGuid()
            };

            var topic = new Topic
            {
                Name = "something",
                Tags = new List<TopicTag>
                                           {
                                               new TopicTag{Tag = "tagone"},
                                               new TopicTag{Tag = "tagtwo"}
                                           },
                User = owner
            };

            var post = new Post() { PostContent = "Test content" };

            var solutionWriter = new MembershipUser { UserName = "******" };

            topicService.SolveTopic(topic, post, marker, solutionWriter);

            Assert.IsFalse(topic.Solved);
        }
        public static TopicViewModel CreateTopicViewModel(Topic topic,
                                                    PermissionSet permission,
                                                    List<Post> posts,
                                                    Post starterPost,
                                                    int? pageIndex,
                                                    int? totalCount,
                                                    int? totalPages,
                                                    MembershipUser loggedOnUser,
                                                    Settings settings,
                                                    bool getExtendedData = false)
        {

            var topicNotificationService = ServiceFactory.Get<ITopicNotificationService>();
            var pollAnswerService = ServiceFactory.Get<IPollAnswerService>();
            var voteService = ServiceFactory.Get<IVoteService>();
            var favouriteService = ServiceFactory.Get<IFavouriteService>();

            var userIsAuthenticated = loggedOnUser != null;

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-AppConstants.TimeSpanInMinutesToShowMembers);

            var viewModel = new TopicViewModel
            {
                Permissions = permission,
                Topic = topic,
                Views = topic.Views,
                DisablePosting = loggedOnUser != null && (loggedOnUser.DisablePosting == true),
                PageIndex = pageIndex,
                TotalCount = totalCount,
                TotalPages = totalPages,
                LastPostPermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", topic.LastPost.Id),
                MemberIsOnline = topic.User.LastActivityDate > date,
            };
          
            if (starterPost == null)
            {
                starterPost = posts.FirstOrDefault(x => x.IsTopicStarter);
            }

            // Get votes for all posts
            var postIds = posts.Select(x => x.Id).ToList();
            postIds.Add(starterPost.Id);

            // Get all votes by post
            var votes = voteService.GetVotesByPosts(postIds);

            // Get all favourites for this user
            var allFavourites = favouriteService.GetByTopic(topic.Id);

            // Map the votes
            var startPostVotes = votes.Where(x => x.Post.Id == starterPost.Id).ToList();
            var startPostFavs = allFavourites.Where(x => x.Post.Id == starterPost.Id).ToList();

            // Create the starter post viewmodel
            viewModel.StarterPost = CreatePostViewModel(starterPost, startPostVotes, permission, topic, loggedOnUser, settings, startPostFavs);

            // Map data from the starter post viewmodel
            viewModel.VotesUp = startPostVotes.Count(x => x.Amount > 0);
            viewModel.VotesDown = startPostVotes.Count(x => x.Amount < 0);
            viewModel.Answers = totalCount != null ? (int)totalCount : posts.Count() - 1;

            // Create the ALL POSTS view models
            viewModel.Posts = CreatePostViewModels(posts, votes, permission, topic, loggedOnUser, settings, allFavourites);

            // ########### Full topic need everything   

            if (getExtendedData)
            {
                // See if the user has subscribed to this topic or not
                var isSubscribed = userIsAuthenticated && (topicNotificationService.GetByUserAndTopic(loggedOnUser, topic).Any());
                viewModel.IsSubscribed = isSubscribed;

                // See if the topic has a poll, and if so see if this user viewing has already voted
                if (topic.Poll != null)
                {
                    // There is a poll and a user
                    // see if the user has voted or not

                    viewModel.Poll = new PollViewModel
                    {
                        Poll = topic.Poll,
                        UserAllowedToVote = permission[SiteConstants.Instance.PermissionVoteInPolls].IsTicked
                    };

                    var answers = pollAnswerService.GetAllPollAnswersByPoll(topic.Poll);
                    if (answers.Any())
                    {
                        var pollvotes = answers.SelectMany(x => x.PollVotes).ToList();
                        if (userIsAuthenticated)
                        {
                            viewModel.Poll.UserHasAlreadyVoted = (pollvotes.Count(x => x.User.Id == loggedOnUser.Id) > 0);
                        }
                        viewModel.Poll.TotalVotesInPoll = pollvotes.Count();
                    }
                }
            }

            return viewModel;
        }
Exemple #25
0
        /// <summary>
        /// Mark a topic as solved
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="post"></param>
        /// <param name="marker"></param>
        /// <param name="solutionWriter"></param>
        /// <returns>True if topic has been marked as solved</returns>
        public bool SolveTopic(Topic topic, Post post, MembershipUser marker, MembershipUser solutionWriter)
        {
            var solved = false;

            var e = new MarkedAsSolutionEventArgs
                        {
                            Topic = topic,
                            Post = post,
                            Marker = marker,
                            SolutionWriter = solutionWriter
                        };
            EventManager.Instance.FireBeforeMarkedAsSolution(this, e);

            if (!e.Cancel)
            {
                // Make sure this user owns the topic, if not do nothing
                if (topic.User.Id == marker.Id)
                {
                    // Update the post
                    post.IsSolution = true;
                    //_postRepository.Update(post);

                    // Update the topic
                    topic.Solved = true;
                    //SaveOrUpdate(topic);

                    // Assign points
                    // Do not give points to the user if they are marking their own post as the solution
                    if (marker.Id != solutionWriter.Id)
                    {
                        _membershipUserPointsService.Add(new MembershipUserPoints
                                                             {
                                                                 Points = _settingsService.GetSettings().PointsAddedForSolution,
                                                                 User = solutionWriter
                                                             });
                    }

                    EventManager.Instance.FireAfterMarkedAsSolution(this, new MarkedAsSolutionEventArgs
                                                                              {
                                                                                  Topic = topic,
                                                                                  Post = post,
                                                                                  Marker = marker,
                                                                                  SolutionWriter = solutionWriter
                                                                              });
                    solved = true;
                }
            }

            return solved;
        }
        public void BeforeBadgeAwardedAllow()
        {
            EventManager.Instance.BeforeBadgeAwarded += _EventManagerInstance_BeforeBadgeAwardedAllow;
            var badgeRepository = Substitute.For<IBadgeRepository>();
            var api = Substitute.For<IMVCForumAPI>();
            var loggingService = Substitute.For<ILoggingService>();
            var localisationService = Substitute.For<ILocalizationService>();
            var badgeService = new BadgeService(badgeRepository, api, loggingService, localisationService, _activityService);
            badgeService.SyncBadges();

            // Create a user with one post with one vote
            var post = new Post
            {
                Id = Guid.NewGuid(),
                Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } },
            };

            var user = new MembershipUser
            {
                Posts = new List<Post> { post },
                Badges = new List<Badge>(),
                BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> 
                { new BadgeTypeTimeLastChecked 
                    { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = BadgeServiceTests.GetTimeAllowsBadgeUpdate()} }
            };

            badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge{Name="testbadge"});
            badgeService.ProcessBadge(BadgeType.VoteUp, user);

            // Event should have cancelled the update
            Assert.IsTrue(user.Badges.Count == 2);

            EventManager.Instance.BeforeBadgeAwarded -= _EventManagerInstance_BeforeBadgeAwardedAllow;
        }
        public void PosterVoteUpRefuseBadge_TooSoon()
        {
            _badgeRepository = Substitute.For<IBadgeRepository>();
            _badgeService = new BadgeService(_badgeRepository,  _api, _loggingService, _localizationService, _activityService);

            // Create a user with one post with one vote
            var post = new Post
            {
                Id = Guid.NewGuid(),
                Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } },
            };

            var user = new MembershipUser
            {
                Posts = new List<Post> { post },
                Badges = new List<Badge>(),
                BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> 
                { new BadgeTypeTimeLastChecked 
                    { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = GetTimeDisAllowsBadgeUpdate()} }
            };

            _badgeService.ProcessBadge(BadgeType.VoteUp, user);

            Assert.IsTrue(user.Badges.Count == 0);
        }
        public void BeforeMarkedAsSolutionCancel()
        {
            var topicRepository = Substitute.For<ITopicRepository>();
            var postRepository = Substitute.For<IPostRepository>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();

            var topicService = new TopicService(membershipUserPointsService, settingsService, topicRepository, postRepository, _api, _topicNotificationService);
            var marker = new MembershipUser
            {
                UserName = "******",
                Id = Guid.NewGuid()
            };

            var topic = new Topic
            {
                Name = "something",
                Tags = new List<TopicTag>
                                           {
                                               new TopicTag{Tag = "tagone"},
                                               new TopicTag{Tag = "tagtwo"}
                                           },
                User = marker
            };

            var post = new Post { PostContent = "Test content" };

            var solutionWriter = new MembershipUser { UserName = "******" };

            EventManager.Instance.BeforeMarkedAsSolution += eventsService_BeforeMarkedAsSolutionCancel;
            topicService.SolveTopic(topic, post, marker, solutionWriter);

            postRepository.DidNotReceive().Update(Arg.Is<Post>(x => x.PostContent == "Test content"));
            Assert.IsFalse(topic.Solved);
            EventManager.Instance.BeforeMarkedAsSolution -= eventsService_BeforeMarkedAsSolutionCancel;

        }
        public void VoteUpAwardTwoBadges()
        {
            _badgeRepository = Substitute.For<IBadgeRepository>();
            _badgeService = new BadgeService(_badgeRepository,  _api, _loggingService, _localizationService, _activityService);

            // Create a user with one post with one vote, and no badge, and one post with one vote
            var post = new Post
            {
                Id = Guid.NewGuid(),
                Votes = new List<Vote> { new Vote { Id = Guid.NewGuid() } },
            };

            var user = new MembershipUser
            {
                Posts = new List<Post> { post },
                Badges = new List<Badge>(),
                Votes = new List<Vote>
                            {
                                new Vote { Id = Guid.NewGuid() }
                            },
                BadgeTypesTimeLastChecked = new List<BadgeTypeTimeLastChecked> 
                { new BadgeTypeTimeLastChecked 
                    { BadgeType = BadgeType.VoteUp.ToString() , TimeLastChecked = GetTimeAllowsBadgeUpdate()} }
            };

            _badgeRepository.Get(Arg.Any<Guid>()).Returns(new Badge { Name = "testbadge" });

            _badgeService.ProcessBadge(BadgeType.VoteUp, user);

            Assert.IsTrue(user.Badges.Count == 3);

            // These tests can no longer work as we now fetch back the db badge records using a substitute
            //var foundPosterVoteUp = false;
            //var foundUserVoteUp = false;

            //foreach (var badge in user.Badges)
            //{
            //    if (badge.Name == "PosterVoteUp" || badge.Name == NameTestVoteUp)
            //    {
            //        foundPosterVoteUp = true;
            //    }
            //    else if (badge.Name == "UserVoteUp")
            //    {
            //        foundUserVoteUp = true;
            //    }
            //}
            //Assert.IsTrue(foundPosterVoteUp);
            //Assert.IsTrue(foundUserVoteUp);
        }
        public void AfterMarkedAsSolution()
        {
            var topicRepository = Substitute.For<ITopicRepository>();
            var postRepository = Substitute.For<IPostRepository>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();
            settingsService.GetSettings().Returns(new Settings{PointsAddedForSolution = 20});

            var topicService = new TopicService(membershipUserPointsService, settingsService, topicRepository, postRepository, _api, _topicNotificationService);
            var marker = new MembershipUser
            {
                UserName = "******",
                Id = Guid.NewGuid()
            };

            var topic = new Topic
            {
                Name = "something",
                Tags = new List<TopicTag>
                                           {
                                               new TopicTag{Tag = "tagone"},
                                               new TopicTag{Tag = "tagtwo"}
                                           },
                User = marker
            };

            var post = new Post { PostContent = "Test content" };

            var solutionWriter = new MembershipUser { UserName = "******" };

            EventManager.Instance.AfterMarkedAsSolution += eventsService_AfterMarkedAsSolution;
            topicService.SolveTopic(topic, post, marker, solutionWriter);

            Assert.IsTrue(topic.Solved);
            Assert.AreEqual(solutionWriter.Email, TestString);
            EventManager.Instance.AfterMarkedAsSolution -= eventsService_AfterMarkedAsSolution;
        }