示例#1
0
        public ElectionYear(ElectionType electionType, int year, double presence, FooData[] fooData)
        {
            FooData      = fooData;
            ElectionType = electionType;
            Year         = year;
            Presence     = presence;

            switch (electionType)
            {
            case ElectionType.Duma:
                DirElectionInfo = DirElectionInfoDuma;
                Result          = Data.Core.Consts.ResultsDuma;
                CaptionDiagram  = CaptionDiagramDuma;
                MainTitle       = MainTitleDuma;
                break;

            case ElectionType.President:
                DirElectionInfo = DirElectionInfoPresident;
                Result          = Data.Core.Consts.ResultsPresident;
                CaptionDiagram  = CaptionDiagramPresident;
                MainTitle       = MainTitlePresident;
                break;

            default:
                throw new Exception("Unknown type");
            }
            PatternExt = String.Format("*{0}.txt", year);
        }
        public Object BeginElection(ServerNode server, ElectionType electionType)
        {
            ManagementCommand command = GetManagementCommand(ConfigurationCommandUtil.MethodName.BeginElection, 1);

            command.Parameters.AddParameter(electionType);
            return(ExecuteCommandOnConfigurationServer(command, true));
        }
示例#3
0
 public static KeyValueViewModel ElectionTypeToKeyValueViewModel(ElectionType electionType)
 {
     return(new KeyValueViewModel
     {
         Id = electionType.Id,
         Name = electionType.Name
     });
 }
        public ActionResult DeleteConfirmed(int id)
        {
            ElectionType electiontype = db.ElectionTypes.Find(id);

            db.ElectionTypes.Remove(electiontype);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#5
0
    public ElectionOutcome IsThereAWinner(ElectionType electionType, string ElectoralCollegeVotes = @"ElectoralCollegeVotes\")
    {
        foreach (KeyValuePair <int, CandidateElectoralCollegeVotes> c in IDCandidateElectoralCollegeVotes)
        {
            c.Value.clearElectoralCollegeVotes();
        }
        if (electionType == ElectionType.InstantRunoff)
        {
            Round++;
        }
        FederalJsonReader reader = new FederalJsonReader();

        foreach (FederalState state in states)
        {
            KeyValuePair <int, List <KeyValuePair <int, int> > > CandidateAndVotes = reader.ReadStatesResults(state.Name);
            if (CandidateAndVotes.Key <= state.Electors)
            {
                foreach (KeyValuePair <int, int> candidateVote in CandidateAndVotes.Value)
                {
                    IDCandidateElectoralCollegeVotes[candidateVote.Key].SetElcetoralCollegeVotes(candidateVote.Value);
                }
            }
            else
            {
                throw new System.InvalidOperationException(state.Name + " is submitting " + CandidateAndVotes.Key.ToString() + " votes instead of " + state.Electors.ToString());
            }
        }
        int mostElectoralVotes = 0;
        List <CandidateElectoralCollegeVotes> outcomeList = new List <CandidateElectoralCollegeVotes>();

        foreach (KeyValuePair <int, CandidateElectoralCollegeVotes> c in IDCandidateElectoralCollegeVotes)
        {
            outcomeList.Add(c.Value);
            if (c.Value.GetElcetoralCollegeVotes() > mostElectoralVotes)
            {
                mostElectoralVotes = c.Value.GetElcetoralCollegeVotes();
            }
        }
        if (mostElectoralVotes > totalElectoralCollegeVotes / 2 || IDCandidateElectoralCollegeVotes.Count == 1)
        {
            int             max            = IDCandidateElectoralCollegeVotes.Aggregate((l, r) => l.Value.GetElcetoralCollegeVotes() > r.Value.GetElcetoralCollegeVotes() ? l : r).Key;
            ElectionOutcome WinningOutcome = new ElectionOutcome();
            WinningOutcome.ElectionType = electionType;
            WinningOutcome.Winner       = IDCandidateElectoralCollegeVotes[max];
            WinningOutcome.outcome      = Outcome.ClearWinner;
            if (electionType == ElectionType.InstantRunoff)
            {
                WinningOutcome.Round = Round;
            }
            WinningOutcome.Results = outcomeList;
            WinningOutcome.totalElectoralCollegeVotes = totalElectoralCollegeVotes;
            return(WinningOutcome);
        }
        else
        {
            return(checkForTie(outcomeList));
        }
    }
        //
        // GET: /Admin/ElectionType/Delete/5

        public ActionResult Delete(int id = 0)
        {
            ElectionType electiontype = db.ElectionTypes.Find(id);

            if (electiontype == null)
            {
                return(HttpNotFound());
            }
            return(View(electiontype));
        }
 public ActionResult Edit(ElectionType electiontype)
 {
     if (ModelState.IsValid)
     {
         db.Entry(electiontype).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(electiontype));
 }
        public ActionResult Create(ElectionType electiontype)
        {
            if (ModelState.IsValid)
            {
                db.ElectionTypes.Add(electiontype);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(electiontype));
        }
示例#9
0
        public ActionResult ElectionTypeCreate(ElectionType model)
        {
            var electionType = new ElectionType()
            {
                Type = model.Type
            };

            context.ElectionType.Add(electionType);
            context.SaveChanges();
            return(RedirectToAction("ElectionType"));
        }
示例#10
0
 private static void RequireType(
     this SimpleValidationResult result,
     Election election,
     ElectionType requiredType
     )
 {
     if (election.Type != requiredType)
     {
         result.Violations.Add(new NotRequiredType(requiredType));
     }
 }
 public Object BeginElection(ServerNode server, ElectionType electionType)
 {
     try
     {
         return(this.service.BeginElection(this.cluster, this.shard, server, electionType));
     }
     catch (System.Exception ex)
     {
     }
     return(null);
 }
        /// <summary>
        /// Authoritative phase:
        /// 1. the requesting node acquires an election lock up at the config server.
        /// 2. It then proceeds with the election conduction where it asks for votes.
        /// 3. Each node checks their world view once more before voting with a yes or no.
        /// 4. Its mandatory for a consensus amongst all the nodes for an election term to be successful.
        /// 5. One negative vote nullifies the current election term. If such is the case, the entire procedure
        /// needs to be repeated.
        /// </summary>
        /// <param name="reportTable"></param>
        /// <returns></returns>
        private ElectionResult HoldElection(LocalShardHeartbeatReporting reportTable, Activity activity)
        {
            ElectionId electionId = null;

            ServerNode requestingNode = new ServerNode();

            requestingNode.Name     = _context.LocalAddress.IpAddress.ToString();
            requestingNode.Priority = (int)_manager.LocalServerPriority;
            ElectionType type = ElectionType.None;

            if (activity == Activity.GeneralElectionsTriggered)
            {
                type = ElectionType.GeneralElections;
            }
            else if (activity == Activity.TakeoverElectionsTriggered)
            {
                type = ElectionType.TakeoverElections;
            }

            Object response = _context.ConfigurationSession.BeginElection(_context.ClusterName.ToLower(), _context.LocalShardName.ToLower(), requestingNode, type);

            if (response != null)
            {
                electionId = response as ElectionId;
                if (electionId != null)
                {
                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsInfoEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Info("ElectionBasedMembershipStrategy", type + " started for node " + _context.LocalAddress);
                    }
                    Address[] activeNodes = reportTable.GetReportTable.Keys.ToArray();

                    return(_manager.ConductElection(electionId, activeNodes, activity));
                }
                else
                {
                    //if we get a database exception from the CS, we wait for a configurable amount of time
                    //before trying to elect a new primary again.
                    if (response is DatabaseException && ((DatabaseException)response).ErrorCode == ErrorCodes.Cluster.PRIMARY_ALREADY_EXISTS)
                    {
                        lock (_mutexOnWait)
                        {
                            Monitor.Wait(_mutexOnWait, _waitTimeout);
                        }
                    }
                }
            }
            if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsDebugEnabled)
            {
                LoggerManager.Instance.ShardLogger.Debug("ElectionBasedMembershipStrategy.HoldElection() ", "Node " + _context.LocalAddress.ToString() + " failed to acquire an election lock on the CS.");
            }
            return(null);
        }
        public IElectionAlgorithm Build(ElectionType electionType)
        {
            switch (electionType)
            {
            case ElectionType.FirstPastThePost:
                return(new FirstPastThePostElectionAlgorithm(this.voteSerializer));

            case ElectionType.InstantRunoff:
                return(new InstantRunoffAlgorithm(this.voteSerializer));

            default:
                throw new Exception($"unrecognized election type: {electionType}");
            }
        }
