private void GetResultComplete(VotingResult result, IDictionary <Guid, VoteReceiptStatus> voteReceiptsStatus, Exception exception)
        {
            if (exception == null)
            {
                var table = new StringTable();

                table.SetColumnCount(2);

                table.AddRow(result.Title.Text, string.Empty);
                table.AddRow("Total Ballots", result.TotalBallots.ToString());
                table.AddRow("Invalid Ballots", result.InvalidBallots.ToString());
                table.AddRow("Valid Ballots", result.ValidBallots.ToString());

                foreach (var question in result.Questions)
                {
                    table.AddRow(question.Text.Text, string.Empty);

                    foreach (var option in question.Options)
                    {
                        table.AddRow(option.Text.Text, option.Result.ToString());
                    }
                }

                BotMethods.SendMessage(SendType.Message, Channel, "Pi-Vote: Result of voting:");
                OutTable(table);
            }
            else
            {
                BotMethods.SendMessage(SendType.Message, Channel, "Pi-Vote: " + exception.Message);
            }

            OnCompleted();
        }
        /// <summary>
        ///     Rückgabe der Abstimmungsergebnisse
        /// </summary>
        /// <param name="frameNumber"></param>
        /// <returns></returns>
        public List <VotingResult> GetResult(int frameNumber)
        {
            List <VotingResult>  results      = new List <VotingResult>();
            IEnumerable <Voting> frameVotings = Votings.Where(v => v.FrameNumber == frameNumber);

            // Resultat zusammenzählen
            for (int i = 0; i < PlayerCount; i++)
            {
                VotingResult result = new VotingResult
                {
                    PlayerId = i
                };

                result.GameAction = new GameAction
                {
                    Direction = frameVotings.Where(v => v.PlayerId == i).GroupBy(v => v.GameAction?.Direction)
                                .OrderByDescending(gp => gp.Count()).Select(v => v.Key).FirstOrDefault() ?? Direction.Undefined,
                    Action = frameVotings.Where(v => v.PlayerId == i).GroupBy(v => v.GameAction?.Action)
                             .OrderByDescending(gp => gp.Count()).Select(v => v.Key).FirstOrDefault() ?? Action.Undefined
                };

                results.Add(result);
            }

            return(results);
        }
Beispiel #3
0
 public void SetLastVotingResult(VotingResult votingResult)
 {
     lock (s_votingResultSync)
     {
         LastVotingResult = votingResult;
     }
 }
Beispiel #4
0
 public void ResetLastVotingResult()
 {
     lock (s_votingResultSync)
     {
         LastVotingResult = VotingResult.Empty;
     }
 }
 public static Hash GetHash(this VotingResult votingResult)
 {
     return(HashHelper.ComputeFrom(new VotingResult
     {
         VotingItemId = votingResult.VotingItemId,
         SnapshotNumber = votingResult.SnapshotNumber
     }));
 }
Beispiel #6
0
 public static Hash GetHash(this VotingResult votingResult)
 {
     return(Hash.FromMessage(new VotingResult
     {
         VotingItemId = votingResult.VotingItemId,
         SnapshotNumber = votingResult.SnapshotNumber
     }));
 }
Beispiel #7
0
 public static Hash GetHash(this VotingResult votingResult)
 {
     return(Hash.FromMessage(new VotingResult
     {
         Sponsor = votingResult.Sponsor,
         Topic = votingResult.Topic,
         EpochNumber = votingResult.EpochNumber
     }));
 }
Beispiel #8
0
 private void ScannerManager_SheetProcessed(object sender, SheetEventArgs e)
 {
     _lastVotingResult = e.SheetProcessingSession.VotingResult;
     _lastError        = e.SheetProcessingSession.Error;
     _lastDropResult   = e.SheetProcessingSession.DropResult;
     _lastSheetType    = e.SheetProcessingSession.SheetType;
     _sheetProcessed.GetAccess(this);
     _sheetProcessed.Set();
 }
