Example #1
0
        /// <summary>
        /// Merges the specified from vote into the specified to vote, assuming the votes aren't the same.
        /// Moves the voters from the from vote into the to vote list, and removes the 'from' vote's key.
        /// </summary>
        /// <param name="fromVote">Vote that is being merged.</param>
        /// <param name="toVote">Vote that is being merged into.</param>
        /// <param name="voteType">The type of vote being merged.</param>
        /// <returns>Returns true if there were any changes.</returns>
        public bool Merge(string fromVote, string toVote, VoteType voteType)
        {
            if (string.IsNullOrEmpty(fromVote))
            {
                throw new ArgumentNullException(nameof(fromVote));
            }
            if (string.IsNullOrEmpty(toVote))
            {
                throw new ArgumentNullException(nameof(toVote));
            }
            if (fromVote == toVote)
            {
                return(false);
            }

            bool merged = false;

            if (voteType == VoteType.Rank)
            {
                merged = MergeRanks(fromVote, toVote);
            }
            else
            {
                merged = MergeVotes(fromVote, toVote);
            }

            if (merged)
            {
                OnPropertyChanged("VoteCounter");
            }

            return(merged);
        }
Example #2
0
        /// <summary>
        /// Adds an individual vote.
        /// </summary>
        /// <param name="vote">The vote that is being added to.</param>
        /// <param name="voter">The voter that is supporting the vote.</param>
        /// <param name="voteType">Type of the vote.</param>
        /// <exception cref="System.ArgumentNullException">vote and voter must not be null or empty.</exception>
        private void AddVote(string vote, string voter, VoteType voteType)
        {
            if (string.IsNullOrEmpty(vote))
            {
                throw new ArgumentNullException(nameof(vote));
            }
            if (string.IsNullOrEmpty(voter))
            {
                throw new ArgumentNullException(nameof(voter));
            }

            string voteKey = GetVoteKey(vote, voteType);
            var    votes   = GetVotesCollection(voteType);

            // Make sure there's a hashset for the voter list available for the vote key.
            if (votes.ContainsKey(voteKey) == false)
            {
                votes[voteKey] = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                OnPropertyChanged("Votes");
            }

            string cleanVoter = VoteString.RemoveBBCode(voter);

            cleanVoter = VoteString.DeUrlContent(cleanVoter);

            // Update the supporters list if the voter isn't already in it.
            if (votes[voteKey].Contains(cleanVoter))
            {
                return;
            }

            votes[voteKey].Add(cleanVoter);

            OnPropertyChanged("Voters");
        }
Example #3
0
 public Vote(User user, VoteType type)
 {
     UserId      = user.Id;
     Username    = user.Username;
     DisplayName = string.Join(' ', user.FirstName, user.LastName);
     Type        = type;
 }
Example #4
0
        /// <summary>
        /// Vote on this item.
        /// </summary>
        /// <param name="type"></param>
        public async Task SetVoteAsync(VoteType type)
        {
            if (this.Vote == type)
            {
                return;
            }

            var data = await WebAgent.Post(VoteUrl, new
            {
                dir = (int)type,
                id  = FullName
            }).ConfigureAwait(false);

            if (Liked == true)
            {
                Upvotes--;
            }
            if (Liked == false)
            {
                Downvotes--;
            }

            switch (type)
            {
            case VoteType.Upvote: Liked = true; Upvotes++; return;

            case VoteType.None: Liked = null; return;

            case VoteType.Downvote: Liked = false; Downvotes++; return;
            }
        }
Example #5
0
        public async Task Vote(VoteType type, RequestType request)
        {
            VoteSettings.Setup(x => x.GetSettingsAsync()).ReturnsAsync(new VoteSettings
            {
                Enabled      = true,
                MovieVoteMax = 10
            });
            var votes = F.CreateMany <Votes>().ToList();

            VoteRepository.Setup(x => x.GetAll()).Returns(new EnumerableQuery <Votes>(votes)
                                                          .AsQueryable()
                                                          .BuildMock().Object);
            var result = new VoteEngineResult();

            if (type == VoteType.Downvote)
            {
                result = await Engine.DownVote(1, request);
            }
            else
            {
                result = await Engine.UpVote(1, request);
            }

            Assert.That(result.Result, Is.True);
            VoteRepository.Verify(x => x.Add(It.Is <Votes>(c => c.UserId == "abc" && c.VoteType == type)), Times.Once);
            VoteRepository.Verify(x => x.Delete(It.IsAny <Votes>()), Times.Never);
            MovieRequestEngine.Verify(x => x.ApproveMovieById(1), Times.Never);
        }
Example #6
0
        public void ModifyTask(VotePartition vote1, string newTask, VoteType type)
        {
            var votes = GetVoteEntries(type);

            var vote2 = vote1.ModifyTask(newTask);

            if (vote1 == vote2)
            {
                return;
            }

            if (!votes.TryGetValue(vote1, out var voters1))
            {
                voters1      = new IdentitySet();
                votes[vote1] = voters1;
            }

            if (!votes.TryGetValue(vote2, out var voters2))
            {
                voters2      = new IdentitySet();
                votes[vote2] = voters2;
            }

            // Save prior state to allow an undo
            PreserveMerge(vote1, vote2, voters1, voters2, type);

            // Update the votes->identity lookup
            voters2.UnionWith(voters1);
            voters1.Clear();
        }