示例#14
0
        /// <summary>
        /// Converts the value of the specified <see cref="ElectionType"/> to its equivalent <see cref="String"/> representation.
        /// </summary>
        /// <param name="electionType">An election type.</param>
        /// <returns>The <see cref="String"/> equivalent of the value of <paramref name="electionType"/>.</returns>
        public static string ToString(ElectionType electionType)
        {
            switch (electionType)
            {
            case ElectionType.General: return("General");

            case ElectionType.Primary: return("Primary");

            case ElectionType.Runoff: return("Runoff/Rerun");

            case ElectionType.Special: return("Special");

            default: return(string.Empty);
            }
        }
示例#15
0
 public ActionResult ElectionTypeEdit(ElectionType model)
 {
     try
     {
         var electionType = context.ElectionType.Where(x => x.Id == model.Id).FirstOrDefault();
         electionType.Type = model.Type;
         context.SaveChanges();
         return(RedirectToAction("ElectionType"));
     }
     catch (Exception ex)
     {
         ViewBag.errorMessage = ex.Message;
         return(View("error"));
     }
 }
示例#16
0
        /// <summary>
        /// Takes a list of ElectionTypeFormat and builds a list of ElectionTypes
        /// </summary>
        /// <param name="electionTypes">A list of ElectionTypesFormat</param>
        /// <returns>A list of ElectionTypes</returns>
        public static List <ElectionType> BuildElectionTypes(List <ElectionTypeFormat> electionTypes)
        {
            List <ElectionType> electionTypeModels = new List <ElectionType>();

            foreach (ElectionTypeFormat electionType in electionTypes)
            {
                ElectionType electionTypeModel = new ElectionType()
                {
                    InternationalName = electionType.InternationalName,
                    ElectionTypeCode  = electionType.ElectionTypeCode,
                    Elections         = new List <Election>()
                };
                electionTypeModels.Add(electionTypeModel);
            }
            return(electionTypeModels);
        }
