private static ElectionMapWinner CreateElectionMapWinner(int id, Ballot ballot, CandidateResult winner, Turnout turnoutForCountry) { var electionMapWinner = new ElectionMapWinner { Id = id, Winner = new Winner() }; if (ballot.BallotType != BallotType.Referendum) { electionMapWinner.Winner.Name = winner.Name; electionMapWinner.Winner.ShortName = winner.ShortName; electionMapWinner.Winner.Votes = winner.Votes; electionMapWinner.Winner.PartyColor = winner.Party?.Color; } else { if (winner.ShortName == "DA") { electionMapWinner.Winner.Name = "DA"; electionMapWinner.Winner.ShortName = "DA"; electionMapWinner.Winner.Votes = winner.YesVotes; } else { electionMapWinner.Winner.Name = "NU"; electionMapWinner.Winner.ShortName = "NU"; electionMapWinner.Winner.Votes = winner.NoVotes; } } electionMapWinner.ValidVotes = turnoutForCountry.ValidVotes; return(electionMapWinner); }
/// <summary> /// Compares two Ballots /// </summary> /// <param name="a">First Ballot to compare</param> /// <param name="b">Second Ballot to compare</param> /// <returns> <c>True</c> if they contain the same values. /// <c>False</c> if atleast one value is different</returns> private bool AreBallotsEqual(Ballot a, Ballot b) { // compare candidateIds and VoterAdresses if (a.CandidateId == b.CandidateId) { if (this.votingAccount.Address.ToLower().Equals((b.VoterAddress.ToLower()))) { // Compare Rankings for (int i = 0; i < a.Ranking.Count; i++) { BigInteger compA = a.Ranking[i]; if (compA.CompareTo(b.Ranking[i]) == 0) { continue; } else { return(false); } } // Ranking is the same return(true); } } return(false); }
private static Vote CreateVote(Choice choice, Poll poll, Ballot ballot) { return(new Vote() { Choice = choice, Poll = poll, Ballot = ballot, VoteValue = 1 }); }
public IActionResult ViewBallot(int id) { var teams = BuildTeamList(id); Ballot ballot = _context.Ballot.FirstOrDefault(b => b.BallotId == id); Debate debate = _context.Debate.FirstOrDefault(d => d.DebateId == ballot.DebateId); IndividualTeam affirmativeTeam = _context.IndividualTeam.FirstOrDefault(i => i.IndividualTeamId == debate.AffirmativeTeamId); IndividualTeam negativeTeam = _context.IndividualTeam.FirstOrDefault(i => i.IndividualTeamId == debate.NegativeTeamId); var currentUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier).ToString(); Judge judge = _context.Judge.FirstOrDefault(t => t.ApplicationUserId == currentUserId); Round round = _context.Round.FirstOrDefault(r => r.RoundId == ballot.RoundId); JudgesBallotViewModel ballotVM = new JudgesBallotViewModel() { Ballot = ballot, AffirmativeTeam = affirmativeTeam, NegativeTeam = negativeTeam, Round = round, Debate = debate, Judge = judge, Winner = "Team", Loser = "Team", TeamsInRound = teams, }; return(View(ballotVM)); }
private void UpdateLocalityTurnout(Ballot ballot, IGrouping <int, CsvTurnout> csvLocality, List <Turnout> turnoutsForBallot, ApplicationDbContext dbContext) { var dbLocality = _localities.FirstOrDefault(l => l.Siruta == csvLocality.Key); if (dbLocality == null) { return; } var dbCounty = _dbCounties.FirstOrDefault(c => c.CountyId == dbLocality.CountyId); var turnout = turnoutsForBallot.FirstOrDefault(t => t.BallotId == ballot.BallotId && t.Division == ElectionDivision.Locality && t.CountyId == dbLocality.CountyId && t.LocalityId == dbLocality.LocalityId); if (turnout == null) { turnout = CreateTurnout(dbCounty, dbLocality, ballot); } turnout.EligibleVoters = csvLocality.Sum(c => c.EnrolledVoters + c.ComplementaryList); turnout.TotalVotes = csvLocality.Sum(c => c.TotalVotes); turnout.PermanentListsVotes = csvLocality.Sum(c => c.LP); turnout.SpecialListsVotes = csvLocality.Sum(c => c.SpecialLists); turnout.CorrespondenceVotes = csvLocality.Sum(c => c.MobileBallot); dbContext.Update(turnout); }
private int EliminateInvalidBallots(List <AVote> Ballots) { List <AVote> InvalidBallots = new List <AVote>(); foreach (AVote Ballot in Ballots) { int index = 0; List <int> Preferences = this.ExtractBallotPreferences(Ballot.showAllVoteForCandidate()); bool IsEliminated = false; do { if (Preferences.Count(i => i == Preferences[index]) > 1 || Preferences[index] > Preferences.Count || Preferences[index] < 1) { InvalidBallots.Add(Ballot); IsEliminated = true; } index++; } while (!IsEliminated && index < Preferences.Count); } foreach (AVote Ballot in InvalidBallots) { Ballots.Remove(Ballot); } return(InvalidBallots.Count); }
public async Task <LiveElectionInfo> ImportLocalityResults(Ballot ballot, ElectionResultsQuery query) { using (var dbContext = _serviceProvider.CreateScope().ServiceProvider.GetService <ApplicationDbContext>()) { var county = await dbContext.Counties.FirstOrDefaultAsync(c => c.CountyId == query.CountyId); if (county == null) { return(LiveElectionInfo.Default); } var url = _liveElectionUrlBuilder.GetFileUrl(ballot.BallotType, ElectionDivision.County, county.ShortName, null); var stream = await _fileDownloader.Download(url.Value); var pollingSections = await ExtractCandidateResultsFromCsv(stream, new CsvIndexes(CsvMode.National)); var locality = await dbContext.Localities.FirstOrDefaultAsync(l => l.LocalityId == query.LocalityId); var sectionsForLocality = pollingSections.Where(p => p.Siruta == locality.Siruta).ToList(); LiveElectionInfo electionInfo = new LiveElectionInfo(); foreach (var pollingSection in sectionsForLocality) { electionInfo.ValidVotes += pollingSection.ValidVotes; electionInfo.NullVotes += pollingSection.NullVotes; } if (locality == null) { return(LiveElectionInfo.Default); } var candidateResults = sectionsForLocality.SelectMany(s => s.Candidates).ToList(); GroupResults(candidateResults, electionInfo); return(electionInfo); } }
private static async Task <Turnout> RetrieveAggregatedTurnoutForCityHalls(ElectionResultsQuery query, Ballot ballot, ApplicationDbContext dbContext) { IQueryable <Turnout> queryable = dbContext.Turnouts .Where(t => t.BallotId == ballot.BallotId); if (ballot.BallotType == BallotType.CountyCouncilPresident || ballot.BallotType == BallotType.CountyCouncil) { queryable = queryable .Where(t => t.Division == ElectionDivision.County); } else { queryable = queryable .Where(t => t.Division == ElectionDivision.Locality); } if (query.CountyId != null) { queryable = queryable.Where(c => c.CountyId == query.CountyId); } var turnoutsForCounty = await queryable.ToListAsync(); var turnout = AggregateTurnouts(turnoutsForCounty); turnout.BallotId = ballot.BallotId; return(turnout); }
public void WriteIsAborted_AfterWriteWithBallotGreaterThanCurrent() { using (CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().First())) { using (CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().Second())) { using (var testSetup = CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().Third())) { var ballotGenerator = testSetup.BallotGenerator; var localNode = testSetup.LocalNode; var roundBasedRegister = testSetup.RoundBasedRegister; var ballot0 = ballotGenerator.New(localNode.SocketIdentity); var lease = new Lease(localNode.SocketIdentity, DateTime.UtcNow, ownerPayload); var txResult = RepeatUntil(() => roundBasedRegister.Write(ballot0, lease), TxOutcome.Commit); Assert.Equal(TxOutcome.Commit, txResult.TxOutcome); var ballot1 = new Ballot(ballot0.Timestamp - TimeSpan.FromSeconds(10), ballot0.MessageNumber, localNode.SocketIdentity); Assert.True(ballot0 > ballot1); txResult = roundBasedRegister.Write(ballot1, lease); Assert.Equal(TxOutcome.Abort, txResult.TxOutcome); } } } }
static void Main(string[] args) { var ballot = new Ballot("0002"); ballot.Output(); Vote(ballot); }
public async Task <Draw> DrawWinsAsync(Draw draw) { DetermineDrawCanBeDrawn(draw); IEnumerable <Ballot> soldBallots = draw.GetSoldBallots(); int randomIndex = await GenerateRandomNumberAsync(0, soldBallots.Count() - 1); Ballot pickedBallot = soldBallots.ElementAt(randomIndex); Price mainPrice = draw.GetMainPrice(); pickedBallot.WonPrice = mainPrice; Price finalDigitPrice = draw.GetFinalDigitPrice(); IEnumerable <Ballot> finalDigitsBallots = draw.GetSoldBallots(pickedBallot.GetLastDigit()); foreach (var wonBallot in finalDigitsBallots) { if (wonBallot.Number != pickedBallot.Number) { wonBallot.WonPrice = finalDigitPrice; } } draw.RegisterAsDrawn(); return(draw); }
/// </inheritdoc> public async Task <IEnumerable <Ballot> > GenerateBallotsAsync(int numberOfBallots) { int seed = await generateSeedAsync(); _randomWrapper.Seed(seed); var uniqueBallots = new Dictionary <int, Ballot>(); for (int i = 0; i < numberOfBallots; i++) { int ballotNumber = _randomWrapper.Next(_minimalLengthOfBallotNumber, _maximumLengthOfBallotNumber); if (!uniqueBallots.ContainsKey(ballotNumber)) { var ballot = new Ballot { Number = ballotNumber }; uniqueBallots.Add(ballotNumber, ballot); } else { i--; } } return(uniqueBallots.Values.ToList()); }
protected void RepeaterBallots_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) { RepeaterItem item = e.Item; if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem)) { Repeater repeaterCandidates = (Repeater)item.FindControl("RepeaterCandidates"); Ballot ballot = (Ballot)item.DataItem; List <CandidateLine> lines = new List <CandidateLine>(); People candidates = ballot.Candidates; int position = 1; foreach (Person candidate in candidates) { lines.Add(new CandidateLine(position, candidate, documentedCandidatesLookup.ContainsKey(candidate.Identity))); position++; } repeaterCandidates.DataSource = lines; repeaterCandidates.DataBind(); } }
public void RequestedBallots_DoNotBelongToPoll() { var ballotManageGuid = new Guid("1AC3FABB-A077-4EF3-84DC-62074BA8FDF1"); IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>(); var poll = CreatePoll(); IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>(); var ballot = new Ballot() { ManageGuid = ballotManageGuid }; ballots.Add(ballot); polls.Add(poll); IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots); ManageVoterController controller = CreateManageVoteController(contextFactory); var request = new DeleteVotersRequestModel(); var ballotDeleteRequest = new DeleteBallotRequestModel() { BallotManageGuid = ballotManageGuid }; DeleteVoteRequestModel voteRequest = new DeleteVoteRequestModel(); ballotDeleteRequest.VoteDeleteRequests.Add(voteRequest); request.BallotDeleteRequests.Add(ballotDeleteRequest); controller.Delete(PollManageGuid, request); }
private Ballot createScoreBallot(List <CandidateRating> candidateRatingList, BallotInstructions ballotInstructions) { Ballot ballot = new Ballot(ballotInstructions); int i = 0; foreach (CandidateRating candidateRating in candidateRatingList.OrderBy(r => r.rating)) { // End the loop if we have already entered the maximum number allowed to list if (i >= ballotInstructions.maximumCandidatesToScore) { break; } // A round nearest in a 0-10 scale would round 0 to .05 down to 0 and .05 to .15 to 1 // This means twice the range rounds to 1 as rounds to 0 // What we want is 0 to .0909 rounds to 0 and .0909 to .1818 rounds to 1 int score = Convert.ToInt32(candidateRating.rating * (ballotInstructions.maximumScore + 1) - .5); if (score < 0) { score = 0; } if (score > ballotInstructions.maximumScore) { score = ballotInstructions.maximumScore; } ballot.candidateScoreList.Add(new CandidateScore(candidateRating.candidate, score)); i++; } return(ballot); }
public async Task <Election> Insert([FromBody] Election election) { Election result = null; try { await DeleteAllObjects(election); result = await CreateAllNewObjects(election); result = await UpdateAllObjects(election); BlockChain electionChain = await Utils.ConvertToBlockChain <Election>(result); Ballot ballot = new Ballot() { Nonce = electionChain.GetLatestBlock().Nonce, BallotChain = JsonConvert.SerializeObject(electionChain), ElectionId = election.Id }; await this.ballotRepository.Insert(Context, ballot); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } finally { } return(result); }
public void ReadIsAborted_AfterReadWithBallotGreaterThanCurrent() { using (CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().First())) { using (CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().Second())) { using (var testSetup = CreateRoundBasedRegister(GetSynodMembers(), GetSynodMembers().Third())) { testSetup.WaitUntilStarted(); var ballotGenerator = testSetup.BallotGenerator; var localNode = testSetup.LocalNode; var roundBasedRegister = testSetup.RoundBasedRegister; var ballot0 = ballotGenerator.New(localNode.SocketIdentity); var txResult = roundBasedRegister.Read(ballot0); Assert.AreEqual(TxOutcome.Commit, txResult.TxOutcome); var ballot1 = new Ballot(ballot0.Timestamp - TimeSpan.FromSeconds(10), ballot0.MessageNumber, localNode.SocketIdentity); Assert.IsTrue(ballot0 > ballot1); txResult = roundBasedRegister.Read(ballot1); Assert.AreEqual(TxOutcome.Abort, txResult.TxOutcome); } } } }
/// <summary> /// Read ballot_vote.csv. /// </summary> private void ReadBallotVotes(string ballotVoteFile) { if (!File.Exists(ballotVoteFile)) { return; } FileInfo file = new FileInfo(ballotVoteFile); using (TextReader reader = file.OpenText()) { CsvReader csv = new CsvReader(reader); while (csv.Read()) { if (csv.CurrentRecord[4] == "0") { // "choice" column is 0, so this choice was not made. continue; } string ballotKey = csv.CurrentRecord[1]; ballotKey = ballotKey.Split('-')[0]; Ballot ballot = this.Ballots.First(b => b.Aid == ballotKey); BallotChoice choice = ballot.Choices.First(c => c.ChoiceId == long.Parse(csv.CurrentRecord[2])); ballot.AddVote(choice, csv.CurrentRecord); } } }
public void PostOfExistingPendingEmailIsLeftAsPending() { // Arrange Guid manageToken = Guid.NewGuid(); Ballot pendingBallot = new Ballot() { Email = "[email protected]", ManageGuid = manageToken }; _dummyBallots.Add(pendingBallot); _mainPoll.Ballots.Add(pendingBallot); var request = new ManageInvitationRequestModel { Email = "[email protected]", SendInvitation = false, ManageToken = manageToken }; // Act _controller.Post(_mainManageID, new List <ManageInvitationRequestModel> { request }); // Assert Ballot newBallot = _mainPoll.Ballots.FirstOrDefault(); Assert.IsNotNull(newBallot); Assert.AreEqual(manageToken, newBallot.ManageGuid); Assert.AreEqual(Guid.Empty, newBallot.TokenGuid); Assert.AreEqual("[email protected]", newBallot.Email); }
public void ExportPositionsTest() { this.objTest.AddStpBallotBallot(1, new int[] { 5, 6, 7 }, 0, 0); this.objTest.AddStpBallotBallot(2, new int[] { 100 }, 3, 5 + 6 + 7); this.objTest.AddStpContBallot(new int[] { 2, 1, 2 }, 0); this.objTest.AddStpContBallot(new[] { 3 }, 3); this.objTest.AddStpCandBallot(5 + 6 + 7 + 100); // count is the maximum number of candidates in a contest this.objTest.AddStpParty(7); this.objTest.LoadStpParams(); BallotPdfTestObject.SetIdentifierFace( this.objTest.parameters, PaperSide.Front); this.objTest.SetTarget(0.12, 0.08, 0, 0, 0.0035, 100); int selectedId = 1; MatrixPtyCstPaperBallot ballot = new MatrixPtyCstPaperBallot( this.objTest.ballots, this.objTest.contests, this.objTest.candidates, this.objTest.parameters, this.objTest.contlist, this.objTest.candlist, this.objTest.parties, this.objTest.target, selectedId, 1, 1); Ballot doBallot = ballot.ExportPositions(); Assert.IsNotNull(doBallot); Assert.IsNotEmpty(doBallot.Cards); Assert.AreEqual(doBallot.BallotStyleId, selectedId); Assert.IsNotEmpty(doBallot.Cards[0].Faces); Assert.AreEqual(doBallot.Cards[0].Faces[0].Marks.Count, 5 + 6 + 7); List <int> markIds = new List <int>(); bool uniqueIds = true; foreach (Card card in doBallot.Cards) { foreach (Face face in card.Faces) { markIds.Clear(); uniqueIds = true; foreach (Mark mark in face.Marks) { uniqueIds = uniqueIds && (markIds.Contains(mark.Id) == false); markIds.Add(mark.Id); } Assert.IsTrue(uniqueIds); } } }
public void PostOfExistingInvitedEmailIsUntouchedByNewInvitation() { // Arrange Guid manageToken = Guid.NewGuid(); Guid ballotToken = Guid.NewGuid(); Ballot existingBallot = new Ballot() { Email = "[email protected]", ManageGuid = manageToken, TokenGuid = ballotToken }; _dummyBallots.Add(existingBallot); _mainPoll.Ballots.Add(existingBallot); var request = new ManageInvitationRequestModel { Email = "[email protected]", SendInvitation = true, ManageToken = manageToken }; // Act _controller.Post(_mainManageID, new List <ManageInvitationRequestModel> { request }); // Assert Ballot newBallot = _mainPoll.Ballots.FirstOrDefault(); Assert.IsNotNull(newBallot); Assert.AreEqual(manageToken, newBallot.ManageGuid); Assert.AreEqual(ballotToken, newBallot.TokenGuid); Assert.AreEqual("[email protected]", newBallot.Email); }
public void BallotWithNoVotes_IsNotReturned() { var pollManageGuid = new Guid("992E252C-56DB-4E9D-9A31-F5BBA3FA5361"); IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>(); var poll = new Poll() { ManageId = pollManageGuid }; IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>(); var ballot = new Ballot() { ManageGuid = new Guid("96ADD6EF-DFE4-4160-84C5-63EDC3076A1B") }; IDbSet <Vote> votes = DbSetTestHelper.CreateMockDbSet <Vote>(); poll.Ballots.Add(ballot); ballots.Add(ballot); polls.Add(poll); IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots, votes); ManageController controller = CreateManageController(contextFactory); ManagePollRequestResponseModel response = controller.Get(pollManageGuid); Assert.AreEqual(0, response.VotersCount); }
private static ManageVoteResponseModel CreateManageVoteResponse(Ballot ballot) { var model = new ManageVoteResponseModel { BallotManageGuid = ballot.ManageGuid, Votes = new List <VoteResponse>() }; if (ballot.VoterName != null) { model.VoterName = ballot.VoterName; } foreach (Vote vote in ballot.Votes) { var voteResponse = new VoteResponse { ChoiceNumber = vote.Choice.PollChoiceNumber, Value = vote.VoteValue, ChoiceName = vote.Choice.Name }; model.Votes.Add(voteResponse); } return(model); }
public void GetWithInviteesReturnsCountOfInvitees() { // Arrange Ballot emailBallot = new Ballot() { Email = "[email protected]" }; Ballot nullBallot = new Ballot() { Email = null }; Ballot emptyBallot = new Ballot() { Email = "" }; _mainPoll.Ballots = new List <Ballot> { emailBallot, nullBallot, emptyBallot }; // Act var response = _controller.Get(_manageMainUUID); // Assert Assert.AreEqual(1, response.InviteeCount); }
private async Task ImportDiasporaFinalResults(Ballot ballot, List <Turnout> allTurnouts, ApplicationDbContext dbContext, List <Locality> allLocalities, List <Party> parties) { var allCountries = await dbContext.Countries.ToListAsync(); var diasporaElectionInfo = new LiveElectionInfo { Candidates = new List <CandidateResult>() }; foreach (var turnout in allTurnouts.Where(t => t.Division == ElectionDivision.Diaspora_Country)) { var country = allCountries.FirstOrDefault(c => c.Id == turnout.CountryId); var electionInfo = await ImportCountryResults(new ElectionResultsQuery { CountryId = country.Id, Division = ElectionDivision.Diaspora_Country, BallotId = ballot.BallotId }, ballot); diasporaElectionInfo.Candidates.AddRange(JsonConvert.DeserializeObject <List <CandidateResult> >(JsonConvert.SerializeObject(electionInfo.Candidates))); UpdateResults(dbContext, electionInfo, turnout, parties); diasporaElectionInfo.ValidVotes += electionInfo.ValidVotes; diasporaElectionInfo.TotalVotes += turnout.TotalVotes; diasporaElectionInfo.NullVotes += electionInfo.NullVotes; } GroupResults(diasporaElectionInfo.Candidates, diasporaElectionInfo); UpdateResults(dbContext, diasporaElectionInfo, allTurnouts.FirstOrDefault(d => d.Division == ElectionDivision.Diaspora && d.BallotId == ballot.BallotId), parties); }
private void DistributeBallotsByFirstPreference(List <string> Candidates, List <AVote> Ballots) { foreach (AVote Ballot in Ballots) { int Index = 0; foreach (int Value in this.ExtractBallotPreferences(Ballot.showAllVoteForCandidate())) { if (Value == 1) { this.CandidateBallotFragments[Candidates[Index]].Add(Ballot, 2); } Index++; } } Dictionary <string, int> Results = new Dictionary <string, int>(); for (int i = 0; i < Candidates.Count; i++) { Results.Add(Candidates[i], (this.CandidateBallotFragments.ContainsKey(Candidates[i])? this.CandidateBallotFragments[Candidates[i]].Count : 0)); } this.RoundsResults.Add(Results); this.RoundExhaustedBallots.Add(0); this.RoundValidBallots.Add(this.TotalBallots - this.InvalidBallots - this.RoundExhaustedBallots[0]); this.RoundMajority.Add(this.RoundValidBallots[0] / 2 + 1); this.CurrentRound++; this.TotalRounds++; }
private async Task ImportCapitalCityFinalResults(Ballot ballot, List <Turnout> allTurnouts, ApplicationDbContext dbContext, List <Locality> allLocalities, List <Party> parties) { try { var sectors = allLocalities.Where(l => l.CountyId == Consts.CapitalCity); var capitalCityResults = new LiveElectionInfo { Candidates = new List <CandidateResult>() }; foreach (var sector in sectors.Where(s => s.Name.ToLower().StartsWith("toate") == false)) { var index = int.Parse(sector.Name.Split(" ").Last()); var sectorResults = await ImportCapitalCityResults(ballot, index); var sectorTurnout = allTurnouts.FirstOrDefault(t => t.LocalityId == sector.LocalityId && t.BallotId == ballot.BallotId); capitalCityResults.Candidates.AddRange(sectorResults.Candidates); capitalCityResults.TotalVotes += sectorTurnout.TotalVotes; capitalCityResults.ValidVotes += sectorResults.ValidVotes; capitalCityResults.NullVotes += sectorResults.NullVotes; UpdateResults(dbContext, sectorResults, sectorTurnout, parties); } } catch (Exception e) { Console.WriteLine(e); } }
public RoundBasedRegister(IIntercomMessageHub intercomMessageHub, IBallotGenerator ballotGenerator, ISynodConfiguration synodConfig, LeaseConfiguration leaseConfig, ILogger logger) { this.logger = logger; this.synodConfig = synodConfig; this.leaseConfig = leaseConfig; this.intercomMessageHub = intercomMessageHub; intercomMessageHub.Start(); readBallot = ballotGenerator.Null(); writeBallot = ballotGenerator.Null(); listener = intercomMessageHub.Subscribe(); listener.Where(m => Unsafe.Equals(m.Identity, LeaseReadMessage.MessageIdentity)) .Subscribe(OnReadReceived); listener.Where(m => Unsafe.Equals(m.Identity, LeaseWriteMessage.MessageIdentity)) .Subscribe(OnWriteReceived); ackReadStream = listener.Where(m => Unsafe.Equals(m.Identity, LeaseAckReadMessage.MessageIdentity)); nackReadStream = listener.Where(m => Unsafe.Equals(m.Identity, LeaseNackReadMessage.MessageIdentity)); ackWriteStream = listener.Where(m => Unsafe.Equals(m.Identity, LeaseAckWriteMessage.MessageIdentity)); nackWriteStream = listener.Where(m => Unsafe.Equals(m.Identity, LeaseNackWriteMessage.MessageIdentity)); }
private void ImportLocalities(List <County> allCounties, List <Locality> allLocalities, List <Turnout> allTurnouts, List <PollingSection> pollingSectionsByCounty, Ballot ballot, ApplicationDbContext dbContext, List <Party> parties) { LiveElectionInfo localitiesElectionInfo = new LiveElectionInfo { Candidates = new List <CandidateResult>() }; foreach (var county in allCounties.Where(c => c.CountyId != Consts.CapitalCity)) { foreach (var locality in allLocalities.Where(l => l.CountyId == county.CountyId && allTurnouts.Any(t => t.LocalityId == l.LocalityId))) { var sectionsForLocality = pollingSectionsByCounty.Where(p => p.Siruta == locality.Siruta).ToList(); LiveElectionInfo electionInfo = new LiveElectionInfo(); foreach (var pollingSection in sectionsForLocality) { electionInfo.ValidVotes += pollingSection.ValidVotes; electionInfo.NullVotes += pollingSection.NullVotes; } var candidateResults = sectionsForLocality.SelectMany(s => s.Candidates).ToList(); localitiesElectionInfo.Candidates.AddRange(JsonConvert.DeserializeObject <List <CandidateResult> >(JsonConvert.SerializeObject(candidateResults))); GroupResults(candidateResults, electionInfo); var turnout = allTurnouts.FirstOrDefault(t => t.LocalityId == locality.LocalityId && t.BallotId == ballot.BallotId); UpdateResults(dbContext, electionInfo, turnout, parties); localitiesElectionInfo.ValidVotes += electionInfo.ValidVotes; localitiesElectionInfo.TotalVotes += electionInfo.TotalVotes; localitiesElectionInfo.NullVotes += electionInfo.NullVotes; } } }
public void BallotSaver(DbAction action, Ballot ballot) { switch (action) { case DbAction.Attach: //if (!_isInTest) { if (SharedDbContext.Ballot.Local.All(l => l.Id != ballot.Id)) { SharedDbContext.Ballot.Attach(ballot); } } break; case DbAction.Save: //if (!_isInTest) { //new BallotCacher(SharedDbContext).UpdateItemAndSaveCache(ballot); } break; default: throw new ArgumentOutOfRangeException("action"); } }
private static CandidateResult CreateCandidateResult(Vote vote, Ballot ballot, List <Party> parties, int?localityId, int?countyId, ElectionDivision division = ElectionDivision.Locality) { var candidateResult = new CandidateResult { BallotId = ballot.BallotId, Division = division, Votes = vote.Votes, Name = vote.Candidate, CountyId = countyId, LocalityId = localityId, Seats1 = vote.Mandates1, Seats2 = vote.Mandates2 }; var partyName = ballot.BallotType == BallotType.LocalCouncil || ballot.BallotType == BallotType.CountyCouncil ? vote.Candidate : vote.Party; if (partyName.IsNotEmpty()) { candidateResult.PartyId = parties.FirstOrDefault(p => p.Alias.ContainsString(partyName))?.Id ?? parties.FirstOrDefault(p => p.Name.ContainsString(partyName))?.Id; } candidateResult.PartyName = partyName; if (candidateResult.PartyId == null && partyName.IsNotEmpty()) { candidateResult.ShortName = partyName.GetPartyShortName(null); } return(candidateResult); }
public LeaderElectionMessageFilter(Ballot ballot, Func<IMessage, ILeaseMessage> payload, ISynodConfiguration synodConfig) { this.ballot = ballot; this.synodConfig = synodConfig; this.payload = payload; }
public void Vote(Ballot ballot) { if (DateTime.Now.Second%2 == 0) { ballot.Fatal("ERROR: This should error every other second"); return; } ballot.Healthy(); }
public void Vote(Ballot ballot) { using(var c = new ServiceController(_serviceName)) { if(c.Status != ServiceControllerStatus.Running) { ballot.Fatal("Service Controller reports '{0}' is not in the running state.".FormatWith(_serviceName)); return; } ballot.Healthy(); } }
public static int DeleteBallot(Ballot b) { var sql = CreateCommand(); sql.CommandText = @"DELETE FROM ballots WHERE id = ?id"; var p0 = sql.CreateParameter(); p0.ParameterName = "?id"; p0.Value = b.Id; sql.Parameters.Add(p0); return ExecuteNonQuery(sql); }
public static void PostBallot(Ballot ballot) { var motion = ballot.Motion; if (motion.PostUrl == "") { return; } var reddit = new RedditSharp.Reddit(Config.RedditUser, Config.RedditPass, true); var post = reddit.GetPost(new Uri(motion.PostUrl)); post.Comment("###" + ballot.Moderator.Name + "###" + Environment.NewLine + "*****" + Environment.NewLine + DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss") + @" \(UTC\) : *" + ballot.Choice.ToString() + "*" + Environment.NewLine ); }
public static Ballot GetBallot(int id) { var result = new Ballot(); var sql = CreateCommand(); sql.CommandText = @"SELECT id,motionId,moderatorId,choice FROM ballots WHERE id = ?id"; var pId = sql.CreateParameter(); pId.ParameterName = "?id"; pId.Value = id; sql.Parameters.Add(pId); var rs = ExecuteReader(sql); result.Choice = (Choice)rs.GetInt32(3); result.Id = rs.GetInt32(0); result.Moderator = GetModerator(rs.GetInt32(2)); result.Motion = GetMotion(rs.GetInt32(1)); return result; }
private void OnWriteReceived(IMessage message) { var payload = message.GetPayload<LeaseWriteMessage>(); var ballot = new Ballot(new DateTime(payload.Ballot.Timestamp, DateTimeKind.Utc), payload.Ballot.MessageNumber, payload.Ballot.Identity); IMessage response; if (writeBallot > ballot || readBallot > ballot) { LogNackWrite(ballot); response = Message.Create(new LeaseNackWriteMessage { Ballot = payload.Ballot, SenderUri = synodConfig.LocalNode.Uri.ToSocketAddress() }, LeaseNackWriteMessage.MessageIdentity); } else { LogAckWrite(ballot); writeBallot = ballot; var ownerEndpoint = new OwnerEndpoint { UnicastUri = new Uri(payload.Lease.OwnerEndpoint.UnicastUri), MulticastUri = new Uri(payload.Lease.OwnerEndpoint.MulticastUri) }; lease = new Lease(payload.Lease.Identity, ownerEndpoint, new DateTime(payload.Lease.ExpiresAt, DateTimeKind.Utc)); response = Message.Create(new LeaseAckWriteMessage { Ballot = payload.Ballot, SenderUri = synodConfig.LocalNode.Uri.ToSocketAddress() }, LeaseAckWriteMessage.MessageIdentity); } intercomMessageHub.Send(response, payload.SenderIdentity); }
public static int InsertBallot(Ballot b) { var sql = CreateCommand(); sql.CommandText = @"INSERT INTO ballots (createDt,motionId,moderatorId,choice) VALUES (DATE('now'),@motionId,@moderatorId,@choice);"; var p0 = sql.CreateParameter(); p0.ParameterName = "@motionId"; p0.Value = b.Motion.Id; sql.Parameters.Add(p0); var p1 = sql.CreateParameter(); p1.ParameterName = "@moderatorId"; p1.Value = b.Moderator.Id; sql.Parameters.Add(p1); var p2 = sql.CreateParameter(); p2.ParameterName = "@choice"; p2.Value = (int)b.Choice; sql.Parameters.Add(p2); b.Id = ExecuteNonQuery(sql); return b.Id; }
private void CommandCast(ChatCommand cmd, Moderator mod) { var usage = "usage: $vote cast [choice]{ yes | no | abstain } [motion id] "; if (cmd.Args.Length == 0) { WriteUser(usage, mod,cmd.Source); return; } var stuff = cmd.Args.Split(' '); if (stuff.GetUpperBound(0) < 1) { WriteUser(usage, mod,cmd.Source); return; } var id = -1; try { id = Int32.Parse(stuff[1]); } catch { WriteUser(usage, mod,cmd.Source); return; } Choice c = Choice.Abstain; bool error = false; switch (stuff[0].ToLower()) { case "yes": case "y": case "+1": case "yay": case "yae": case "yea": case "oui": case "si": case "ja": case "da": c = Choice.Yes; break; case "no": case "n": case "-1": case "nae": case "nay": case "non": case "nein": case "neit": c = Choice.No; break; case "abstain": case "abs": case "0": c = Choice.Abstain; break; default: error = true; break; } if (error) { WriteUser(usage, mod); return; } WriteUser("Submitting ballot. Please wait.",mod,cmd.Source); var motion = Motion.GetMotion(id); var b = new Ballot(); b.Choice = c; b.Moderator = mod; b.Motion = motion; b.Insert(); WriteUser("Your ballot has been recorded", mod,cmd.Source); }
public LeaseTxResult Read(Ballot ballot) { var ackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseAckReadMessage>(), synodConfig); var nackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseNackReadMessage>(), synodConfig); var awaitableAckFilter = new AwaitableMessageStreamFilter(ackFilter.Match, m => m.GetPayload<LeaseAckReadMessage>(), GetQuorum()); var awaitableNackFilter = new AwaitableMessageStreamFilter(nackFilter.Match, m => m.GetPayload<LeaseNackReadMessage>(), GetQuorum()); using (ackReadStream.Subscribe(awaitableAckFilter)) { using (nackReadStream.Subscribe(awaitableNackFilter)) { var message = CreateReadMessage(ballot); intercomMessageHub.Broadcast(message); var index = WaitHandle.WaitAny(new[] {awaitableAckFilter.Filtered, awaitableNackFilter.Filtered}, leaseConfig.NodeResponseTimeout); if (ReadNotAcknowledged(index)) { return new LeaseTxResult {TxOutcome = TxOutcome.Abort}; } var lease = awaitableAckFilter .MessageStream .Select(m => m.GetPayload<LeaseAckReadMessage>()) .Max(p => CreateLastWrittenLease(p)) .Lease; return new LeaseTxResult { TxOutcome = TxOutcome.Commit, Lease = lease }; } } }
public LeaseTxResult Write(Ballot ballot, Lease lease) { var ackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseAckWriteMessage>(), synodConfig); var nackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseNackWriteMessage>(), synodConfig); var awaitableAckFilter = new AwaitableMessageStreamFilter(ackFilter.Match, m => m.GetPayload<LeaseAckWriteMessage>(), GetQuorum()); var awaitableNackFilter = new AwaitableMessageStreamFilter(nackFilter.Match, m => m.GetPayload<LeaseNackWriteMessage>(), GetQuorum()); using (ackWriteStream.Subscribe(awaitableAckFilter)) { using (nackWriteStream.Subscribe(awaitableNackFilter)) { intercomMessageHub.Broadcast(CreateWriteMessage(ballot, lease)); var index = WaitHandle.WaitAny(new[] {awaitableAckFilter.Filtered, awaitableNackFilter.Filtered}, leaseConfig.NodeResponseTimeout); if (ReadNotAcknowledged(index)) { return new LeaseTxResult {TxOutcome = TxOutcome.Abort}; } return new LeaseTxResult { TxOutcome = TxOutcome.Commit, // NOTE: needed??? Lease = lease }; } } }
private IMessage CreateWriteMessage(Ballot ballot, Lease lease) { return Message.Create(new LeaseWriteMessage { Ballot = new Messages.Ballot { Identity = ballot.Identity, Timestamp = ballot.Timestamp.Ticks, MessageNumber = ballot.MessageNumber }, Lease = new Messages.Lease { Identity = lease.OwnerIdentity, ExpiresAt = lease.ExpiresAt.Ticks, OwnerEndpoint = new Messages.OwnerEndpoint { UnicastUri = lease.OwnerEndpoint.UnicastUri.ToSocketAddress(), MulticastUri = lease.OwnerEndpoint.MulticastUri.ToSocketAddress() } } }, LeaseWriteMessage.MessageIdentity); }
private IMessage CreateReadMessage(Ballot ballot) { return Message.Create(new LeaseReadMessage { Ballot = new Messages.Ballot { Identity = ballot.Identity, Timestamp = ballot.Timestamp.Ticks, MessageNumber = ballot.MessageNumber } }, LeaseReadMessage.MessageIdentity); }
private void OnReadReceived(IMessage message) { var payload = message.GetPayload<LeaseReadMessage>(); var ballot = new Ballot(new DateTime(payload.Ballot.Timestamp, DateTimeKind.Utc), payload.Ballot.MessageNumber, payload.Ballot.Identity); IMessage response; if (writeBallot >= ballot || readBallot >= ballot) { LogNackRead(ballot); response = Message.Create(new LeaseNackReadMessage { Ballot = payload.Ballot, SenderUri = synodConfig.LocalNode.Uri.ToSocketAddress() }, LeaseNackReadMessage.MessageIdentity); } else { LogAckRead(ballot); readBallot = ballot; response = CreateLeaseAckReadMessage(payload); } intercomMessageHub.Send(response, payload.SenderIdentity); }