Beispiel #1
0
        public void VoteModel_Empty_Identifier()
        {
            var user    = Users.First().Value;
            var request = new VoteModel(user, VoteType.Up, string.Empty);
            var result  = Validate(request);

            Assert.IsTrue(result.Count == 1);
            Assert.IsTrue(result[0].ErrorMessage == Localization.Errors.EmptyUrlField);
        }
Beispiel #2
0
        public async Task VoteForUserAsync(VoteModel voteModel)
        {
            var refBuilder = new StringBuilder(hostUri);

            refBuilder.Append($"votes/");

            var uri         = new Uri(refBuilder.ToString());
            var jsonContent = await PostAsync(uri, voteModel);
        }
        public PictureVote AddVoteToPicture(VoteModel pictureVote, Picture picture, User user)
        {
            var vote = new PictureVote()
            {
                isPositive = pictureVote.isPositive
            };

            return(this.pictureManager.AddVoteToPicture(vote, picture, user));
        }
        // GET: Block
        #region Index

        /// <summary>
        ///     Decrypt encrypted vote and passing data to blockchain
        /// </summary>
        /// <param name="_id">Block id</param>
        /// <param name="_dataBase64">Encrypted vote</param>
        /// <returns>Success vote</returns>
        public ActionResult Index(int _id, string _dataBase64)
        {
            var user = Session["UserSession"] as UserSession;

            if (user == null)
            {
                return(RedirectToAction("Index", "Vote"));
            }
            if (_dataBase64 == null)
            {
                return(RedirectToAction("SignIn", "Vote"));
            }
            else
            {
                var _data     = Convert.FromBase64String(_dataBase64);
                var _privKey  = Session["PrivateKeySession"] as PrivateKeySession;
                var _voteData = VoteModel.RSADecrypt(_data, _privKey.PrivateKey);

                var _temp  = Session["UserSession"] as UserSession;
                var _user  = db.Users.SingleOrDefault(x => x.Username.Equals(_temp.Username));
                var _block = db.Blocks.SingleOrDefault(x => x.Block_key.Equals(_user.Public_key));

                _block.Data            = _voteData;
                db.Entry(_block).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                var block = new BlockChainModel();
                block.isBlock(_user.Public_key, _block.Data, _block.Prev_ID, _block.Block_key);

                /////////////
                _user.Voted           = 1;
                db.Entry(_user).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                /////////////

                var candidate = db.Blocks.SingleOrDefault(x => x.Block_key == _voteData);
                if (candidate != null)
                {
                    if (candidate.Data == null)
                    {
                        candidate.Data            = "1";
                        db.Entry(candidate).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        candidate.Data            = (int.Parse(candidate.Data) + 1).ToString();
                        db.Entry(candidate).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                return(RedirectToAction("VoteSuccess", "Vote"));
            }
        }
        public ActionResult Upvote([IoCModelBinder(typeof(SetIPAddressModelBinder))] VoteModel voteModel)
        {
            var response = _commentVotingUiService.Upvote(voteModel);

            if (Request.IsAjaxRequest())
            {
                return(Json(response.IsSuccess()));
            }
            return(RedirectToPage(response));
        }
Beispiel #6
0
        public async Task SendVote(VoteModel vote)
        {
            var uri = $"{_apiConfiguration.ApiPath}/vote";

            var content  = new StringContent(JsonConvert.SerializeObject(vote), Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync(uri, content);


            response.EnsureSuccessStatusCode();
        }
Beispiel #7
0
        public bool UpdateVote(int songId, int id, VoteModel newVote)
        {
            var vote = GetVote(songId, id);

            newVote.Id = id;
            if (vote == null)
            {
                throw new NotFoundException($"The Id: {id} does not exist");
            }
            return(repository.UpdateVote(mapper.Map <VoteEntity>(newVote)));
        }
        public async Task <IActionResult> Create(VoteModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                var user = await GetCurrentUser();

                var vote = new Vote
                {
                    ArticleId = model.ArticleId,
                    VotedOn   = _dateTimeService.GetNowUtc(),
                    UserId    = user.Id,
                    VoteType  = model.VoteType
                };

                vote = await _voteService.CreateVote(vote);

                var artVoteCount = await GetVoteCountForArticle(model.ArticleId, model.VoteType);

                var score = (await _dbContext.Articles.FindAsync(model.ArticleId))?.Score;

                var voteResultModel = new
                {
                    model.ArticleId,
                    model.VoteType,
                    VoteCount = artVoteCount,
                    Score     = score
                };

                return(Created("", voteResultModel));
            }
            catch (ApplicationException ex) when(ex.Message == "Article does not exist")
            {
                _logger.LogError(ex, $"Article {model.ArticleId} does not exist");
                return(NotFound("Article not found"));
            }
            catch (ApplicationException ex) when(ex.Message.Contains("does not allow multiple votes"))
            {
                var errorMsg = "Vote type does not allow multiple votes";

                _logger.LogInformation(errorMsg);
                return(StatusCode((int)HttpStatusCode.BadRequest, errorMsg));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating vote", model.ArticleId, model);

                return(StatusCode((int)HttpStatusCode.InternalServerError, "Error creating vote"));
            }
        }
 private void UpdateRating(ObservableCollection <UserModel> members, VoteModel vote)
 {
     foreach (var mem in members)
     {
         if (mem.FullName == vote.Candidate.FullName)
         {
             mem.Votes.Add(vote);
             mem.Rating = (int)mem.Votes.Average(s => s.Rating);
         }
     }
 }
Beispiel #10
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" });
        }
 public override void OnNavigatedTo(INavigationParameters parameters)
 {
     base.OnNavigatedTo(parameters);
     if (parameters != null)
     {
         if (parameters.ContainsKey(nameof(VoteModel)))
         {
             Vote = (VoteModel)parameters[nameof(VoteModel)];
         }
     }
 }
Beispiel #12
0
        public static VoteModel toModel(Vote_DatabaseModel entity)
        {
            VoteModel model = new VoteModel();

            if (entity != null)
            {
                model.username = entity.username;
                model.rating   = entity.rating;
                model.comments = entity.comments;
            }
            return(model);
        }
Beispiel #13
0
        public void Vote(VoteModel model)
        {
            var parameters = new Dictionary <string, string>()
            {
                { "@WinCatReference", model.WinnerCat.Reference },
                { "@WinCatUrl", model.WinnerCat.Url },
                { "@LostCatReference", model.LoserCat.Reference },
                { "@LostCatUrl", model.LoserCat.Url },
            };

            SqlHelper.ExecuteProc <CatSqlObjet>(Cat_Context, "PS_InsertVote", parameters);
        }
Beispiel #14
0
        public ActionResult AddVote()
        {
            VoteModel model = new VoteModel()
            {
                StartTime = DateTime.Now,
                EndTime   = DateTime.Now.AddMonths(1),
                State     = 1
            };

            ViewData["referer"] = SiteUtils.GetAdminRefererCookie();
            return(View(model));
        }
        public async Task <IHttpActionResult> CastVote([FromUri] int tutorialId, [FromBody] VoteModel model)
        {
            if (model == null)
            {
                throw new THQArgumentException(Errors.corruptJson);
            }
            Vote vote = await this._tutorialManager.CastVote(tutorialId, HttpContext.Current.User.Identity.Name, model.Rating, HttpContext.Current.Request.UserHostAddress);

            VoteModel returnModel = Mapper.Map <VoteModel>(vote);

            return(this.Ok(returnModel));
        }
        public async Task <IHttpActionResult> PostVote(VoteModel vote)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.VoteList.Add(_modelFactory.Unwrap(vote));
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = vote.ID }, vote));
        }
