/// <summary>
        /// Rates the meal.
        /// </summary>
        private async void Rate()
        {
            await TryExecuteAsync(async _ =>
            {
                double value = Rating == UserRating.Good ? 1.0
                             : Rating == UserRating.Neutral ? 0.5
                                                         : 0.0;

                var request = new VoteRequest {
                    DeviceId = _deviceIdentifier.Current, MealId = Meal.Id, RatingValue = value
                };
                var response = await _foodService.VoteAsync(request);

                if (response.Status == VoteStatus.Success)
                {
                    Meal.Rating            = UpdateRating(Meal.Rating, value);
                    Meal.Restaurant.Rating = UpdateRating(Meal.Restaurant.Rating, value);

                    _navigationService.NavigateBack();
                }
                else
                {
                    Status = response.Status;
                }
            });
        }
Beispiel #2
0
        public void Vote(VoteRequest request, IVoteView view)
        {
            UserBiz userBiz = new UserBiz();

            if (userBiz.GetCurrentUser().RandomCode != request.RandomCode)
            {
                view.ShowVoteResult("验证码错误");
            }
            else if (userBiz.GetCurrentUser().HaveVoteCount > 9)
            {
                view.ShowVoteResult("投票失败,您已经投过10张票啦~~");
            }
            else
            {
                VoteBiz biz = new VoteBiz();
                if (biz.Vote(new Vote()
                {
                    ProductId = request.ProductId, IP = request.IP
                }))
                {
                    userBiz.GetCurrentUser().HaveVoteCount++;
                    view.ShowVoteResult("投票成功");
                }
                else
                {
                    view.ShowVoteResult("投票失败,您所在的IP地址已经投过10张票啦~");
                }
            }
        }
        public async Task <ActionResult <PollVote> > PostPollVote(VoteRequest request)
        {
            Member member = GetAuthenticatedMember();

            // check if member is a participant of this poll
            if (!IsParticipant(request.PollID, member))
            {
                return(NotFound());
            }

            // check if member has already voted
            if (HasVoted(request.PollID, member))
            {
                return(BadRequest("Already voted!"));
            }

            _context.PollVotes.Add(new PollVote
            {
                MemberID     = member.MemberID,
                PollAnswerID = request.AnswerID
            });

            await _context.SaveChangesAsync();

            return(Ok());
        }
        public ContentResult edit(VoteRequest request)
        {
            var msg  = string.Empty;
            var flag = _voteService.Update(request, UserContext.SysUserContext.Id, out msg);

            return(Result <string>(flag, msg));
        }
Beispiel #5
0
        public async Task <ActionResult <EventDto> > AddVotes(long id, [FromBody] VoteRequest request)
        {
            var command  = new VoteCommand(id, request.Name, request.Votes);
            var eventDto = await _mediator.Send(command);

            return(Ok(eventDto));
        }
        public async Task <ActionResult <PollVote> > PutPollVote(VoteRequest request)
        {
            Member member = GetAuthenticatedMember();

            if (!IsParticipant(request.PollID, member))
            {
                return(NotFound());
            }

            // if for some reason the user hasn't voted yet, submit it as a new vote
            if (!HasVoted(request.PollID, member))
            {
                return(await PostPollVote(request));
            }

            // change answer
            var pollVote = _context.PollVotes.FirstOrDefault(pv => pv.PollVoteID == request.VoteID && pv.MemberID == member.MemberID);

            if (pollVote == null)
            {
                return(BadRequest("Invalid action for this user"));
            }
            pollVote.PollAnswerID          = request.AnswerID;
            _context.Entry(pollVote).State = EntityState.Modified;

            await _context.SaveChangesAsync();

            return(NoContent());
        }
Beispiel #7
0
        public async Task <Response> AddVoteAsync(
            string urlBase,
            string servicePrefix,
            string controller,
            VoteRequest voteRequest,
            string tokenType,
            string accessToken)
        {
            try
            {
                var request = JsonConvert.SerializeObject(voteRequest);
                var content = new StringContent(request, Encoding.UTF8, "application/json");
                var client  = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                var url      = $"{servicePrefix}{controller}";
                var response = await client.PostAsync(url, content);

                var answer = await response.Content.ReadAsStringAsync();

                var obj = JsonConvert.DeserializeObject <Response>(answer);
                return(obj);
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                });
            }
        }