Beispiel #9
0
        public override Empty Withdraw(WithdrawInput input)
        {
            var votingRecord = State.VotingRecords[input.VoteId];

            Assert(votingRecord != null, "Voting record not found.");

            var votingEventHash = new VotingEvent
            {
                Topic   = votingRecord.Topic,
                Sponsor = votingRecord.Sponsor
            }.GetHash();

            var votingEvent = State.VotingEvents[votingEventHash];

            Assert(votingEvent.CurrentEpoch > votingRecord.EpochNumber,
                   "Cannot withdraw votes of on-going voting event.");

            // Update VotingRecord.
            votingRecord.IsWithdrawn          = true;
            votingRecord.WithdrawTimestamp    = Context.CurrentBlockTime.ToTimestamp();
            State.VotingRecords[input.VoteId] = votingRecord;

            var votingGoingHash = new VotingResult
            {
                Sponsor     = votingRecord.Sponsor,
                Topic       = votingRecord.Topic,
                EpochNumber = votingRecord.EpochNumber
            }.GetHash();

            var votingHistories = UpdateHistoryAfterWithdrawing(votingRecord.Voter, votingEventHash, input.VoteId);

            var votingResult = State.VotingResults[votingGoingHash];

            votingResult.Results[votingRecord.Option] -= votingRecord.Amount;
            if (!votingHistories.Votes[votingEventHash.ToHex()].ActiveVotes.Any())
            {
                votingResult.VotersCount -= 1;
            }

            State.VotingResults[votingGoingHash] = votingResult;

            if (!State.VotingEvents[votingEventHash].Delegated)
            {
                State.TokenContract.Unlock.Send(new UnlockInput
                {
                    From   = votingRecord.Voter,
                    Symbol = votingRecord.Currency,
                    Amount = votingRecord.Amount,
                    LockId = input.VoteId,
                    To     = Context.Self,
                    Usage  = $"Withdraw votes for {votingRecord.Topic}"
                });
            }

            return(new Empty());
        }
Beispiel #10
0
        public override VotingResult GetVotingResult(GetVotingResultInput input)
        {
            var votingResultHash = new VotingResult
            {
                VotingItemId   = input.VotingItemId,
                SnapshotNumber = input.SnapshotNumber
            }.GetHash();

            return(State.VotingResults[votingResultHash]);
        }
Beispiel #11
0
        public override VotingResult GetLatestVotingResult(Hash input)
        {
            var votingItem       = AssertVotingItem(input);
            var votingResultHash = new VotingResult
            {
                VotingItemId   = input,
                SnapshotNumber = votingItem.CurrentSnapshotNumber
            }.GetHash();

            return(State.VotingResults[votingResultHash]);
        }
Beispiel #12
0
 public void Reset()
 {
     lock (s_sync)
     {
         Id      = GenerateId();
         _closed = true;
         _closedEvent.Set();
         ReceivingAllowed = true;
         VotingResult     = null;
         _error           = null;
         ErrorSpecified.Reset();
         DropResult = DropResult.Timeout;
     }
 }
Beispiel #13
0
        public void Calculate <T>(T methodInstance, VotingResult result) where T : IMethod
        {
            List <string> allLists = configuration.Parties
                                     .Concat(configuration.Coalition)
                                     .Concat(configuration.NationalMinority)
                                     .ToList();
            var totalVotes = result.Constituencies.Sum(c => c.Voted);

            foreach (var list in allLists)
            {
                int     listResult    = result.Constituencies.Sum(t => t.Votes.Where(v => v.List == list).Sum(v => v.ReceivedVotes));
                decimal percentResult = (1m * listResult) / totalVotes;
            }
        }
Beispiel #14
0
 public void ReturnListOfLists()
 {
     var voteResult = new VotingResult()
     {
         Constituencies =
         {
             new Constituency("1", 1000, 900)
             {
                 Votes =
                 {
                     new Vote("1", 400), new Vote("1")
                 }
             }
         }
     }
 }
Beispiel #15
0
        public void Open()
        {
            lock (s_sync)
            {
                Id      = GenerateId();
                _closed = false;
                _closedEvent.Reset();
                ReceivingAllowed = true;
                VotingResult     = null;
                _error           = null;
                ErrorSpecified.Reset();
                DropResult = DropResult.Timeout;


                GCSettings.LatencyMode = GCLatencyMode.LowLatency;
            }
        }
Beispiel #16
0
        //TODO: EpochNumber cannot update when CurrentEpoch >= EpochNumber + 1
        public override Empty UpdateEpochNumber(UpdateEpochNumberInput input)
        {
            input.Topic = input.Topic.Trim();

            var votingEvent = AssertVotingEvent(input.Topic, Context.Sender);

            // Update previous voting going information.
            var previousVotingGoingHash = new VotingResult
            {
                Sponsor     = Context.Sender,
                Topic       = input.Topic,
                EpochNumber = votingEvent.CurrentEpoch
            }.GetHash();
            var previousVotingResult = State.VotingResults[previousVotingGoingHash];

            previousVotingResult.EndTimestamp            = Context.CurrentBlockTime.ToTimestamp();
            State.VotingResults[previousVotingGoingHash] = previousVotingResult;

            Assert(votingEvent.CurrentEpoch + 1 == input.EpochNumber, "Can only increase epoch number 1 each time.");
            votingEvent.CurrentEpoch = input.EpochNumber;
            State.VotingEvents[votingEvent.GetHash()] = votingEvent;

            // Initial next voting going information.
            var currentVotingGoingHash = new VotingResult
            {
                Sponsor     = Context.Sender,
                Topic       = input.Topic,
                EpochNumber = input.EpochNumber
            }.GetHash();

            State.VotingResults[currentVotingGoingHash] = new VotingResult
            {
                Sponsor        = Context.Sender,
                Topic          = input.Topic,
                EpochNumber    = input.EpochNumber,
                StartTimestamp = Context.CurrentBlockTime.ToTimestamp()
            };
            return(new Empty());
        }