示例#17
0
        /// <summary>
        /// Checks whether the given election type is a valid model, and then proceeds to look through any connected models
        /// that are not in the checkedModels set and ensure that they all result in a valid model.
        /// </summary>
        /// <param name="electionType">The model to check.</param>
        /// <param name="checkedModels">A set of already checked models.</param>
        private static void ValidateElectionType(ElectionType electionType, HashSet <int> checkedModels)
        {
            if (electionType == null)
            {
                throw new ArgumentException("ElectionType cannot be null.");
            }

            if (electionType.InternationalName == null)
            {
                throw new ArgumentException("ElectionType.InternationalName cannot be null.");
            }
            if (electionType.InternationalName.Length < 3)
            {
                throw new ArgumentException("ElectionType.InternationalName cannot be shorter than 3 characters.");
            }
            if (electionType.ElectionTypeCode == null)
            {
                throw new ArgumentException("ElectionType.InternationalName cannot be null.");
            }
            if (electionType.ElectionTypeCode.Length < 2)
            {
                throw new ArgumentException("ElectionType.InternationalName cannot be shorter than 2 characters.");
            }

            checkedModels.Add(electionType.GetHashCode());

            if (electionType.Elections != null)
            {
                foreach (Election election in electionType.Elections)
                {
                    if (!checkedModels.Contains(election.GetHashCode()))
                    {
                        ValidateElection(election, checkedModels);
                    }
                }
            }
        }
示例#18
0
 public Object BeginElection(string cluster, string shard, ServerNode server, ElectionType electionType)
 {
     return(_session.BeginElection(cluster, shard, server, electionType));
 }
示例#19
0
 public Election(ElectionId id, ElectionType electionType)
 {
     ElectionId   = id;
     ElectionType = electionType;
 }
示例#20
0
 public VoterBooth(IVoterTerminal voterTerminal, ElectionType electionType)
 {
     this.voterTerminal = voterTerminal;
     this.electionType  = electionType;
 }