Example #7
0
        public void Vote(long id, VoteType type)
        {
            var currentUserId = 1;//todo

            PostService.Vote(new PostVote(id, type, currentUserId));
            //make request to signalr
        }
Example #8
0
        /// <summary>
        /// Attempt to find any existing vote that matches with the vote we have,
        /// and can be used as a key in the VotesWithSupporters table.
        /// </summary>
        /// <param name="vote">The vote to search for.</param>
        /// <returns>Returns the string that can be used as a key in the VotesWithSupporters table.</returns>
        private string GetVoteKey(string vote, VoteType voteType)
        {
            // Store a lookup of the cleaned version of the vote so we don't have to repeat the processing.
            if (!cleanedKeys.TryGetValue(vote, out string cleaned))
            {
                cleaned           = VoteString.RemoveBBCode(vote);
                cleaned           = VoteString.DeUrlContent(cleaned);
                cleanedKeys[vote] = cleaned;
            }

            var votes = GetVotesCollection(voteType);

            // If the vote already matches an existing key, we don't need to search again.
            if (votes.ContainsKey(vote))
            {
                return(vote);
            }

            // Find any vote that matches using an agnostic string comparison, that ignores
            // case, spacing, and most punctuation.
            string agVote = votes.Keys.FirstOrDefault(k =>
                                                      Agnostic.StringComparer.Equals(cleaned, cleanedKeys[k]));

            // If we found a match, return that; otherwise this is a new vote, so return it unchanged.
            return(agVote ?? vote);
        }
        public void CreateVote(int ideaId, VoteType voteType, string userId = null)
        {
            Vote vote = new Vote();
            Idea idea = GetIdea(ideaId);

            if (userId != null)
            {
                UsersManager usersManager = new UsersManager(unitOfWorkManager);
                User         user         = usersManager.GetUser(Int32.Parse(userId));
                if (ideationsRepository.CheckUserVote(user, voteType, idea) == true)
                {
                    vote.User     = user;
                    vote.VoteType = voteType;
                    vote.Idea     = idea;
                    ideationsRepository.CreateVote(vote);
                    unitOfWorkManager.Save();
                }
                else
                {
                    throw new Exception("user already voted in that type");
                }
            }
            else
            {
                vote.VoteType = voteType;
                vote.Idea     = idea;
                ideationsRepository.CreateVote(vote);
                unitOfWorkManager.Save();
            }
        }
Example #10
0
        public HashSet <string> GetVoterListForVote(string vote, VoteType voteType)
        {
            var votes = VoteCounter.GetVotesCollection(voteType);

            if (votes.ContainsKey(vote))
            {
                return(votes[vote]);
            }

            if (voteType == VoteType.Rank)
            {
                var condensedVoters = votes.Where(k => Agnostic.StringComparer.Equals(VoteString.CondenseVote(k.Key), vote)).Select(k => k.Value);

                HashSet <string> condensedHash = new HashSet <string>();

                foreach (var cond in condensedVoters)
                {
                    condensedHash.UnionWith(cond);
                }

                return(condensedHash);
            }

            return(null);
        }
Example #11
0
        /// <summary>
        /// Add a line containing a reference to a voter's post.
        /// Handles rank, plan, and normal voters.
        /// </summary>
        /// <param name="voterName">The name of the voter.</param>
        /// <param name="voteType">The type of vote this is for.</param>
        /// <param name="marker">The marker to use for rank votes.</param>
        private void AddVoter(string voterName, VoteType voteType = VoteType.Vote, string marker = null)
        {
            bool closeBold = false;

            if (voteType == VoteType.Rank && marker != null)
            {
                sb.Append("[");
                sb.Append(marker);
                sb.Append("] ");
            }
            else if (VoteCounter.Instance.PlanNames.Contains(voterName))
            {
                sb.Append("[b]Plan: ");
                closeBold = true;
            }

            sb.Append("[url=\"");
            sb.Append(VoteInfo.GetVoterUrl(voterName, voteType));
            sb.Append("\"]");
            sb.Append(voterName);
            sb.Append("[/url]");

            if (closeBold)
            {
                sb.Append("[/b]");
            }

            sb.AppendLine();
        }
Example #12
0
    void EndVote()
    {
        int winner = GetMaxScore();

        voteText.text = "Winner is " + winner;
        voteTime      = false;
        monster[(int)currentVoteType].sprite = choices[winner - 1].sprite;
        monster[(int)currentVoteType].color  = Color.white;
        currentVoteType += 1;
        bool isThereNext = ((int)currentVoteType < 4);

        socketClient.ChangeVoteStatus(false);
        //VoteMessage msg = new VoteMessage();
        //msg.serverSpeaking = true;
        //msg.start = false;
        //msg.isThereNext =
        //server.SendMessageToAllClients(VoteMessage.id, msg);
        if (isThereNext)
        {
            StartCoroutine(WaitALittle());
        }
        else
        {
            StartCoroutine(WaitALittleEnd());
        }
    }
