Пример #1
0
        public object Vote(VoteModel model)
        {
            Choice choice = db.Choices.Include("Poll").Include("VotedBy").FirstOrDefault(c => c.Id == model.ChoiceId);
            User   user   = db.Users.FirstOrDefault(u => u.Id == model.UserId);

            if (choice == null || user == null)
            {
                return(new { Success = false, Message = "Invalid User and/or Choice." });
            }

            PaulPrincipal paul = User as PaulPrincipal;

            if (paul != null && user.Id != paul.Id)
            {
                return(new { Success = false, Message = "You can only vote as the currently logged in user." });
            }

            // Toggle off
            if (choice.VotedBy.Count(u => u.Id == model.UserId) > 0)
            {
                User userToRemove = choice.VotedBy.FirstOrDefault(u => u.Id == model.UserId);
                choice.VotedBy.Remove(userToRemove);

                db.Entry(choice).State = EntityState.Modified;
                db.SaveChanges();

                return(new { Success = true, Choice = choice, Action = "Removed" });
            }

            // Check if max
            Poll poll          = choice.Poll;
            int  userVoteCount = 0;

            foreach (Choice pollChoice in poll.Choices)
            {
                userVoteCount += pollChoice.VotedBy.Count(u => u.Id == model.UserId);

                if (userVoteCount >= poll.MaxVotes)
                {
                    return
                        (new
                    {
                        Success = false,
                        Message = "You are only allowed to vote " + poll.MaxVotes + " times in this poll."
                    });
                }
            }

            choice.VotedBy.Add(user);
            db.Entry(choice).State = EntityState.Modified;
            db.SaveChanges();

            return(new { Success = true, Choice = choice, Action = "Added" });
        }
Пример #2
0
        // POST api/polls
        public object Add(Poll poll)
        {
            // Weird.. time zones are setup properly lol
            poll.Closing = poll.Closing.AddHours(-4);

            db.Entry(poll.CreatedBy).State = EntityState.Unchanged;
            foreach (Choice choice in poll.Choices)
            {
                choice.AddedBy = poll.CreatedBy;
                //db.Entry(choice.AddedBy).State = EntityState.Unchanged;
            }
            db.Polls.Add(poll);
            db.SaveChanges();

            poll = db.Polls.Include("Choices").Include("CreatedBy").FirstOrDefault(p => p.Id == poll.Id);
            return(new { Success = true, Poll = poll });
        }