Beispiel #17
0
        public async Task <IActionResult> Vote()
        {
            var cats = await _catService.GetCatsForVote();

            var model = new VoteModel
            {
                FirstCat  = cats.Item1,
                SecondCat = cats.Item2,
            };

            return(View(model));
        }
Beispiel #18
0
        public string Vote(DateTime date, string login, string restaurant)
        {
            VoteModel vModel = new VoteModel();
            Vote      vote   = new Vote(restaurant, date, login);

            try
            {
                vModel.Vote(vote);
            }catch (Exception except) { return(except.Message); }

            return("Voto inserido com sucesso!");
        }
Beispiel #19
0
        public async Task <IActionResult> Vote([FromBody] VoteModel model)
        {
            try
            {
                await _catService.SendVote(model);

                return(Json("OK"));
            }
            catch
            {
                return(Json("KO"));
            }
        }
        public override async Task <OperationResult <VoteResponse> > Vote(VoteModel model, CancellationToken ct)
        {
            return(await Task.Run(() =>
            {
                if (!TryReconnectChain(ct))
                {
                    return new OperationResult <VoteResponse>(new ApplicationError(Localization.Errors.EnableConnectToBlockchain));
                }

                var keys = ToKeyArr(model.PostingKey);
                if (keys == null)
                {
                    return new OperationResult <VoteResponse>(new ApplicationError(Localization.Errors.WrongPrivatePostingKey));
                }

                short weigth = 0;
                if (model.Type == VoteType.Up)
                {
                    weigth = 10000;
                }
                if (model.Type == VoteType.Flag)
                {
                    weigth = -10000;
                }

                var op = new VoteOperation(model.Login, model.Author, model.Permlink, weigth);
                var resp = _operationManager.BroadcastOperations(keys, ct, op);

                var result = new OperationResult <VoteResponse>();
                if (!resp.IsError)
                {
                    var dt = DateTime.Now;
                    var content = _operationManager.GetContent(model.Author, model.Permlink, ct);
                    if (!content.IsError)
                    {
                        //Convert Asset type to double
                        result.Result = new VoteResponse(true)
                        {
                            NewTotalPayoutReward = content.Result.TotalPayoutValue + content.Result.CuratorPayoutValue + content.Result.PendingPayoutValue,
                            NetVotes = content.Result.NetVotes,
                            VoteTime = dt
                        };
                    }
                }
                else
                {
                    OnError(resp, result);
                }
                return result;
            }, ct));
        }