Example #13
0
        public void AddPlanTypeVoteTest()
        {
            string        voteLine = "[x] First test";
            string        voter    = "me";
            string        planname = "◈PlanPlan";
            string        postId   = "1";
            List <string> vote     = new List <string> {
                voteLine
            };
            VoteType voteType = VoteType.Plan;

            voteCounter.AddVotes(vote, planname, postId, voteType);
            voteCounter.AddVotes(vote, voter, postId, VoteType.Vote);

            Assert.IsTrue(voteCounter.GetVotesCollection(voteType).Keys.Contains(voteLine));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[voteLine].Contains(voter));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[voteLine].Contains(planname));

            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter));
            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(planname));
            Assert.AreEqual(postId, voteCounter.GetVotersCollection(voteType)[voter]);
            Assert.AreEqual(postId, voteCounter.GetVotersCollection(voteType)[planname]);

            Assert.IsTrue(voteCounter.HasPlan("PlanPlan"));
        }
Example #14
0
        // Merge rank votes
        public UndoAction(UndoActionType actionType, VoteType voteType, Dictionary <string, string> postIDs,
                          Dictionary <KeyValuePair <string, HashSet <string> >, string> mergedVotes)
        {
            if (actionType != UndoActionType.Merge)
            {
                throw new InvalidOperationException("Invalid use of constructor for Merge undo.");
            }
            if (voteType != VoteType.Rank)
            {
                throw new InvalidOperationException("Invalid use of constructor for non-rank merge.");
            }
            if (postIDs == null)
            {
                throw new ArgumentNullException(nameof(postIDs));
            }
            if (mergedVotes == null)
            {
                throw new ArgumentNullException(nameof(mergedVotes));
            }

            ActionType = actionType;
            VoteType   = voteType;
            PostIDs    = new Dictionary <string, string>(postIDs, postIDs.Comparer);

            MergedVotes = new Dictionary <KeyValuePair <string, HashSet <string> >, string>();
            foreach (var mergedVote in mergedVotes)
            {
                // original vote, revised vote key
                MergedVotes.Add(new KeyValuePair <string, HashSet <string> >(mergedVote.Key.Key, new HashSet <string>(mergedVote.Key.Value)), mergedVote.Value);
            }
        }
Example #15
0
        public void AddVoteReplacementTest1()
        {
            string        voteLine1 = "[x] First test";
            string        voteLine2 = "[x] Second test";
            string        voter1    = "me";
            string        postId1   = "1";
            string        postId2   = "2";
            List <string> vote1     = new List <string> {
                voteLine1
            };
            List <string> vote2 = new List <string> {
                voteLine2
            };
            VoteType voteType = VoteType.Vote;

            voteCounter.AddVotes(vote1, voter1, postId1, voteType);
            voteCounter.AddVotes(vote2, voter1, postId2, voteType);

            Assert.IsFalse(voteCounter.GetVotesCollection(voteType).Keys.Contains(voteLine1));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType).Keys.Contains(voteLine2));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[voteLine2].Contains(voter1));

            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter1));
            Assert.AreEqual(postId2, voteCounter.GetVotersCollection(voteType)[voter1]);
        }
Example #16
0
        public void AddVoteMultiTest2()
        {
            string        voteLine1 = "[x] First test";
            string        voteLine2 = "[x] 『b』First『/b』 test";
            string        voter1    = "me";
            string        postId1   = "1";
            string        voter2    = "you";
            string        postId2   = "2";
            List <string> vote1     = new List <string> {
                voteLine1
            };
            List <string> vote2 = new List <string> {
                voteLine2
            };
            VoteType voteType = VoteType.Vote;

            voteCounter.AddVotes(vote1, voter1, postId1, voteType);
            voteCounter.AddVotes(vote2, voter2, postId2, voteType);

            Assert.IsTrue(voteCounter.GetVotesCollection(voteType).Keys.Contains(voteLine1));
            Assert.IsFalse(voteCounter.GetVotesCollection(voteType).Keys.Contains(voteLine2));
            Assert.AreEqual(1, voteCounter.GetVotesCollection(voteType).Count);
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[voteLine1].Contains(voter1));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[voteLine1].Contains(voter2));

            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter1));
            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter2));
            Assert.AreEqual(postId1, voteCounter.GetVotersCollection(voteType)[voter1]);
            Assert.AreEqual(postId2, voteCounter.GetVotersCollection(voteType)[voter2]);
        }