Beispiel #8
0
        /// <summary>
        /// Processes the given vote request.
        /// </summary>
        /// <param name="request">VoteRequest</param>
        void Vote(VoteRequest request)
        {
            var lastLogIndex = this.Logs.Count;
            var lastLogTerm  = this.GetLogTermForIndex(lastLogIndex);

            if (request.Term < this.CurrentTerm ||
                (this.VotedFor != null && this.VotedFor != request.CandidateId) ||
                lastLogIndex > request.LastLogIndex ||
                lastLogTerm > request.LastLogTerm)
            {
                Console.WriteLine("\n [Server] " + this.ServerId + " | term " + this.CurrentTerm +
                                  " | log " + this.Logs.Count + " | vote false\n");
                this.Send(request.CandidateId, new VoteResponse(this.CurrentTerm, false));
            }
            else
            {
                Console.WriteLine("\n [Server] " + this.ServerId + " | term " + this.CurrentTerm +
                                  " | log " + this.Logs.Count + " | vote true\n");

                this.VotedFor = request.CandidateId;
                this.LeaderId = null;

                this.Send(request.CandidateId, new VoteResponse(this.CurrentTerm, true));
            }
        }
Beispiel #9
0
        private void rejectVote(VoteRequest request, AcceptorState state)
        {
            VoteStatus   voteStatus = VoteStatus.Rejected;
            VoteResponse response   = generateVoteResponse(state, request, voteStatus);

            sendVoteResponse(request.MessageSender, response);
        }
Beispiel #10
0
        public bool InsertVote(VoteRequest voteRequest)
        {
            var vote        = _mapper.Map <TVote>(voteRequest);
            var updateCount = _voteRepository.InsertVote(vote);

            return(updateCount > 0);
        }
Beispiel #11
0
 private void VerifyReturnsNoContent(int warId, VoteRequest voteRequest, System.Web.Http.IHttpActionResult result)
 {
     result.Should().BeOfType <StatusCodeResult>();
     ((StatusCodeResult)result).StatusCode.Should().Be(HttpStatusCode.NoContent);
     voteRequest.UserIdentifier.Should().Be(_stubUser.Id);
     _stubVoteRepository.Verify(x => x.Add(warId, voteRequest), Times.Once);
 }
 public BaseResponse <VotingItemResponse> CastVote([FromBody] VoteRequest request, [FromHeader] Guid UserID)
 {
     return(BaseResponse <VotingItemResponse> .ConstructResponse(
                HttpStatusCode.OK,
                HttpStatusCode.OK.ToString(),
                voteService.VoteForItem(request, UserID)));
 }
Beispiel #13
0
 public override Task <VoteResult> Vote(VoteRequest request)
 {
     if (!GrantVotes)
     {
         return(Task.FromResult(new VoteResult(Term, false)));
     }
     return(base.Vote(request));
 }
Beispiel #14
0
 public async Task Add(int warId, VoteRequest request)
 {
     using (var connection = await CreateOpenConnection())
         using (var command = CreateInsertCommand(warId, request, connection))
         {
             await command.ExecuteNonQueryAsync();
         }
 }
Beispiel #15
0
        public async Task <VoteRequest> SendVoteRequest()
        {
            var json = await client.GetStringAsync($"api/LectionRating/SendVoteRequest");

            VoteRequest request = await Task.Run(() => JsonConvert.DeserializeObject <VoteRequest>(json));

            return(request);
        }
Beispiel #16
0
 public override Task<VoteResult> Vote(VoteRequest request)
 {
     if (!GrantVotes)
     {
         return Task.FromResult(new VoteResult(Term, false));
     }
     return base.Vote(request);
 }
        public async Task <IActionResult> Vote(int id, VoteRequest request)
        {
            var createVoteInput = new VoteInput(id, request.ParticipantEmailAddress, request.Options);

            await this.voteInputPort.HandleAsync(createVoteInput, this.votePresenter);

            return(this.votePresenter.ViewModel);
        }
        public Task <VoteResponse> Vote(VoteRequest request)
        {
            if (!TryGetViewer(out var user))
            {
                return(null);
            }

            return(this.game.VoteAsync(user, request.Value));
        }
        public override Task <VoteResponse> AskVote(VoteRequest request, ServerCallContext context)
        {
            Console.WriteLine("Finished Asking for Votes for Partition :" + request.PartitionId);
            var res = _storage.AskVote(request.PartitionId);

            return(Task.FromResult(new VoteResponse {
                Res = res
            }));
        }
 private void sendRequestToAcceptors(LeaderState state, VoteRequest objMessage)
 {
     state.VoteRequestPendingDecisionPerSlot[objMessage.SlotNumber] = new List <MessageSender>();
     foreach (MessageSender acceptor in state.Acceptors)
     {
         state.VoteRequestPendingDecisionPerSlot[objMessage.SlotNumber].Add(acceptor);
         broker.SendMessage(acceptor.UniqueId, objMessage);
     }
 }