Beispiel #17
0
        private List <KeyValuePair <VoteKey, bool> > GetVoteKeysForAdding(
            VotingResult votingResult,
            VotingMode votingMode,
            int scannerSerialNumber)
        {
            Logger.LogVerbose(Message.Common_DebugCall);
            var keys       = new List <KeyValuePair <VoteKey, bool> >();
            var sourceData = _electionManager.SourceData;
            var blank      = (0 <= votingResult.BulletinNumber && votingResult.BulletinNumber < sourceData.Blanks.Length)
                            ? sourceData.Blanks[votingResult.BulletinNumber]
                            : null;
            var bulletinVote = new VoteKey
            {
                ScannerSerialNumber = scannerSerialNumber,
                VotingMode          = votingMode,
                BlankId             = (blank != null ? blank.Id : votingResult.BulletinNumber.ToString()),
                BlankType           = votingResult.BlankType,
            };

            if (bulletinVote.BlankType == BlankType.Valid)
            {
                if (votingResult.SectionsMarks == null || votingResult.SectionsValidity == null)
                {
                    bulletinVote.BlankType = BlankType.NoMarks;
                }
                else
                {
                    var invalid = true;
                    for (var sectionIndex = 0;
                         sectionIndex <= votingResult.SectionsMarks.GetUpperBound(0);
                         sectionIndex++)
                    {
                        if (votingResult.SectionsValidity[sectionIndex] &&
                            votingResult.SectionsMarks[sectionIndex] != null &&
                            votingResult.SectionsMarks[sectionIndex].Length > 0)
                        {
                            invalid = false;
                            break;
                        }
                    }
                    if (invalid)
                    {
                        bulletinVote.BlankType = BlankType.NoMarks;
                    }
                }
            }
            if (bulletinVote.BlankType == BlankType.Valid)
            {
                bool isBulletinAdded = false;
                for (var sectionIndex = 0;
                     sectionIndex <= votingResult.SectionsMarks.GetUpperBound(0);
                     sectionIndex++)
                {
                    if (!votingResult.SectionsValidity[sectionIndex])
                    {
                        continue;
                    }
                    for (var markIndex = 0; markIndex < votingResult.SectionsMarks[sectionIndex].Length; markIndex++)
                    {
                        VoteKey candidateVote;
                        if (!isBulletinAdded && markIndex == 0)
                        {
                            candidateVote   = bulletinVote;
                            isBulletinAdded = true;
                        }
                        else
                        {
                            candidateVote = new VoteKey
                            {
                                ScannerSerialNumber = scannerSerialNumber,
                                BlankId             = blank.Id,
                                VotingMode          = votingMode
                            }
                        };
                        candidateVote.ElectionNum = blank.Sections[sectionIndex];
                        candidateVote.CandidateId = sourceData.GetElectionByNum(blank.Sections[sectionIndex]).
                                                    Candidates[votingResult.SectionsMarks[sectionIndex][markIndex]].Id;
                        keys.Add(new KeyValuePair <VoteKey, bool>(candidateVote, false));
                    }
                }
            }
            else
            {
                keys.Add(new KeyValuePair <VoteKey, bool>(bulletinVote, false));
            }
            return(keys);
        }