Example #17
0
        private static void TestMismatch(string line1, string line2)
        {
            string        voter1  = "me";
            string        postId1 = "1";
            string        voter2  = "you";
            string        postId2 = "2";
            List <string> vote1   = new List <string> {
                line1
            };
            List <string> vote2 = new List <string> {
                line2
            };
            VoteType voteType = VoteType.Vote;

            voteCounter.AddVotes(vote1, voter1, postId1, voteType);
            voteCounter.AddVotes(vote2, voter2, postId2, voteType);

            Assert.IsTrue(voteCounter.GetVotesCollection(voteType).Keys.Contains(line1));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType).Keys.Contains(line2));
            Assert.AreEqual(2, voteCounter.GetVotesCollection(voteType).Count);
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[line1].Contains(voter1));
            Assert.IsTrue(voteCounter.GetVotesCollection(voteType)[line2].Contains(voter2));

            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter1));
            Assert.IsTrue(voteCounter.GetVotersCollection(voteType).ContainsKey(voter2));
            Assert.AreEqual(postId1, voteCounter.GetVotersCollection(voteType)[voter1]);
            Assert.AreEqual(postId2, voteCounter.GetVotersCollection(voteType)[voter2]);
        }
		public ActionResult Vote(int answerId, VoteType voteType)
		{
			var vote = new AnswerVote {AnswerId = answerId, UserId = User.Identity.GetUserId(), VoteType = voteType};
			_voteService.Create(vote);

			return Json(new {answerId, rating = CalculateRating(answerId)}, JsonRequestBehavior.AllowGet);
		}
Example #19
0
        public void FindVotesForVoterTest2()
        {
            string        voteLine1 = "[x] Vote for stuff 1";
            string        voteLine2 = "[x] Vote for stuff 2";
            string        voter1    = "me";
            string        voter2    = "you";
            string        postId1   = "1";
            string        postId2   = "2";
            List <string> vote1     = new List <string> {
                voteLine1
            };
            List <string> vote2 = new List <string> {
                voteLine1, voteLine2
            };
            VoteType voteType = VoteType.Vote;

            voteCounter.AddVotes(vote1, voter1, postId1, voteType);
            voteCounter.AddVotes(vote2, voter2, postId2, voteType);
            voteCounter.ReferenceVoters.Add(voter1);
            voteCounter.ReferenceVoters.Add(voter2);

            var votes = voteCounter.GetVotesFromReference("[x] you", "Him");

            Assert.AreEqual(2, votes.Count);
            Assert.IsTrue(votes.Contains(voteLine1));
            Assert.IsTrue(votes.Contains(voteLine2));
        }
Example #20
0
 public void Join(IEnumerable <Identity> voters1, Identity voter2, VoteType type)
 {
     foreach (var voter in voters1)
     {
         Join(voter, voter2, type);
     }
 }
Example #21
0
        // Join
        public UndoAction(UndoActionType actionType, VoteType voteType, Dictionary <string, string> postIDs,
                          List <string> joinedVoters, IEnumerable <KeyValuePair <string, HashSet <string> > > priorVotes)
        {
            if (actionType != UndoActionType.Join)
            {
                throw new InvalidOperationException("Invalid use of constructor for Join undo.");
            }
            if (joinedVoters == null)
            {
                throw new ArgumentNullException(nameof(joinedVoters));
            }
            if (priorVotes == null)
            {
                throw new ArgumentNullException(nameof(priorVotes));
            }

            ActionType = actionType;
            VoteType   = voteType;
            PostIDs    = new Dictionary <string, string>(postIDs, postIDs.Comparer);

            JoinedVoters = new List <string>(joinedVoters);

            PriorVotes = new List <KeyValuePair <string, HashSet <string> > >();
            foreach (var prior in priorVotes)
            {
                PriorVotes.Add(new KeyValuePair <string, HashSet <string> >(prior.Key, new HashSet <string>(prior.Value)));
            }
        }
 public CommentVote(VoteType type, int voter, int affectedComment)
 {
     ID              = voter + ":" + affectedComment;
     Type            = type;
     Voter           = voter;
     AffectedComment = affectedComment;
 }
Example #23
0
        // Merge
        public UndoAction(UndoActionType actionType, VoteType voteType, Dictionary <string, string> postIDs,
                          string vote1, HashSet <string> voters1,
                          string vote2, HashSet <string> voters2)
        {
            if (actionType != UndoActionType.Merge)
            {
                throw new InvalidOperationException("Invalid use of constructor for Merge undo.");
            }
            if (vote1 == null)
            {
                throw new ArgumentNullException(nameof(vote1));
            }
            if (voters1 == null)
            {
                throw new ArgumentNullException(nameof(voters1));
            }
            if (vote2 == null)
            {
                throw new ArgumentNullException(nameof(vote2));
            }
            if (voters2 == null)
            {
                throw new ArgumentNullException(nameof(voters2));
            }

            ActionType = actionType;
            VoteType   = voteType;
            PostIDs    = new Dictionary <string, string>(postIDs, postIDs.Comparer);

            Vote1   = vote1;
            Voters1 = new HashSet <string>(voters1 ?? Enumerable.Empty <string>());

            Vote2   = vote2;
            Voters2 = new HashSet <string>(voters2 ?? Enumerable.Empty <string>());
        }