Beispiel #21
0
 private static void VerifyRequestInVotesCollection(IEnumerable <Vote> votes, VoteRequest request)
 {
     votes.Should().NotBeNullOrEmpty();
     votes.Should().Contain(x => x.MatchId == request.MatchId &&
                            x.Choice == request.Choice &&
                            x.UserId != null &&
                            x.UserId.NameIdentifier == request.UserIdentifier.NameIdentifier &&
                            x.UserId.AuthenticationType == request.UserIdentifier.AuthenticationType);
 }
Beispiel #22
0
 public Retard(int id, string titre, string description, string file, int idEleve, int idUserConnecte)
 {
     this.id          = id;
     this.titre       = titre;
     this.description = description;
     this.file        = "https://picsum.photos/200";
     this.eleve       = EleveRequest.GetEleveById(idEleve);
     votes            = Vote.GetValueFromList(VoteRequest.getVoteByRetard(id));
     currentUserVote  = DidIVoted(idUserConnecte, id);
 }
 public Task <VoteResponse> VoteAsync(VoteRequest request)
 {
     return(Task.FromResult
            (
                new VoteResponse
     {
         Status = VoteStatus.Success
     }
            ));
 }
Beispiel #24
0
        public int DeleteVote(VoteRequest vote)
        {
            var sqlService = new SqlService();

            sqlService.AddParameter("@LyricsId", vote.LyricsId);
            sqlService.AddParameter("@UserId", vote.VoterId);
            int retId = (int)sqlService.ExecuteScalar("Votes_Delete_ByVoterId");

            return(retId);
        }
        public void Execute(MessageStrategyExecuteArg <IMessage> obj)
        {
            if (!(obj.Message is VoteRequest))
            {
                throw new MessageStrategyException("This strategy shouldn't be invoked with this message type");
            }

            VoteRequest request = obj.Message as VoteRequest;

            sendRequestToAcceptors(obj.RoleState as LeaderState, request);
        }
Beispiel #26
0
        public int VoteUp(VoteRequest vote)
        {
            var sqlService = new SqlService();

            sqlService.AddParameter("@LyricsId", vote.LyricsId);
            sqlService.AddParameter("@UserId", vote.VoterId);

            var retId = (int)sqlService.ExecuteScalar("Votes_Insert");

            return(retId);
        }
        public VotingItemResponse VoteForItem(VoteRequest request, Guid UserID)
        {
            Users user = dbContext.Users.Find(UserID);

            if (user == null)
            {
                throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.USER_NOT_EXIST.ToString());
            }

            VotingItems votingItem = dbContext.VotingItems
                                     .Where(v => v.VotingItemId.Equals(request.VotingItemID) && v.DueDate > DateTime.Now).FirstOrDefault();

            if (votingItem == null)
            {
                throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.VOTING_ITEM_NOT_EXIST_OR_EXPIRED.ToString());
            }

            UserVotes userVote = dbContext.UserVotes
                                 .Where(us => us.UserId.Equals(UserID) && us.VotingItemId.Equals(request.VotingItemID)).FirstOrDefault();

            if (userVote != null)
            {
                throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.USER_ALREADY_VOTED.ToString());
            }

            using (IDbContextTransaction transaction = dbContext.Database.BeginTransaction())
            {
                try
                {
                    UserVotes newVotes = new UserVotes();
                    newVotes.UserId       = UserID;
                    newVotes.VotingItemId = request.VotingItemID;
                    newVotes.CreatedBy    = user.Email;
                    newVotes.UpdatedBy    = user.Email;

                    votingItem.SupportersCount += 1;

                    dbContext.UserVotes.Add(newVotes);
                    dbContext.VotingItems.Update(votingItem);
                    dbContext.SaveChanges();
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw new BusinessLogicException(HttpStatusCode.InternalServerError, ResponseCode.FAILED_TO_VOTE.ToString());
                }
            }

            List <Guid>       listCategories = constructListCategoryID(votingItem.VotingCategories.ToList());
            List <Categories> categories     = dbContext.Categories.Where(cat => listCategories.Contains(cat.CategoryId)).ToList();

            return(constructResponse(votingItem, categories));
        }
 public bool VoteExists(VoteRequest voteRequest)
 {
     using (SqlConnection connection = new SqlConnection(_connectionString))
     {
         var queryString    = @"Select *
                             From Vote
                             Where AchievementId = @AchievementId AND UserId = @UserId";
         var existenceState = connection.Query <int>(queryString, voteRequest).SingleOrDefault();
         return(existenceState > 0);
     }
     throw new Exception("It didn't work.");
 }
        public ActionResult Vote([FromBody] VoteRequest vote)
        {
            var poll = pollDac.Get(it => it.IsClose == false);

            if (poll != null)
            {
                poll.Menus.FirstOrDefault(it => it.Id == vote.FoodId).Voter.Add(vote.Username);

                pollDac.Update(poll);
            }
            return(Ok());
        }