Beispiel #18
0
 public void AddVotingResult(
     VotingResult votingResult,
     VotingMode votingMode,
     int scannerSerialNumber)
 {
     Logger.LogVerbose(Message.Common_DebugCall);
     lock (s_votingResultSync)
     {
         SetLastVotingResult(votingResult);
         List <KeyValuePair <VoteKey, bool> > voteKeysForAdding = null;
         while (true)
         {
             try
             {
                 if (voteKeysForAdding == null)
                 {
                     voteKeysForAdding = GetVoteKeysForAdding(LastVotingResult, votingMode, scannerSerialNumber);
                 }
                 for (var keyIndex = 0; keyIndex < voteKeysForAdding.Count; keyIndex++)
                 {
                     var item = voteKeysForAdding[keyIndex];
                     if (item.Value)
                     {
                         continue;
                     }
                     var votesCount = 0;
                     try
                     {
                         votesCount = VotingResults.VotesCount(item.Key);
                         VotingResults.AddVote(item.Key);
                     }
                     catch (ThreadAbortException)
                     {
                         Logger.LogWarning(Message.VotingResult_AddVotingResultAbort);
                         Thread.ResetAbort();
                     }
                     catch (Exception ex)
                     {
                         Logger.LogError(Message.VotingResult_AddVotingResultError, ex);
                     }
                     finally
                     {
                         if (VotingResults.VotesCount(item.Key) != votesCount + 1)
                         {
                             keyIndex--;
                         }
                         else
                         {
                             voteKeysForAdding[keyIndex] = new KeyValuePair <VoteKey, bool>(item.Key, true);
                         }
                     }
                 }
                 break;
             }
             catch (ThreadAbortException)
             {
                 Logger.LogWarning(Message.VotingResult_AddVotingResultAbort);
                 Thread.ResetAbort();
             }
             catch (Exception ex)
             {
                 Logger.LogError(Message.VotingResult_AddVotingResultError, ex);
             }
         }
     }
     RaiseStateChanged();
 }
        public List <MsgBase> HandleResoultRequest(MsgBase msg)
        {
            List <MsgBase>         results        = new List <MsgBase>();
            ElectionResultsRequest resultsRequest = msg as ElectionResultsRequest;

            if (resultsRequest.State == "")
            {
                ElectionResults result = new ElectionResults()
                {
                    RequestUID = resultsRequest.Base_MsgUID,
                    Election   = resultsRequest.ElectionID,
                    State      = ""
                };

                Dictionary <string, VotingResult> summaryResults = new Dictionary <string, VotingResult>();
                foreach (var state in m_Votes)
                {
                    foreach (VotesDetails votes in state.Value.Values)
                    {
                        if (summaryResults.ContainsKey(votes.CandidateId))
                        {
                            summaryResults[votes.CandidateId].VoteCount         += votes.VoteCount;
                            summaryResults[votes.CandidateId].ElectoralVotesWon += votes.ElectoralVotesWon;
                        }
                        else
                        {
                            CandidateDetails candidate = m_Candidates[votes.CandidateId];
                            VotingResult     vResult   = new VotingResult()
                            {
                                CandidateId        = votes.CandidateId,
                                CandidateFirstName = candidate.FirstName,
                                CandidateLastName  = candidate.LastName,
                                Party             = candidate.Party,
                                ElectoralVotes    = 348,
                                ElectoralVotesWon = votes.ElectoralVotesWon,
                                VoteCount         = votes.VoteCount,
                                FinalResults      = false
                            };
                            summaryResults.Add(vResult.CandidateId, vResult);
                        }
                    }
                }
                int allVotes = summaryResults.Values.Sum(v => v.VoteCount);

                foreach (VotingResult vote in summaryResults.Values)
                {
                    vote.VotePercent = (vote.VoteCount / allVotes) * 100;
                    result.Voting.Add(vote);
                }

                results.Add(result);
            }
            else if (resultsRequest.State == "All")
            {
                foreach (var state in m_Votes)
                {
                    ElectionResults result = new ElectionResults()
                    {
                        RequestUID = resultsRequest.Base_MsgUID,
                        Election   = resultsRequest.ElectionID,
                        State      = state.Key
                    };

                    foreach (VotesDetails votes in state.Value.Values)
                    {
                        CandidateDetails candidate = m_Candidates[votes.CandidateId];
                        result.Voting.Add(new VotingResult()
                        {
                            CandidateId        = votes.CandidateId,
                            CandidateFirstName = candidate.FirstName,
                            CandidateLastName  = candidate.LastName,
                            Party             = candidate.Party,
                            ElectoralVotes    = votes.ElectoralVotes,
                            ElectoralVotesWon = votes.ElectoralVotesWon,
                            VoteCount         = votes.VoteCount,
                            VotePercent       = votes.VotePercent,
                            FinalResults      = votes.FinalResults
                        });
                    }

                    results.Add(result);
                }
            }
            else
            {
                if (m_Votes.ContainsKey(resultsRequest.State))
                {
                    ElectionResults result = new ElectionResults()
                    {
                        RequestUID = resultsRequest.Base_MsgUID,
                        Election   = resultsRequest.ElectionID,
                        State      = resultsRequest.State
                    };

                    foreach (VotesDetails votes in m_Votes[resultsRequest.State].Values)
                    {
                        CandidateDetails candidate = m_Candidates[votes.CandidateId];
                        result.Voting.Add(new VotingResult()
                        {
                            CandidateId        = votes.CandidateId,
                            CandidateFirstName = candidate.FirstName,
                            CandidateLastName  = candidate.LastName,
                            Party             = candidate.Party,
                            ElectoralVotes    = votes.ElectoralVotes,
                            ElectoralVotesWon = votes.ElectoralVotesWon,
                            VoteCount         = votes.VoteCount,
                            VotePercent       = votes.VotePercent,
                            FinalResults      = votes.FinalResults
                        });
                    }

                    results.Add(result);
                }
                else
                {
                    results.Add(new ElectionResults());
                }
            }

            return(results);
        }