Example #24
0
        public void VoteForComment(Guid commentId, Guid userId, string ipAddress, VoteType voteType, DateTime dateCasted)
        {
            _conn.Perform(conn =>
            {
                var vote = conn.Single <Vote>(x => x.UserId == userId && x.CommentId == commentId);

                if (vote == null)
                {
                    conn.Insert(new Vote
                    {
                        Id          = GuidUtil.NewSequentialId(),
                        DateCreated = Common.CurrentTime(),
                        UserId      = userId,
                        CommentId   = commentId,
                        VoteType    = voteType,
                        DateCasted  = dateCasted,
                        IpAddress   = ipAddress
                    });
                }
                else
                {
                    if (vote.VoteType != voteType)
                    {
                        conn.Update <Vote>(new { Type = (int)voteType }, x => x.Id == vote.Id);
                    }
                }
            });
        }
Example #25
0
        public object SetVoteAsync(Post post, User user, VoteType type)
        {
            var vote = _context.Votes
                       .Where(v => v.PostId == post.Id && v.UserId == user.Id)
                       .FirstOrDefault();

            if (vote != null)
            {
                _context.Remove(vote);
                _context.SaveChanges();

                // Return if the given vote was the same so it is only a remove.
                if (vote.Type == type)
                {
                    return(null);
                }
            }

            vote = new Vote {
                Post = post, User = user, Type = type
            };

            _context.Votes.Add(vote);
            _context.SaveChanges();

            return(vote.Type);
        }
Example #26
0
        public void VoteForPost(Guid postId, Guid userId, string ipAddress, VoteType voteType, DateTime dateCasted)
        {
            _conn.Perform(conn =>
            {
                var vote = conn.Single <Vote>(x => x.UserId == userId && x.PostId == postId);

                if (vote == null)
                {
                    conn.Insert(new Vote
                    {
                        Id         = Guid.NewGuid(),
                        CreatedAt  = TimeHelper.CurrentTime(),
                        UserId     = userId,
                        PostId     = postId,
                        VoteType   = voteType,
                        DateCasted = dateCasted,
                        IpAddress  = ipAddress
                    });
                }
                else
                {
                    if (vote.VoteType != voteType)
                    {
                        conn.Update <Vote>(new { Type = (int)voteType }, x => x.Id == vote.Id);
                    }
                }
            });
        }
 private int GetVotes(string articleId, VoteType voteType)
 {
     return(this.dbContext.Votes
            .Where(v => v.ArticleId == articleId && v.Type == voteType)
            .ToList()
            .Count);
 }
Example #28
0
        public async Task <HttpResponse <Annotation> > Vote(TextFormat textFormat, VoteType voteType, string annotationId)
        {
            using (var client = new HttpClient())
            {
                var baseAddress =
                    UriHelper.CreateUri <Annotation>(textFormat.ToString().ToLower(), annotationId, true, voteType);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", _accessToken);
                var response = await client.PutAsync(baseAddress, null).ConfigureAwait(false);

                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync().ConfigureAwait(false);

                    var jToken       = JToken.Parse(result);
                    var jsonResponse = jToken.SelectToken("response").SelectToken("annotation");
                    var jsonMeta     = jToken.SelectToken("meta");

                    var serializer = new JsonSerializer
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver
                        {
                            NamingStrategy = new SnakeCaseNamingStrategy()
                        }
                    };
                    return
                        (new HttpResponse <Annotation>
                    {
                        Meta = jsonMeta.ToObject <Meta>(serializer),
                        Response = jsonResponse.ToObject <Annotation>(serializer)
                    });
                }
            }
        }
Example #29
0
        public VoteModel(UserInfo user, VoteType type, string identifier) : base(user)
        {
            Type       = type;
            Identifier = identifier;

            UrlHelper.TryCastUrlToAuthorAndPermlink(Identifier, out Author, out Permlink);
        }
Example #30
0
        public T HighestVoted <T>(VoteType voteType, List <Client> voters)
        {
            if (voteType == VoteType.Sub && !AllowSubVoting)
            {
                return(default(T));
            }
            if (voteType == VoteType.Mode && !AllowModeVoting)
            {
                return(default(T));
            }

            List <Pair <object, int> > voteList = GetVoteList(voteType, voters);

            T   selected     = default(T);
            int highestVotes = 0;

            foreach (Pair <object, int> votable in voteList)
            {
                if (selected == null || votable.Second > highestVotes)
                {
                    highestVotes = votable.Second;
                    selected     = (T)votable.First;
                }
            }

            return(selected);
        }