示例#21
0
 public Winner(string name, string electionStats, ElectionType electionType)
 {
     this.Name          = name;
     this.ElectionStats = electionStats;
     this.ElectionType  = electionType;
 }
示例#22
0
 public NotRequiredType(ElectionType requiredElectionType)
 {
     RequiredElectionType = requiredElectionType;
 }
示例#23
0
        public void BallotPrompt(ElectionType electionType)
        {
            if (electionType == ElectionType.FirstPastThePost)
            {
                var i = 1;

                Console.WriteLine("Welcome to the election! This is a 'First Past The Post' election model.\nThese are the following candidates to select from:\n" +
                                  string.Join("\n", this.candidateArr.Select(x => $"{i++}: {x}"))
                                  );
                int counter = 1;
                int choice  = 0;
                while (counter < 4)
                {
                    Console.WriteLine("Please select your choice of candidate e.g. 1.");
                    choice = Convert.ToInt32(Console.ReadLine());
                    if (choice < 1 || choice > candidateArr.Length)
                    {
                        Console.WriteLine("Please enter a valid choice.");
                        counter += 1;
                    }
                    else
                    {
                        Console.WriteLine("Thank you for voting!");
                        break;
                    }
                }

                if (counter == 4)
                {
                    Console.WriteLine("You've exhausted your tries. Bye Bye");
                    return;
                }

                FirstPastThePostVote irVote = new FirstPastThePostVote(this.candidateArr[choice - 1]);
                var  jsonVote  = this.voteSerializer.Serialize(irVote);
                var  signature = SignatureProvider.Sign(this.password, this.keyPair, jsonVote.GetBytes());
                Vote vote      = new Vote(this.keyPair.PublicKey.GetBase64String(), jsonVote, signature.GetBase64String());
                this.voteMemoryPool.AddVote(vote);
            }
            else if (electionType == ElectionType.InstantRunoff)
            {
                var i = 1;
                Console.WriteLine("Welcome to the election! This is a 'Instant Runoff' election model.\nThese are the following candidates to select from:\n" +
                                  string.Join("\n", this.candidateArr.Select(x => $"{i++}: {x}"))
                                  );
                // We need to consider when a candidate is not wishing NONE
                int           counter        = 1;
                var           prefs          = "";
                List <string> tokens         = null;
                char[]        charSeparators = new char[] { ',' };
                while (counter < 4)
                {
                    Console.WriteLine("Please type a list in order of candidate preference e.g. 2,1,3.");
                    prefs  = Console.ReadLine();
                    tokens = prefs.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries).ToList();

                    if (tokens.Count > this.candidateArr.Length)
                    {
                        Console.WriteLine("Please enter valid choices in the correct format.");
                        counter += 1;
                    }

                    List <string> rankedOrderedCandidates = new List <string>();

                    for (int j = 0; j < tokens.Count; j++)
                    {
                        rankedOrderedCandidates.Add(this.candidateArr[Convert.ToInt32(tokens[j]) - 1]);
                    }


                    InstantRunoffVote iroVote = new InstantRunoffVote(rankedOrderedCandidates); // make the IR vote
                    var  jsonVote             = this.voteSerializer.Serialize(iroVote);
                    var  signature            = SignatureProvider.Sign(this.password, this.keyPair, jsonVote.GetBytes());
                    Vote vote = new Vote(this.keyPair.PublicKey.GetBase64String(), jsonVote, signature.GetBase64String());
                    this.voteMemoryPool.AddVote(vote);
                    return;
                }

                Console.WriteLine("You've exhausted your tries. Bye Bye");
                return;
            }
        }
