public async Task <ActionResult> GetVote() { var filePath = _hostingEnvironment.ContentRootPath + "\\AppData\\Fingerprints\\"; var voter = await _context.Voters.FindAsync(User.Identity.Name); var votervotes = await _context.VoterVotes .Include(vv => vv.Vote) .Include(vv => vv.Voter) .Where(vv => vv.VoterId == User.Identity.Name) .Where(vv => vv.Vote.Status == "Running") .Where(vv => !vv.IsVoted) .ToListAsync(); if (votervotes.Count > 0) { var voteRes = new VoteResult() { VoteId = votervotes.ElementAt(0).VoteId, Title = votervotes.ElementAt(0).Vote.Title, Candidates = await _context.Candidates .Where(c => c.VoteId == votervotes.ElementAt(0).VoteId) .Select(c => new CandidateResultRasp { Id = c.Id, ListNumber = c.ListNumber, Name = c.Name, Picture = c.Picture }) .ToListAsync() }; return(Json(voteRes)); } return(Ok(new { result = "You voted for all votes" })); }
public async Task <ActionResult> Vote([FromBody] VoteResult voteResult) { var voter = await _context.Voters.FindAsync(User.Identity.Name); var votervotes = await _context.VoterVotes .Include(vv => vv.Vote) .Include(vv => vv.Voter) .Where(vv => vv.VoterId == User.Identity.Name && vv.Voter.Fingerprint != null) .Where(vv => vv.Vote.Title == voteResult.Title) .Where(vv => vv.Vote.Status == "Running") .FirstOrDefaultAsync(); if (votervotes != null) { try { _context.Candidates.Find(voteResult.Candidates[0].Id).CurrentVoted += 1; votervotes.IsVoted = true; _context.VoterVotes.Update(votervotes); _context.SaveChanges(); return(Ok(new { result = "Thanks a lot" })); } catch (Exception) { return(BadRequest(new { result = "Error in Voting process" })); } } return(Ok(new { result = "You voted in all votes" })); }
public void UpdateVoteResult(VoteResult voteResult) { var existingVoteResult = GetMovieVoteResult(voteResult.MovieId); existingVoteResult.Likes = voteResult.Likes; existingVoteResult.Hates = voteResult.Hates; }
public Models.VoteResults GetModel(VoteResult voteResult) { var electionResult = new VoteResults(); if (voteResult.RankingVoteId != null) { electionResult.RankingVoteId = voteResult.RankingVoteId; electionResult.RankingVoteItem = RankingVoteTicketBuilder.GetModel(voteResult.RankingVote); electionResult.Ranking = voteResult.Ranking; } if (voteResult.SingleVote != null) { electionResult.SingleVoteId = voteResult.SingleVoteId; electionResult.SingleVoteItem = SingleVoteTicketBuilder.GetModel(voteResult.SingleVote); electionResult.VotedYes = voteResult.VoteYes; electionResult.VotedNo = voteResult.VoteNo; } if (voteResult.MultipleVote != null) { electionResult.MultipleVoteId = voteResult.MultipleVoteId; electionResult.MultipleVoteItem = MultiVoteTicketBuilder.GetModel(voteResult.MultipleVote); electionResult.VotedFor = voteResult.VotedFor; } return(electionResult); }
protected void btnDeny_Click(object sender, EventArgs e) { using (var myDB = new canclubEntities1()) { User loggeduser = (User)Session["currentuser"]; int pId = Convert.ToInt32(Request["detail"]); var newvote = new Vote(); newvote.PropId = pId; newvote.UserId = loggeduser.UserId; newvote.IsActive = true; var voteresult = (from x in myDB.VoteResult where (x.PropId == pId) select x).SingleOrDefault(); if (voteresult != null) { voteresult.Result -= 1; myDB.Vote.Add(newvote); myDB.SaveChanges(); } else { var newvoteresult = new VoteResult(); newvoteresult.PropId = pId; newvoteresult.Result = -1; myDB.VoteResult.Add(newvoteresult); myDB.Vote.Add(newvote); myDB.SaveChanges(); } Response.Redirect("~/ProposalDetail.aspx?detail=" + pId); } }
public VoteResult Get() { var results = new VoteResult { }; using (var connection = System.Data.SqlClient.SqlClientFactory.Instance.CreateConnection()) { connection.ConnectionString = ConnectionString; using (var command = connection.CreateCommand()) { command.CommandText = "select vote, count(vote) as votes from votes.dbo.votes group by vote"; command.CommandType = System.Data.CommandType.Text; connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { if ((string)reader["vote"] == "a") { results.VoteA = reader.GetInt32(reader.GetOrdinal("votes")); } else if ((string)reader["vote"] == "b") { results.VoteB = reader.GetInt32(reader.GetOrdinal("votes")); } } } } } return(results); }
private async Task <int> GetCurrentVoteSummary(Guid candidateId) { List <VoteResult> allCandidates = (await voteService.GetVoteSummary(Context, DefaultElectionId)).ToList(); VoteResult vr = allCandidates.FirstOrDefault(n => n.Id == candidateId); return(vr == null ? 0 : vr.Count); }
private void SaveVote(int movieId, int userId, bool like) { var vote = GetMovieVoteForUser(movieId, userId); if (vote == No.Vote) { var newVote = new Vote(userId, movieId); if (like) { newVote.LikeMovie(); } else { newVote.HateMovie(); } _voteRepository.AddVote(newVote); } else { if (like) { vote.LikeMovie(); } else { vote.HateMovie(); } _voteRepository.UpdateVote(vote); } var voteResult = GetMovieVotes(movieId); if (voteResult == No.Votes) { var newVoteResult = new VoteResult(movieId); if (like) { newVoteResult.LikeMovie(); } else { newVoteResult.HateMovie(); } _voteRepository.AddVoteResult(newVoteResult); } else { if (like) { voteResult.LikeMovie(); } else { voteResult.HateMovie(); } _voteRepository.UpdateVoteResult(voteResult); } }
public EzVoteResult( VoteResult result ) { if (result.item != null) { Item = new EzBallot(result.item); } }
public VoteResult Vote(VoteParams voteParams) { Log.WriteWarning("Vote: Username={0},globalId={1},type={2}", SecurityInfo.SessionData.Profile.UserName, voteParams.GlobalId, voteParams.ObjectType); var session = Session; using (var tx = session.BeginSaveTransaction()) { var dbProfile = session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId); bool sendMessage = false; ISortable planFromDb = null; if (voteParams.ObjectType == VoteObject.SupplementCycleDefinition) { planFromDb = session.Get <SupplementCycleDefinition>(voteParams.GlobalId); sendMessage = true; } else if (voteParams.ObjectType == VoteObject.Exercise) { planFromDb = session.Get <Exercise>(voteParams.GlobalId); sendMessage = true; } else if (voteParams.ObjectType == VoteObject.WorkoutPlan) { planFromDb = session.Get <TrainingPlan>(voteParams.GlobalId); sendMessage = true; } else if (voteParams.ObjectType == VoteObject.Supplement) { planFromDb = session.Get <Suplement>(voteParams.GlobalId); } ProfileNotification notificationType = planFromDb.Profile != null ? planFromDb.Profile.Settings.NotificationVoted : ProfileNotification.None; VoteResult result = new VoteResult(); result.Rating = saveRating(SecurityInfo, voteParams, dbProfile, planFromDb); try { //send message only when someone else vote if (planFromDb.Profile != null && planFromDb.Profile != dbProfile && sendMessage) { //SendMessage(notificationType, dbProfile, planFromDb.Profile, messageFormat, messageTypeToSend.Value, "VoteEMailSubject", "VoteEMailMessage", DateTime.Now, dbProfile.UserName, planFromDb.Name, voteParams.UserRating); NewSendMessageEx(notificationType, dbProfile, planFromDb.Profile, "VoteEMailSubject", "VoteEMailMessage", DateTime.Now, dbProfile.UserName, planFromDb.Name, voteParams.UserRating); } } catch (Exception ex) { ExceptionHandler.Default.Process(ex); } tx.Commit(); return(result); } }
/// <summary> /// display vote result /// </summary> /// <param name="className"></param> /// <returns></returns> public List <VoteResult> GetVoteResult(string className) { List <VoteResult> _VoteResultList = new List <VoteResult>(); List <Vote_ItemCatalog> _Vote_ItemCatalogList = className != ""?this._vote_ItemCatalogService.GetAll().Where(x => x.ClassName == className).OrderBy(x => x.Name).ToList(): this._vote_ItemCatalogService.GetAll().OrderBy(x => x.Name).ToList(); List <Vote_Mapping> _Vote_MappingList = className != "" ? this._vote_MappingService.GetAll().Where(x => x.ClassName == className).ToList() : this._vote_MappingService.GetAll().ToList();; List <Login> _LoginList = this._loginService.GetAll().ToList(); foreach (var r in _Vote_ItemCatalogList) { VoteResult _VoteResult = new VoteResult(); _VoteResult.Id = r.Id.ToString(); _VoteResult.ClassName = r.ClassName; _VoteResult.Name = r.Name; _VoteResult.Number = r.Number.ToString(); _VoteResult.Provider = r.Provider; if (_Vote_MappingList.Where(x => x.FK_Vote_ItemCatalogId == r.Id) != null) { _VoteResult.VoteCount = _Vote_MappingList.Where(x => x.FK_Vote_ItemCatalogId == r.Id).Count(); foreach (Vote_Mapping v in _Vote_MappingList.Where(x => x.FK_Vote_ItemCatalogId == r.Id).ToList()) { string _Name = _LoginList.Where(x => x.Id == v.FK_LoginId).First().CustomerName; _VoteResult.Voter = _VoteResult.Voter + _Name + ","; } if (_VoteResult.Voter != null) { _VoteResult.Voter = _VoteResult.Voter.Remove(_VoteResult.Voter.LastIndexOf(","), 1); } } else { _VoteResult.VoteCount = 0; _VoteResult.Voter = ""; } _VoteResultList.Add(_VoteResult); } //high vote show yellow backcolor and same vote count show yellow too if (_VoteResultList.Where(x => Convert.ToInt32(x.VoteCount) > 0).Count() > 0) { _VoteResultList.OrderByDescending(x => x.VoteCount).First().Important = true; int _ImportantVote = _VoteResultList.OrderByDescending(x => x.VoteCount).First().VoteCount; foreach (VoteResult v in _VoteResultList.Where(x => x.VoteCount == _ImportantVote).ToList()) { v.Important = true; } } return(_VoteResultList); }
private void IntegrateResultType(List <string> voterNames, Guid voteId, VoteType voteType) { foreach (var voterName in voterNames) { var parliamentarianId = FindParliamentarianIdFromName(voterName); if (parliamentarianId == null || _context.VoteResults.Any(x => x.ParliamentarianId == parliamentarianId && x.VoteId == voteId)) { continue; } var voteResult = new VoteResult { VoteResultId = Guid.NewGuid(), VoteType = voteType, VoteId = voteId, ParliamentarianId = parliamentarianId.Value }; _context.Add(voteResult); } }
public object Vote(string voteHandlerTypeName, string pollID, string variantIDs, List <AnswerViarint> allVariants, string statBarCSSClass, string liderBarCSSClass, string variantNameCSSClass, string voteCountCSSClass, string additionalParams) { var result = new VoteResult() { PollID = pollID }; var voteHandler = (IVoteHandler)Activator.CreateInstance(Type.GetType(voteHandlerTypeName)); List <string> selectedVariantIDs = new List <string>(); selectedVariantIDs.AddRange(variantIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); string errorMessage = ""; if (voteHandler.VoteCallback(pollID, selectedVariantIDs, additionalParams, out errorMessage)) { result.Success = "1"; foreach (var var in allVariants) { var selectedID = selectedVariantIDs.Find(id => String.Equals(id, var.ID, StringComparison.InvariantCultureIgnoreCase)); if (!String.IsNullOrEmpty(selectedID)) { var.VoteCount++; } } allVariants.ForEach(v => v.Name = HttpUtility.HtmlDecode(v.Name)); result.HTML = RenderAnsweredVariants(allVariants, statBarCSSClass, liderBarCSSClass, variantNameCSSClass, voteCountCSSClass); } else { result.Success = "0"; result.Message = HttpUtility.HtmlEncode(errorMessage); } return(result); }
public object Convert(object value, Type targetType, object parameter, string language) { SolidColorBrush returnBrush = new SolidColorBrush(Color.FromArgb(255, 249, 128, 21)); if (value is VoteResult) { VoteResult voteResultValue = (VoteResult)value; if (voteResultValue == VoteResult.TypicalSplit) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 212, 88, 70)); } else if (voteResultValue == VoteResult.NonTypicalSplit) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 171, 113, 231)); } else if (voteResultValue == VoteResult.LibMinority) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 236, 158, 158)); } else if (voteResultValue == VoteResult.ConMinority) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 116, 159, 244)); } else if (voteResultValue == VoteResult.MixedMinority) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 140, 199, 136)); } else if (voteResultValue == VoteResult.Even) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 158, 158, 158)); } else if (voteResultValue == VoteResult.Unanimous) { returnBrush = new SolidColorBrush(Color.FromArgb(255, 33, 102, 28)); } } return(returnBrush); }
/// <summary> /// Update the database poll record with the selected vote /// and notify any connected clients /// </summary> /// <param name="pollId"></param> /// <param name="question"></param> /// <param name="answer"></param> /// <returns></returns> public async Task <VoteResult> Vote(int pollId, int question, int answer) { VoteResult result = new VoteResult(); if (question < 1 || answer < 1) { result.StatusCode = 400; result.Errors.Add("Question and Answer index values must start at 1"); return(result); } try { // Register the vote in the database Poll updatedPoll = await _pollRepository.VoteAsync(pollId, question, answer); if (updatedPoll != null) { // then notify other connected clients of the poll status using SignalR PollResult message = PollHelper.GetPollResults(updatedPoll); await SendMessageToOthers(MessageTypes.VOTE_RECEIVED, message); result.StatusCode = 200; } else { result.StatusCode = 400; result.Errors.Add("Poll does not exist or is closed"); } } catch (Exception e) { result.StatusCode = 500; result.Errors.Add(e.Message); } return(result); }
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) { return(VoteResult.ToString()); }
public void AddVoteResult(VoteResult newVoteResult) { VoteResults.Add(newVoteResult); }
public async Task Vote(VoteResult result) { result.SelectedTeam = result.VoteChoice.ToString(); await this.Clients.Caller.ReceiveVotingResultAsync(result); }
public void OnVoteResultForced(Database.Model.Vote item, VoteResult forcedResult) { VoteResultForced?.Invoke(this, new VoteResultForcedEventArgs { Item = item, Result = forcedResult }); }
public object Vote(string voteHandlerTypeName, string pollID, string variantIDs, List<AnswerViarint> allVariants, string statBarCSSClass, string liderBarCSSClass, string variantNameCSSClass, string voteCountCSSClass, string additionalParams) { var result = new VoteResult { PollID = pollID }; var voteHandler = (IVoteHandler)Activator.CreateInstance(Type.GetType(voteHandlerTypeName)); var selectedVariantIDs = new List<string>(); selectedVariantIDs.AddRange(variantIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); string errorMessage; if (voteHandler.VoteCallback(pollID, selectedVariantIDs, additionalParams, out errorMessage)) { result.Success = "1"; foreach (var var in allVariants) { var selectedID = selectedVariantIDs.Find(id => String.Equals(id, var.ID, StringComparison.InvariantCultureIgnoreCase)); if (!String.IsNullOrEmpty(selectedID)) var.VoteCount++; } allVariants.ForEach(v => v.Name = HttpUtility.HtmlDecode(v.Name)); result.HTML = RenderAnsweredVariants(allVariants, statBarCSSClass, liderBarCSSClass, variantNameCSSClass); } else { result.Success = "0"; result.Message = HttpUtility.HtmlEncode(errorMessage); } return result; }
public ActionResult VoteResults() { // init count int count = 0; // init model VoteResult model = new VoteResult(); //model.Votes = new List<SingleVote>(); // init candidateScore List <CandidateScore> candidateScores = new List <CandidateScore>(); // get votes var votes = db.Votes.ToArray(); // get candidates var allCandidates = User.GetAllCandidates(); // init candidate scores model.CandidateScores = allCandidates.Select(x => new CandidateScore { Id = x.VoterId, Name = x.FirstName + " " + x.LastName, VoteCount = 0, PositionId = x.PositionId }).ToList(); // init all position ids model.Positions = User.GetAllPositions(); // loop through votes and get each voter details foreach (var item in votes) { // init count count++; // get user var user = db.VoteUsers.Where(x => x.VoterId == item.VoterId).FirstOrDefault(); if (model.CandidateScores.Any(x => x.Id == item.CandidateId)) { var cand = model.CandidateScores.Where(x => x.Id == item.CandidateId).FirstOrDefault(); cand.VoteCount++; } // init singlevm SingleVote vote = new SingleVote { SN = count, VoterName = user.FirstName + " " + user.LastName, VoterPhone = user.Phone, VotedFor = db.VoteUsers.Where(x => x.VoterId == item.CandidateId).Select(x => x.FirstName + " " + x.LastName).FirstOrDefault() }; //model.Votes.Add(vote); } ; model.Name = User.GetName(); return(View("VoteResults", model)); }
/// <summary> /// Creates a window with a matching notice message depending on /// the DatabaseResult type. /// </summary> /// <param name="voteResult">The reason that the ballot was not handed out.</param> public DeclineBallotHandout(VoteResult voteResult) { this.voteResult = voteResult; InitializeComponent(); }
static void Main(string[] args) { var question1 = new Question(); question1.QuestionId = 1; var question2 = new Question(); question2.QuestionId = 2; var user1 = new User(); user1.UserId = 1; var user2 = new User(); user2.UserId = 2; var user3 = new User(); user3.UserId = 3; List <Vote> votes = new List <Vote>() { new Vote() { Question = question2, TimeStamp = DateTime.Today.AddDays(-1), User = user1, VoteId = 1 }, new Vote() { Question = question1, TimeStamp = DateTime.Today, User = user1, VoteId = 2 }, new Vote() { Question = question2, TimeStamp = DateTime.Today.AddDays(-1), User = user2, VoteId = 3 }, new Vote() { Question = question1, TimeStamp = DateTime.Today.AddDays(-1), User = user3, VoteId = 4 } }; // Group Votes by User and then Select only the most recent Vote of // each User var results = from vote in votes where vote.TimeStamp >= DateTime.Today.AddDays(-7) && vote.TimeStamp < DateTime.Today.AddDays(1) group vote by vote.User into g select g.OrderByDescending(v => v.TimeStamp).First(); // Total Users who voted var total = results.Count(); // Group Users' votes by Question foreach (var result in results.GroupBy(v => v.Question.QuestionId)) { var voteResult = new VoteResult() { QuestionId = result.Key, Percentage = ((float)result.Count() / total) * 100.0f }; Console.WriteLine(voteResult.QuestionId); Console.WriteLine(voteResult.Percentage); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { HttpClient client = new HttpClient(); string name = req.Query["votePage"]; var response = await client.GetAsync($"{name}"); var pageContents = await response.Content.ReadAsStringAsync(); log.LogInformation("Fetched Content"); var decodedContent = System.Web.HttpUtility.HtmlDecode(pageContents); var removedHTML = StripHTML(decodedContent); log.LogInformation("Stripped Markup"); string[] lines = removedHTML.Split( new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None ); var finalLines = new List <string>(); foreach (var line in lines) { string trimmedLine = line.TrimStart().TrimEnd(); if (string.IsNullOrEmpty(trimmedLine)) { continue; } finalLines.Add(trimmedLine); } var voteResult = new VoteResult(); string[] split = finalLines[0].Split(new String[] { "Mál:", "Viðgerð:" }, StringSplitOptions.RemoveEmptyEntries); voteResult.Term = int.Parse(Regex.Match(split[0], @"\d+").Value).ToString(); voteResult.Topic = int.Parse(Regex.Match(split[1], @"\d+").Value).ToString(); voteResult.Reading = int.Parse(Regex.Match(split[2], @"\d+").Value).ToString(); DateTime.TryParseExact(finalLines[1], "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime resultDate); voteResult.VoteDate = resultDate; voteResult.Present = int.Parse(Regex.Match(finalLines.FirstOrDefault(x => x.Contains("Present")), @"\d+").Value); voteResult.TotalYes = int.Parse(Regex.Match(finalLines.FirstOrDefault(x => x.Contains("Total JA")), @"\d+").Value); voteResult.TotalNo = int.Parse(Regex.Match(finalLines.FirstOrDefault(x => x.Contains("Total NEI")), @"\d+").Value); voteResult.TotalBlank = int.Parse(Regex.Match(finalLines.FirstOrDefault(x => x.Contains("Total BLANK")), @"\d+").Value); voteResult.TotalAbsent = 33 - voteResult.Present; voteResult.YesVotes = new List <string>(); voteResult.NoVotes = new List <string>(); voteResult.BlankVotes = new List <string>(); voteResult.AbsentVotes = new List <string>(); int counter = finalLines.FindIndex(x => x.Contains("JA:")) + 1; for (int i = counter; i < (counter + voteResult.TotalYes); i++) { voteResult.YesVotes.Add(finalLines[i].Substring(finalLines[i].IndexOf(" ") + 1)); } counter = finalLines.FindIndex(x => x.Contains("NEI:")) + 1; for (int i = counter; i < (counter + voteResult.TotalNo); i++) { voteResult.NoVotes.Add(finalLines[i].Substring(finalLines[i].IndexOf(" ") + 1)); } counter = finalLines.FindIndex(x => x.Contains("BLANK:")) + 1; for (int i = counter; i < (counter + voteResult.TotalBlank); i++) { voteResult.BlankVotes.Add(finalLines[i].Substring(finalLines[i].IndexOf(" ") + 1)); } log.LogInformation("Parsed Votes"); string json = JsonConvert.SerializeObject(voteResult); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }); }