Beispiel #21
0
        public HttpResponseMessage PostVoteForPicture(VoteModel vote, int pictureId, string sessionKey)
        {
            try
            {
                var userService = new UserService();
                var user        = userService.GetUserBySessionKey(sessionKey);

                Validator.ValidateUser(user, "Cannot vote for picture");

                var pictureService = new PictureService();
                var picture        = pictureService.GetPictureById(pictureId);

                Validator.ValidatePicture(picture, PICTURE_NOT_FOUND);

                if (picture.Album.User.Id != user.Id)
                {
                    throw new Exception(USER_ACCESS_DENIED);
                }

                var isVoted = picture.Votes.Count(v => v.User.Id == user.Id) > 0;
                if (isVoted)
                {
                    throw new Exception("Already voted..");
                }

                var newVote = pictureService.AddVoteToPicture(vote, picture, user);

                var pictureToReturn = new PictureModel()
                {
                    Comments = from comment in picture.Comments
                               select new CommentModel()
                    {
                        Text      = comment.Text,
                        UserName  = comment.User.UserName,
                        CreatedAt = comment.CreatedAt
                    },
                    CreateDate    = picture.CreateDate,
                    Id            = picture.Id,
                    Url           = picture.Url,
                    Title         = picture.Title,
                    PositiveVotes = picture.Votes.Count(v => v.isPositive == true),
                    NegativeVotes = picture.Votes.Count(v => v.isPositive == false)
                };

                return(this.Request.CreateResponse(HttpStatusCode.OK, pictureToReturn));
            }
            catch (Exception ex)
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
        public VoteModel GetVoteForIndexPage()
        {
            using (var db = new CMSdb(_context))
            {
                VoteModel model = new VoteModel();
                var       query = db.vote_vote
                                  .Where(w => w.f_site == _siteId && w.b_disabled == false)
                                  .Where(w => w.d_date_start <= DateTime.Now && (w.d_date_end >= DateTime.Now || w.d_date_end == null));

                if (query.Any())
                {
                    query = query.OrderByDescending(o => o.d_date_start).OrderByDescending(i => i.b_important);
                    var data = query.Join(db.vote_stat_answer.Where(w => w.f_user == _currentUserId), m => m.id, n => n.f_user, (m, n) => m);
                    if (data.Any())
                    {
                        //данные достаточные для перехода на конкретное голосование
                        model = query.Select(s => new VoteModel
                        {
                            ShowStat = false,
                            Title    = s.c_title,
                            Id       = s.id,
                            Text     = s.c_text
                        }).First();
                    }
                    else
                    {
                        //статистика
                        model = query.Select(s => new VoteModel
                        {
                            ShowStat = true,
                            Title    = s.c_title,
                            Id       = s.id,
                            Text     = s.c_text,
                            ListStat = s.fkids.OrderBy(o => o.n_sort).Select(a => new AnswerAndStat()
                            {
                                Id           = a.id,
                                Variant      = a.c_variant,
                                AllCount     = s.fkstats.Count(),
                                CurrentCount = s.fkstats.Where(e => e.f_answer == a.id).Count()
                            }).ToList(),
                        }).First();
                    }
                    return(model);
                }
                else
                {
                    return(null);
                }
            }
        }
Beispiel #23
0
        public async Task <OperationResult <VoteResponse> > Vote(VoteModel model, CancellationToken ct)
        {
            var results = Validate(model);

            if (results.Any())
            {
                return(new OperationResult <VoteResponse>(new ValidationError(results)));
            }

            var result = await _ditchClient.Vote(model, ct);

            Trace($"post/@{model.Author}/{model.Permlink}/{model.Type.GetDescription()}", model.Login, result.Error, $"@{model.Author}/{model.Permlink}", ct);//.Wait(5000);
            return(result);
        }
Beispiel #24
0
        public ActionResult RemoveVote(int id, VoteModel sessionVoteModel = null)
        {
            var cookie   = controllerInformationProvider.GetVotingCookie();
            var cookieId = cookie.Id;

            messageBus.Send(new DeleteVoteCommand
            {
                SessionId = id,
                CookieId  = cookieId
            });

            controllerInformationProvider.SaveVotingCookie(cookie);
            return(RedirectOrReturnPartialView(id));
        }
Beispiel #25
0
        public async Task <OperationResult <VoteResponse> > Vote(VoteModel model, CancellationToken ct)
        {
            var results = Validate(model);

            if (results.Any())
            {
                return(new OperationResult <VoteResponse>(new ValidationError(string.Join(Environment.NewLine, results.Select(i => i.ErrorMessage)))));
            }

            var result = await _ditchClient.Vote(model, ct);

            Trace($"post/{model.Identifier}/{model.Type.GetDescription()}", model.Login, result.Error, model.Identifier, ct);//.Wait(5000);
            return(result);
        }
Beispiel #26
0
        public VoteModel ReturnVoteData(int newsID, int userID)
        {
            VoteModel Vote = new VoteModel();

            _DataTable = new MySqlVoteData().GetVoteData(newsID, userID);
            foreach (DataRow row in _DataTable.Rows)
            {
                Vote.ID       = Convert.ToInt32(row["ID"]);
                Vote.NewsID   = Convert.ToInt32(row["NewsID"]);
                Vote.UserID   = Convert.ToInt32(row["UserID"]);
                Vote.IsUpvote = Convert.ToBoolean(row["isUpvote"]);
            }
            return(Vote);
        }
Beispiel #27
0
 public ActionResult <bool> UpdateVote(int songId, int id, [FromBody] VoteModel vote)
 {
     try
     {
         return(Ok(service.UpdateVote(songId, id, vote)));
     }
     catch (NotFoundException ex)
     {
         return(NotFound(ex.Message));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
        private void RatingUpdated(object sender, EventArgs args)
        {
            var candidate = (UserModel)sender;
            var vote      = new VoteModel {
                Voter     = CurrentUser,
                Candidate = candidate,
                Rating    = candidate.TempRate
            };
            var navParam = new NavigationParameters
            {
                { nameof(VoteModel), vote }
            };

            NavigationService.NavigateAsync(nameof(MessagePopupPage), navParam);
        }
Beispiel #29
0
        private bool LimitTimeVote(VoteModel vote)
        {
            int hourLimit   = Convert.ToInt32(_configuration["LimitTime:Hour"]);
            int minuteLimit = Convert.ToInt32(_configuration["LimitTime:Minute"]);

            DateTime limitTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                                              DateTime.Now.Day, hourLimit, minuteLimit, 0);

            if (vote.DateVote.TimeOfDay > limitTime.TimeOfDay)
            {
                return(true);
            }

            return(false);
        }
        public async Task <OperationResult <Post> > Vote(VoteModel model, CancellationToken ct)
        {
            var results = Validate(model);

            if (results != null)
            {
                return(new OperationResult <Post>(results));
            }

            var result = await _ditchClient.Vote(model, ct);

            var startDelay = DateTime.Now;

            await Trace($"post/@{model.Author}/{model.Permlink}/{model.Type.GetDescription()}", model.Login, result.Exception, $"@{model.Author}/{model.Permlink}", ct);

            if (!result.IsSuccess)
            {
                return(new OperationResult <Post>(result.Exception));
            }

            OperationResult <Post> postInfo;

            if (model.IsComment) //TODO: << delete when comment update support will added on backend
            {
                postInfo = new OperationResult <Post> {
                    Result = model.Post
                };
            }
            else
            {
                var infoModel = new NamedInfoModel($"@{model.Author}/{model.Permlink}")
                {
                    Login        = model.Login,
                    ShowLowRated = true,
                    ShowNsfw     = true
                };
                postInfo = await GetPostInfo(infoModel, ct);
            }

            var delay = (int)(model.VoteDelay - (DateTime.Now - startDelay).TotalMilliseconds);

            if (delay > 100)
            {
                await Task.Delay(delay, ct);
            }

            return(postInfo);
        }