示例#24
0
        internal Configuration.Services.ElectionResult ConductElection(ElectionId electionId, Address[] activeNodes, Activity activity)
        {
            Address[] votingNodes = null;
            if (activeNodes == null)
            {
                throw new ArgumentNullException("Active nodes are null");
            }
            Election election = null;

            if (votingNodes == null)
            {
                votingNodes = new Address[activeNodes.Length];
            }
            try
            {
                ElectionType electionType = ElectionType.None;
                if (activity == Activity.GeneralElectionsTriggered)
                {
                    electionType = ElectionType.GeneralElections;
                }
                else if (activity == Activity.TakeoverElectionsTriggered)
                {
                    electionType = ElectionType.TakeoverElections;
                }

                election    = new Election(electionId, electionType);
                votingNodes = activeNodes;
                election.RequestingServerInfo = LocalServerInfo();

                if (election.StartElection(votingNodes))
                {
                    ResponseCollection <object> response = (ResponseCollection <object>)MulticastRequest(election);

                    if (response != null)
                    {
                        foreach (var server in _shard.ActiveChannelsList)
                        {
                            IClusterResponse <object> serverResponse = response.GetResponse(server);
                            if (serverResponse.IsSuccessfull)
                            {
                                if (serverResponse.Value != null)
                                {
                                    ElectionVote vote = serverResponse.Value as ElectionVote;
                                    if (vote != null)
                                    {
                                        election.AddVote(vote);
                                    }
                                }
                            }
                        }
                    }
                    return(election.GetElectionResult());
                }
            }
            catch (Exception e)
            {
                if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.ShardLogger.Error("ElectionManager.ConductElection()", e.ToString());
                }
            }
            return(null);
        }
示例#25
0
        void ballotPrompt(ElectionType electionType)
        {
            if (electionType == ElectionType.FirstPastThePost)
            {
                var i = 1;
                Console.WriteLine("Welcome to the election! These are the following candidates to select from:\n" +
                                  string.Join("\n", this.candidateArr.Select(x => $"{i++}: {x}"))
                                  );
                int counter = 1;
                int choice  = 0;
                while (counter < 4)
                {
                    Console.WriteLine("Please select your choice of candidate e.g. 1.");
                    choice = Convert.ToInt32(Console.ReadLine());
                    if (choice < 1 || choice > candidateArr.Length)
                    {
                        Console.WriteLine("Please enter a valid choice.");
                        counter += 1;
                    }
                    else
                    {
                        break;
                    }
                }

                if (counter == 4)
                {
                    Console.WriteLine("You've exhausted your tries. Bye Bye");
                    return;
                }
                FirstPastThePostVote irVote = new FirstPastThePostVote(this.candidateArr[choice - 1]);
                var  jsonVote  = this.voteSerializer.Serialize(irVote);
                var  signature = SignatureProvider.Sign(this.password, this.keyPair, jsonVote.GetBytes());
                Vote vote      = new Vote(this.keyPair.PublicKey.GetBase64String(), jsonVote, signature.GetBase64String());
            }
            else if (electionType == ElectionType.InstantRunoff)
            {
                var i = 1;
                Console.WriteLine("Welcome to the election! These are the following candidates to select from:\n" +
                                  string.Join("\n", this.candidateArr.Select(x => $"{i++}: {x}"))
                                  );
                // We need to consider when a candidate is not wishing NONE
                int    counter        = 1;
                var    prefs          = "";
                char[] charSeparators = new char[] { ',' };
                while (counter < 4)
                {
                    Console.WriteLine("Please type a list in order of candidate preference e.g. 2, 1, 3.");
                    prefs = Console.ReadLine();
                    string[] tokens = prefs.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
                    if () //TODO validation check of voter input check
                    {
                        Console.WriteLine("Please enter a valid choice.");
                        counter += 1;
                    }
                    else
                    {
                        break;
                    }
                }

                if (counter == 4)
                {
                    Console.WriteLine("You've exhausted your tries. Bye Bye");
                    return;
                }
                InstantRunoffVote iroVote = new InstantRunoffVote(); // make the IR vote
                var  jsonVote             = this.voteSerializer.Serialize(iroVote);
                var  signature            = SignatureProvider.Sign(this.password, this.keyPair, jsonVote.GetBytes());
                Vote vote = new Vote(this.keyPair.PublicKey.GetBase64String(), jsonVote, signature.GetBase64String());
            }
        }
示例#26
0
 public void WriteVoteDocuments(string FolderPath, string StateName, int NumOfVotes, decimal SpoilerEffectCoefficient, ElectionType currentElectionType, List <CandidatePreferences> preferences)
 {
 }
 public Object BeginElection(ServerNode server, ElectionType electionType)
 {
     return(_shardSession.BeginElection(server, electionType));
 }