Beispiel #30
0
        /// <summary>
        /// Invokes the VoteRequest event with the specified EventArgs.
        /// </summary>
        /// <param name="e">VoteRequestEventArgs object.</param>
        public static void InvokeVoteRequest(VoteRequestEventArgs e)
        {
            if (InternalVoteRequest != null && e != null)
            {
                InternalVoteRequest.Invoke(e);
            }

            if (VoteRequest != null && e != null)
            {
                VoteRequest.Invoke(e);
            }
        }
Beispiel #31
0
        private VoteResponse generateVoteResponse(AcceptorState state, VoteRequest request, VoteStatus voteStatus)
        {
            VoteResponse response = new VoteResponse
            {
                BallotNumber  = state.BallotNumber,
                MessageSender = state.MessageSender,
                SlotNumber    = request.SlotNumber,
                VoteStatus    = voteStatus
            };

            return(response);
        }
Beispiel #32
0
        /// <summary>
        /// Processes the given vote request.
        /// </summary>
        /// <param name="request">VoteRequest</param>
        void Vote(VoteRequest request)
        {
            var lastLogIndex = this.Logs.Count;
            var lastLogTerm = this.GetLogTermForIndex(lastLogIndex);

            if (request.Term < this.CurrentTerm ||
                (this.VotedFor != null && this.VotedFor != request.CandidateId) ||
                lastLogIndex > request.LastLogIndex ||
                lastLogTerm > request.LastLogTerm)
            {
                Console.WriteLine("\n [Server] " + this.ServerId + " | term " + this.CurrentTerm +
                    " | log " + this.Logs.Count + " | vote false\n");
                this.Send(request.CandidateId, new VoteResponse(this.CurrentTerm, false));
            }
            else
            {
                Console.WriteLine("\n [Server] " + this.ServerId + " | term " + this.CurrentTerm +
                    " | log " + this.Logs.Count + " | vote true\n");

                this.VotedFor = request.CandidateId;
                this.LeaderId = null;

                this.Send(request.CandidateId, new VoteResponse(this.CurrentTerm, true));
            }
        }
Beispiel #33
0
 public void Vote(VoteRequest data)
 {
     Trace.TraceInformation("Vote called" + data.GameId);
     var playerId = Context.User.Identity.GetUserId();
     if (!string.IsNullOrEmpty(playerId) || !string.IsNullOrEmpty(data.Vote))
     {
         try
         {
             var game = GameConstants.Dal.LoadGame<Lee>(data.GameId) as Lee;
             if (game != null) game.RecordPlayerVote(playerId, data.Vote);
             GameConstants.Dal.SaveGame(game);
             var playersToUpdate = game.CurrentRound.PlayerInputs.Where(pi => !string.IsNullOrEmpty(pi.Vote)).Select(pi => pi.PlayerId).ToArray();
             UpdateClients(game, GetUserGroup(playersToUpdate));
         }
         catch (LeeException ex)
         {
             SendMessage(ex.Message);
         }
     }
 }