Example #31
0
        public async Task VoteAsync(int articleId, string userId, VoteType voteType)
        {
            var vote = await this.votesRepository
                       .All()
                       .FirstOrDefaultAsync(
                v => v.ArticleId == articleId && v.UserId == userId);

            if (vote == null)
            {
                vote = new Vote
                {
                    ArticleId = articleId,
                    UserId    = userId,
                    Type      = voteType,
                };

                await this.votesRepository.AddAsync(vote);

                await this.votesRepository.SaveChangesAsync();
            }
            else
            {
                vote.Type = voteType;

                this.votesRepository.Update(vote);
                await this.votesRepository.SaveChangesAsync();
            }
        }
 public RichQuestion(Question question, int votes, VoteType? currentUsersVotes, List<RichAnswer> answers, int answerCount)
 {
     Question = question;
     Votes = votes;
     CurrentUsersVote = currentUsersVotes;
     Answers = answers;
     AnswerCount = answerCount;
 }
        public HttpResponseMessage Questions(int qid, VoteType voteType)
        {
            if (User.Identity.IsAuthenticated == false)
            {
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }

            var user = db.Users.Find(User.Identity.GetUserId());

            var q = db.Questions.Find(qid);

            if (q == null)
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            q.Votes.Where(v => v.Voter == user && v.Active == true).ToList().ForEach(v =>
            {
                v.Active = false;
            });

            int voteValue;

            switch (voteType)
            {
                case VoteType.Remove:
                    voteValue = 0;
                    break;
                case VoteType.Up:
                    voteValue = 1;
                    break;
                case VoteType.Down:
                    voteValue = -1;
                    break;
                default:
                    voteValue = 0;
                    break;
            }

            q.Votes.Add(new Vote()
            {
                Voter = user,
                VoteValue = voteValue,
                TimeStamp = DateTime.UtcNow,
                Active = true
            });

            try
            {
                db.SaveChangesAsync();
            }
            catch (Exception)
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
 public PuzzleViewModel(Puzzle puzzle, VoteType voteType, Solution latestSolution, Solution bestSolution, int userSolutionCount, IEnumerable<SolutionViewModel> puzzleLeaderBoard, bool isCreator, bool isLeading)
 {
     _puzzle = puzzle;
     _voteType = voteType;
     LatestSolution = latestSolution;
     BestSolution = bestSolution;
     UserSolutionCount = userSolutionCount;
     PuzzleLeaderBoard = puzzleLeaderBoard;
     IsCreator = isCreator;
     Themes = puzzle.Themes.Select(x => x.Name);
     IsLeading = isLeading;
 }
        private static string GetPrefix(VoteType voteType)
        {
            const string path = "/Content/images/";
            switch (voteType)
            {
                case VoteType.ThumbUp:
                    return path + "plus";

                case VoteType.ThumbDown:
                    return path + "minus";

                default:
                    throw new Exception("Illegal vote type " + voteType);
            }
        }
 private static int GetPointsForVotee(VoteType vote)
 {
     switch (vote)
     {
         case VoteType.None:
             return 0;
         case VoteType.Up:
             return Settings.UpVoteReputationValue;
         case VoteType.Down:
             return Settings.DownVoteReputationValue;
     }
     return 0;
 }
 private static int GetPointsForVoter(VoteType vote)
 {
     return 0;
 }
Example #38
0
        public ActionResult VoteComment(Guid commentId, VoteType type)
        {
            _commandBus.Send(new CastVoteForComment
            {
                UserId = _userContext.CurrentUser.Id,
                CommentId = commentId,
                DateCasted = Common.CurrentTime(),
                IpAddress = HttpContext.RemoteAddress(),
                VoteType = type
            });

            return CommonJsonResult(true);
        }
        /// <summary>
        /// Votes on a puzzle
        /// </summary>
        /// <remarks>
        /// If the puzzle has already been voted on in the specified direction, 
        /// then the vote is removed.
        /// </remarks>
        /// <param name="puzzleId">The Id of the puzzle to vote on</param>
        /// <param name="voteType">The vote type</param>
        /// <returns>
        /// The following JSON object is returned:
        /// 
        /// message: Contains an error message
        /// voteCount: The current vote count of the puzzle. Undefined if an error occurs.
        /// isUpVoted: True if the users vote is an up-vote otherwise false. Undefined if an error occurs. 
        /// </returns>
        public JsonResult VoteOnPuzzle(int puzzleId, VoteType voteType)
        {
            var result = _puzzleService.VoteOnPuzzle(puzzleId, voteType);

            //We need to format the vote count before sending it back.
            var voteCount = result.VoteCount.HasValue ? result.VoteCount.Value.FormatInteger() : null;

            return Json(new { result.ErrorMessage, VoteCount = voteCount, result.VoteType }, JsonRequestBehavior.AllowGet);
        }
Example #40
0
 public RichAnswer(Answer answer, VoteType? currentUsersVote)
 {
     Answer = answer;
     CurrentUserVote = currentUsersVote;
 }
Example #41
0
 public void Vote(VoteType type)
 {
     var request = Reddit.CreatePost(VoteUrl);
     var stream = request.GetRequestStream();
     Reddit.WritePostBody(stream, new
     {
         dir = (int)type,
         id = FullName,
         uh = Reddit.User.Modhash
     });
     stream.Close();
     var response = request.GetResponse();
     var data = Reddit.GetResponseString(response.GetResponseStream());
     Liked = null;
 }
        /// <summary>
        /// Votes on a puzzle.
        /// </summary>
        /// <remarks>If the puzzle has already been in the specified direction then the vote is removed.</remarks>
        /// <param name="puzzleId">The puzzle to vote up</param>
        /// <param name="voteType">The type of vote to apply to the puzzle</param>
        public VoteResult VoteOnPuzzle(int puzzleId, VoteType voteType)
        {
            Puzzle puzzle = null;
            User user;
            VoteResult voteResult = null;
            var puzzleCreatorRep = 0;
            var voterRep = 0;

            using (_repository.OpenSession())
            {
                user = _repository.All<User>().ById(_authenticationService.CurrentUserId);

                #region Ensure

                //Make sure the puzzle exists
                puzzle = _repository.All<Puzzle>().ById(puzzleId);
                if (puzzle == null)
                    return new VoteResult { ErrorMessage = "The puzzle you requested does not exist." };

                //Only logged in users can vote
                if (!_authenticationService.IsAuthenticated)
                    return new VoteResult { ErrorMessage = "You must be logged in to vote on a puzzle" };

                //Make sure the user has enough reputation to vote
                if (voteType == VoteType.Up && user.Reputation < Settings.MinimumReputationToUpVote)
                    return new VoteResult
                    {
                        ErrorMessage =
                            "You must have a reputation of at least {0} to up vote a puzzle".ToFormat(
                            Settings.MinimumReputationToUpVote)
                    };
                if (voteType == VoteType.Down && user.Reputation < Settings.MinimumReputationToDownVote)
                    return new VoteResult
                    {
                        ErrorMessage =
                            "You must have a reputation of at least {0} to down vote a puzzle".ToFormat(
                            Settings.MinimumReputationToDownVote)
                    };

                //Make sure the user is not voting on their own puzzle.
                if (user.Id == puzzle.User.Id)
                    return new VoteResult { ErrorMessage = "You cannot vote on your own puzzle." };

                //Make sure the user hasn't reached their vote limit for the day
                var todaysNumberOfVotes =
                    _repository.All<Vote>().Where(x => x.UserId == user.Id && x.DateVoted == DateTime.Now.Date).
                        Count();

                if (todaysNumberOfVotes >= Settings.MaximumDailyVoteLimit)
                    return new VoteResult
                               {
                                   ErrorMessage =
                                       "You have reached the daily vote limit of {0}. Please wait a little while before voting again."
                                       .ToFormat(Settings.MaximumDailyVoteLimit)
                               };

                #endregion

                //Begin transaction
                using (var tx = _repository.BeginTransaction())
                {
                    voteResult = new VoteResult();
                    puzzleCreatorRep += GetPointsForVotee(voteType);
                    voterRep += GetPointsForVoter(voteType);

                    //Check for an existing vote record.
                    var vote = _repository.All<Vote>().Where(v => v.UserId == user.Id && v.PuzzleId == puzzleId).FirstOrDefault();
                    if (vote == null)
                    {
                        //No vote exists so create a new vote.
                        vote = new Vote
                                   {
                                       DateVoted = DateTime.Now.Date,
                                       PuzzleId = puzzleId,
                                       UserId = user.Id,
                                       VoteType = voteType
                                   };

                        _repository.Save(vote);

                        voteResult.VoteType = voteType;
                    }
                    else
                    {
                        //Determine which vote type to apply
                        var voteTypeToApply = VoteType.None;

                        if (voteType == VoteType.Down && vote.VoteType == VoteType.Down)
                        {
                            puzzleCreatorRep *= -1;
                            voterRep *= -1;
                            voteTypeToApply = VoteType.None;
                        }
                        else if (voteType == VoteType.Up && vote.VoteType == VoteType.Up)
                        {
                            puzzleCreatorRep *= -1;
                            voterRep *= -1;
                            voteTypeToApply = VoteType.None;
                        }
                        else
                            voteTypeToApply = voteType;

                        if (voteTypeToApply == VoteType.None)
                            _repository.Delete(vote);
                        else
                        {
                            vote.VoteType = voteTypeToApply;
                            _repository.Save(vote);
                        }

                        voteResult.VoteType = voteTypeToApply;
                    }

                    puzzle.User.Reputation += puzzleCreatorRep;
                    user.Reputation += voterRep;

                    _repository.Save(puzzle.User);
                    _repository.Save(user);

                    _repository.Save(new ActionItem
                                         {
                                             Action = ActionType.Voted,
                                             DateCreated = DateTime.Now,
                                             UserId = user.Id,
                                             PuzzleId = puzzleId,
                                             VoteType = voteResult.VoteType.Value,
                                             AffectedUserId = puzzle.User.Id
                                         });

                    tx.Commit();
                }
            }
            //Update Puzzle Vote Count
            voteResult.VoteCount = UpdatePuzzleVoteCount(puzzleId);

            return voteResult;
        }
 public Task VoteAsync(VoteType vote, string itemId)
 {
     EnsureIsAuthorized();
     var request = new NameValueCollection { { "direction", vote.ToString().ToLower() } };
     return _restTemplate.PutAsync("links/" + itemId + "/vote", request);
 }
Example #44
0
        public ActionResult VotePost(Guid postId, VoteType type)
        {
            if (!Request.IsAuthenticated)
            {
                return Json(new
                {
                    success = false,
                    error = "You must be logged in to vote for an item."
                });
            }

            _commandBus.Send(new CastVoteForPost
            {
                UserId = _userContext.CurrentUser.Id,
                PostId = postId,
                DateCasted = Common.CurrentTime(),
                IpAddress = Request.UserHostAddress,
                VoteType = type
            });

            return Json(new
            {
                success = true,
                error = (string)null
            });
        }
 public static string ImageForVote(VoteType voteType, VoteType? userVote)
 {
     bool selected = voteType == userVote;
     return GetPrefix(voteType) + (selected ? "_on.png" : "_off.png");
 }
Example #46
0
 public Task VoteInPollAsync(IPoll poll, VoteType voteType)
 {
     throw new NotImplementedException();
 }
Example #47
0
        public void VoteForPost(Guid postId, Guid userId, string ipAddress, VoteType voteType, DateTime dateCasted)
        {
            _conn.Perform(conn =>
            {
                var vote = conn.Single<Vote>(x => x.UserId == userId && x.PostId == postId);

                if (vote == null)
                {
                    conn.Insert(new Vote
                    {
                        Id = GuidUtil.NewSequentialId(),
                        DateCreated = Common.CurrentTime(),
                        UserId = userId,
                        PostId = postId,
                        VoteType = voteType,
                        DateCasted = dateCasted,
                        IpAddress = ipAddress
                    });
                }
                else
                {
                    if (vote.VoteType != voteType)
                        conn.Update<Vote>(new { Type = (int)voteType }, x => x.Id == vote.Id);
                }
            });
        }
        public ActionResult Vote(Guid id, VoteType voteType)
        {
            var userId = User.Identity.UserId();
            var theme = this.DB.Themes
                .Include("Votes")
                .FirstOrDefault(t => t.ThemeId == id && t.Owner != userId);
            if (theme != null)
            {
                if (theme.Votes.Any(v => v.Owner == userId) == false)
                {
                    theme.Votes.Add(new Vote
                    {
                        Owner = userId,
                        ThemeId = theme.ThemeId,
                        VoteType = (int)voteType
                    });
                    this.DB.SaveChanges();
                }
                return PartialView("_Theme", theme);
            }

            return new EmptyResult();
        }
Example #49
0
 private void Vote(Repository repo, TreeDefinition votesDir, VoteType vote)
 {
     switch (vote)
     {
         case LibBastion.VoteType.Upvote:
             votesDir.Add(UPVOTE, Upvote(repo), Mode.NonExecutableFile);
             break;
         case LibBastion.VoteType.Downvote:
             votesDir.Add(DOWNVOTE, Downvote(repo), Mode.NonExecutableFile);
             break;
     }
 }
Example #50
0
        public ActionResult VotePost(Guid postId, VoteType type)
        {
            _commandBus.Send(new CastVoteForPost
            {
                UserId = _userContext.CurrentUser.Id,
                PostId = postId,
                DateCasted = Common.CurrentTime(),
                IpAddress = Request.UserHostAddress,
                VoteType = type
            });

            return CommonJsonResult(true);
        }
Example #51
0
        public void Vote(Post post, Identity voter, VoteType vote)
        {
            using (var repo = new Repository(_directory.FullName))
            {
                var postCommit = repo.Branches[post.Id].Tip;

                // Retrieve existing tree
                var commitRoot = postCommit.Tree;
                var votesDir = (Tree)commitRoot[VOTES_DIR].Target;
                var repliesDir = (Tree)commitRoot[REPLIES_DIR].Target;

                // Copy existing content to new votes treedef
                var newVotesDir = new TreeDefinition();
                foreach (TreeEntry obj in votesDir)
                {
                    newVotesDir.Add(obj.Name, obj);
                }
                // Add new vote to new votes treedef
                Vote(repo, newVotesDir, vote);

                // Assemble new root treedef
                var newPostRoot = new TreeDefinition();
                newPostRoot.Add(VOTES_DIR, repo.ObjectDatabase.CreateTree(newVotesDir));
                newPostRoot.Add(REPLIES_DIR, repliesDir);

                // Commit new root treedef to post branch
                var message = string.Format("{0} by {1}", vote, voter.Name);
                var sig = new Signature(voter.Name, voter.Identifier, DateTimeOffset.UtcNow);
                CommitToBranch(repo, post.Id, message, sig, repo.ObjectDatabase.CreateTree(newPostRoot));
            }
        }
 public UserProfilePuzzleViewModel(Puzzle puzzle, VoteType userVote, bool isAuthenticated, int currentUserId)
 {
     IsAuthenticated = isAuthenticated;
     CurrentUserId = currentUserId;
     _puzzle = puzzle;
     _userVote = userVote;
     Themes = puzzle.Themes;
 }
        public void SetVote(VoteType type)
        {
            if (this.Vote == type) return;

            var request = WebAgent.CreatePost(VoteUrl);
            var stream = request.GetRequestStream();
            WebAgent.WritePostBody(stream, new
            {
                dir = (int)type,
                id = FullName,
                uh = Reddit.User.Modhash
            });
            stream.Close();
            var response = request.GetResponse();
            var data = WebAgent.GetResponseString(response.GetResponseStream());

            if (Liked == true) Upvotes--;
            if (Liked == false) Downvotes--;

            switch(type)
            {
                case VoteType.Upvote: Liked = true; Upvotes++; return;
                case VoteType.None: Liked = null; return;
                case VoteType.Downvote: Liked = false; Downvotes++; return;
            }
        }