public void Save(Voter obj)
 {
     if (obj.Id == 0)
         context.Entry(obj).State = System.Data.Entity.EntityState.Added;
     else
         context.Entry(obj).State = System.Data.Entity.EntityState.Modified;
     context.SaveChanges();
 }
 public string Vote(Voter aVoter)
 {
     if (!HisThisEmail(aVoter.Email))
        {
        return "This Email is not recorded.";
        }
        return aVoterGateway.Vote(aVoter);
 }
 private void castButton_Click(object sender, EventArgs e)
 {
     aVoter = new Voter();
     aVoter.Email = votersEmailAddressTextBox.Text;
     Candidate aCandidate = (Candidate)selectSymbolOfCandidateComboBox.SelectedItem;
     aVoter.CandidateId = aCandidate.CandidateID;
     string msg = aVoterBll.Vote(aVoter);
     MessageBox.Show(msg);
 }
Exemple #4
0
 public Vote(VoteEvent myVoteEvent, Voter v, int uid)
 {
     this.v = v;
     this.c = myVoteEvent.GetCandidateByUid(uid);
     if (this.c == null)
     {
         Log myLog = new Log("The Candidate is null");
         LogStore.LogList.Add(myLog);
     }
 }
Exemple #5
0
 public bool Equals(Voter obj)
 {
     if (this.GetUid() == obj.GetUid())
     {
         return true;
     }
     else
     {
         return false;
     }
 }
 public string Vote(Voter aVoter)
 {
     connection.Open();
     string query = string.Format("INSERT INTO t_Elect VALUES ('{0}','{1}')", aVoter.CandidateId, aVoter.ID);
     SqlCommand command = new SqlCommand(query, connection);
     int affectedRow = command.ExecuteNonQuery();
     connection.Close();
     if (affectedRow > 0)
         return "You have Voted";
     return "Error";
 }
        public override IEnumerable <(string, int, RankedBallot)> GetPotentialStrategicBallots(List <List <int> > ranking, Voter v)
        {
            // "Favorite Betrayal": sort those preferred to winner by reverse elimination order, not utility order. Tiebreak by utility, at least!
            // This will hopefully eliminate less-preferred candidates sooner and help more-preferred candidates survive the runoffs
            var winnerEv = ranking[0].Min(w => v.Utilities[w]);
            var max      = v.Utilities.Max();

            if (winnerEv != max)
            {
                yield return("Pre-Winner Truncation", 1, new RankedBallot(v.CandidateCount, v.Ranking
                                                                          .TakeWhile(x => v.Utilities[x[0]] > winnerEv)));
            }

            yield return("Post-Winner Truncation", 1, new RankedBallot(v.CandidateCount, v.Ranking
                                                                       .TakeWhile(x => v.Utilities[x[0]] >= winnerEv)));

            if (v.Utilities.Count(u => u > winnerEv) < 2)
            {
                yield break;
            }

            var candidates = v.Utilities
                             .Select((u, c) => (
                                         Candidate: c,
                                         Utility: u,
                                         Rank: ranking.FindIndex(tier => tier.Contains(c))))
                             .ToLookup(a => a.Utility > winnerEv);

            yield return("Favorite Betrayal", 1, new RankedBallot(v.CandidateCount,
                                                                  candidates[true]
                                                                  .GroupBy(c => c.Rank)
                                                                  .OrderByDescending(gp => gp.Key)
                                                                  .Concat(
                                                                      candidates[false]
                                                                      .GroupBy(c => c.Utility)
                                                                      .OrderByDescending(gp => gp.Key)
                                                                      )
                                                                  .Select(gp => gp.Select(a => a.Candidate).ToList())
                                                                  .ToList()));
        }
Exemple #8
0
        private void AddNewRecord()
        {
            if (ValidateFormInputs())
            {
                try
                {
                    var cnicCount = db.Voters.Where(x => x.CNIC == txtCNIC1.Text).ToList().Count;
                    //var voterNoCount = db.Voters.Where(x => x.voter_no == txtVoteNo.Text).ToList().Count();

                    if (cnicCount < 1)
                    {
                        //if (voterNoCount < 1)
                        //{
                        Voter voter = new Voter();

                        voter.name = txtName.Text;

                        if (!String.IsNullOrEmpty(txtFather.Text))
                        {
                            voter.father_name = txtFather.Text;
                        }

                        string cnic = txtCNIC1.Text + txtCNIC2.Text + txtCNIC3.Text;
                        voter.CNIC = cnic;

                        if (!String.IsNullOrEmpty(txtVoteNo.Text))
                        {
                            voter.voter_no = txtVoteNo.Text;
                        }
                        if (!String.IsNullOrEmpty(txtFamily.Text))
                        {
                            voter.family = txtFamily.Text;
                        }
                        if (!String.IsNullOrEmpty(txtPhoneNo.Text))
                        {
                            voter.phone = txtPhoneNo.Text;
                        }
                        if (!String.IsNullOrEmpty(txtAddress.Text))
                        {
                            voter.address = txtAddress.Text;
                        }
                        if (!String.IsNullOrEmpty(txtPollingStation.Text))
                        {
                            voter.polling_station = txtPollingStation.Text;
                        }
                        if (!String.IsNullOrEmpty(txtCaste.Text))
                        {
                            voter.Caste = txtCaste.Text;
                        }

                        db.Voters.Add(voter);
                        db.SaveChanges();

                        ResetFormFields();

                        MessageBox.Show("Success");
                        //}
                        //else
                        //{
                        //    MessageBox.Show("Voter Number: " + txtVoteNo.Text + " already exist");
                        //}
                    }
                    else
                    {
                        MessageBox.Show("CNIC: " + txtCNIC1.Text + " already exist");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
        }
 public VoterFacade(Voter voter)
 {
     _voter = voter;
 }
Exemple #10
0
        public ActionResult Edit(Voter voter)
        {
            if (ModelState.IsValid)
            {
                var refer       = db.Refers.Find(voter.ReferId);
                var city        = db.Cities.Find(Convert.ToInt32(voter.CityId));
                var department  = db.Departments.Find(Convert.ToInt32(voter.DepartmentId));
                var country     = db.Countries.Find(Convert.ToInt32(voter.CountryId));
                var comune      = db.Communes.Find(Convert.ToInt32(voter.CommuneId));
                var votingPlace = db.VotingPlaces.Find(Convert.ToInt32(voter.VotingPlaceId));
                if (voter.PerfilId == 1)
                {
                    voter.BossId = refer.UserId;
                }
                if (voter.PerfilId == 2)
                {
                    voter.LinkId = refer.UserId;
                }
                if (voter.PerfilId == 3)
                {
                    voter.CoordinatorId = refer.UserId;
                }
                if (voter.PerfilId == 4)
                {
                    voter.LeaderId = refer.UserId;
                }
                voter.ReferId         = refer.ReferId;
                voter.Fname           = string.Format("{0} {1}", voter.FirstName, voter.LastName);
                voter.CityId          = city.Name;
                voter.DepartmentId    = department.Name;
                voter.CountryId       = country.Name;
                voter.CommuneId       = comune.Name;
                voter.VotingPlaceId   = votingPlace.Name;
                db.Entry(voter).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null &&
                        ex.InnerException.InnerException != null &&
                        ex.InnerException.InnerException.Message.Contains("_Index"))
                    {
                        ModelState.AddModelError(string.Empty, "Ya existe un Registro con esa descripción");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.ToString());
                    }
                }
            }
            ViewBag.CityId        = new SelectList(CombosHelper.GetCities(), "CityId", "Name", voter.CityId);
            ViewBag.CommuneId     = new SelectList(CombosHelper.GetCommunes(), "CommuneId", "Name", voter.CommuneId);
            ViewBag.CountryId     = new SelectList(CombosHelper.GetCountries(), "CountryId", "Name", voter.CountryId);
            ViewBag.DepartmentId  = new SelectList(CombosHelper.GetDepartments(), "DepartmentId", "Name", voter.DepartmentId);
            ViewBag.VotingPlaceId = new SelectList(CombosHelper.GetVotingPlaces(), "VotingPlaceId", "Name", voter.VotingPlaceId);
            ViewBag.PerfilId      = new SelectList(
                CombosHelper.GetUser(),
                "userId",
                "name",
                voter.PerfilId);

            ViewBag.ReferId = new SelectList(
                CombosHelper.GetRefer(),
                "ReferId",
                "FullName",
                voter.ReferId);
            return(View(voter));
        }
Exemple #11
0
        public async Task <IActionResult> Index_CodeBehind(LanguagePreference languagePreference, string revote)
        {
            string voteAnswerChoices = "";

            if (HttpContext.Session.GetString("ControlNumber") == null)
            {
                return(await Task.Run <IActionResult>(() => { return RedirectToAction("Login"); }));
            }

            List <VoteSubmission> voteSubmissions = _context.votesubmission.AsQueryable().ToList();

            string controlNumber = HttpContext.Session.GetString("ControlNumber");

            SHOAccount shoaccount = _context.shoaccounts.AsQueryable().Where(sho => sho.ControlNumber == controlNumber).FirstOrDefault();

            if (shoaccount.maskedVoters != null && shoaccount.maskedVoters.Any())
            {
                List <string> voteSessionIds     = new List <string>();
                string        voteSessionId      = "";
                string        firstVoteSessionId = "";
                bool          allTheSame         = true;
                for (int x = 0; x < shoaccount.maskedVoters.Count(); x++)
                {
                    VoteMask voteMask = shoaccount.maskedVoters[x];
                    Voter    voter1   = await _blockchainContext.getVoteAnswersByVoterId(voteMask.voterId);

                    voteAnswerChoices = voter1.voteSelections;
                    string voteSessionId1 = voter1.sessionId;
                    voteSessionIds.Add(voteSessionId1);
                    if (x == 0)
                    {
                        firstVoteSessionId = voteSessionId1;
                    }
                    else
                    {
                        if (firstVoteSessionId != voteSessionId1)
                        {
                            allTheSame = false;
                        }
                    }
                }

                if (allTheSame)
                {
                    voteSessionId = firstVoteSessionId;
                }
                else
                {
                }

                var existingVoteSubmissions = voteSubmissions.Where(v => v.ControlNumber == controlNumber && v.voteSubmissionStatus == VoteSubmissionStatus.VotesConfirmed);
                if (existingVoteSubmissions.Any())
                {
                    if (existingVoteSubmissions.Any(vs => vs._id == voteSessionId) && allTheSame)
                    {
                        var filterVoteSubmission = Builders <VoteSubmission> .Filter.Eq("_id", voteSessionId);

                        _context.votesubmission.DeleteMany(filterVoteSubmission);
                    }
                    else
                    {
                        if (languagePreference == LanguagePreference.Russian)
                        {
                            return(RedirectToAction("Confirm_Russian", new { id = existingVoteSubmissions.FirstOrDefault()._id }));
                        }
                        else
                        {
                            return(RedirectToAction("Confirm", new { id = existingVoteSubmissions.FirstOrDefault()._id }));
                        }
                    }
                }
                else
                {
                    if (revote == "0")
                    {
                        var filterVoteSubmission = Builders <VoteSubmission> .Filter.Eq("ControlNumber", controlNumber);

                        _context.votesubmission.DeleteMany(filterVoteSubmission);
                    }
                }
            }

            if (revote == "1" || voteAnswerChoices == "")
            {
                MainVM viewModel = new MainVM();
                if (controlNumber != "-1")
                {
                    List <Question> questions = _blockchainContext.questions;

                    viewModel.activeQuestions = (from q in questions
                                                 orderby q.questionIndex
                                                 select new QuestionVM
                    {
                        quid = q.quid,
                        boardRecommendation = q.boardRecommendation,
                        text = q.text,
                        text_ru = q.text_ru,
                        questionIndex = q.questionIndex,
                        keyid = q.quid + "|",
                        SelectedAnswerId = "Z"
                    }
                                                 ).ToList();

                    viewModel.activeQuestions.ForEach(sv => sv.orderNum = Convert.ToInt32(sv.questionIndex) + 1);

                    List <Answer> answers = new List <Answer>();
                    Answer        answer  = new Answer();
                    answer.answid = "A";
                    answer.test   = "FOR";
                    answers.Add(answer);
                    Answer answer2 = new Answer();
                    answer2.answid = "B";
                    answer2.test   = "AGAINST";
                    answers.Add(answer2);
                    Answer answer3 = new Answer();
                    answer3.answid = "Z";
                    answer3.test   = "ABSTAIN";
                    answers.Add(answer3);

                    foreach (QuestionVM question in viewModel.activeQuestions)
                    {
                        question.Answers = (from a in answers
                                            orderby a.answid
                                            select new AnswerVM
                        {
                            quid = question.quid,
                            answid = a.answid,
                            text = a.test
                        }
                                            ).ToList();
                    }
                }
                else
                {
                    viewModel.activeQuestions = new List <QuestionVM>();
                }

                return(await Task.Run <IActionResult>(() => { return View(viewModel); }));
            }
            else
            {
                if (languagePreference == LanguagePreference.Russian)
                {
                    return(await Task.Run <IActionResult>(() => { return RedirectToAction("Confirm_Russian", new { id = "0" }); }));
                }
                else
                {
                    return(await Task.Run <IActionResult>(() => { return RedirectToAction("Confirm", new { id = "0" }); }));
                }
            }
        }
 public VoterModel(Voter voter)
 {
     this.Assign(voter);
     new HashSet <RatingModel>();
     new ApplicationUser();
 }
        public static XmlDocument lookup(string json)
        {
            XmlDocument             output      = null;
            JObject                 voterlookup = JObject.Parse(json);
            string                  firstname   = (string)voterlookup["VoterRequest"]["Subject"]["FirstName"];
            XmlSerializerNamespaces ns          = new XmlSerializerNamespaces();

            ns.Add("addr", "http://www.fgdc.gov/schemas/address/addr");
            ns.Add("addr_type", "http://www.fgdc.gov/schemas/address/addr_type");

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(VoterRecordsRequest));

            VoterRecordsRequest recordsRequest = new VoterRecordsRequest();
            Voter voter = new Voter();
            Name  name  = new Name()
            {
                FirstName = (string)voterlookup["VoterRequest"]["Subject"]["FirstName"],
                LastName  = (string)voterlookup["VoterRequest"]["Subject"]["LastName"],
                FullName  = (string)voterlookup["VoterRequest"]["Subject"]["FullName"],
            };

            name.MiddleName            = new string[1];
            name.MiddleName[0]         = (string)voterlookup["VoterRequest"]["Subject"]["MiddleName"];
            voter.Name                 = name;
            voter.DateOfBirthSpecified = true;
            voter.DateOfBirth          = Convert.ToDateTime((string)voterlookup["VoterRequest"]["Subject"]["DateOfBirth"]);

            int ids = voterlookup["VoterRequest"]["Subject"]["VoterId"].Count();

            voter.VoterId = new VoterId[ids];
            for (int i = 0; i < ids; i++)
            {
                VoterId vid = new VoterId();
                if (voterlookup["VoterRequest"]["Subject"]["VoterId"][i]["DateOfIssuance"] != null)
                {
                    vid.DateOfIssuanceSpecified = true;
                    vid.DateOfIssuance          = Convert.ToDateTime((string)voterlookup["VoterRequest"]["Subject"]["VoterId"][i]["DateOfIssuance"]);
                }
                vid.StringValue  = (string)voterlookup["VoterRequest"]["Subject"]["VoterId"][i]["StringValue"];
                vid.Type         = getVoterType((string)voterlookup["VoterRequest"]["Subject"]["VoterId"][i]["type"]);
                voter.VoterId[i] = vid;
            }

            voter.ResidenceAddress = voterAddress(voter);

            recordsRequest.Type    = new VoterRequestType[1];
            recordsRequest.Type[0] = VoterRequestType.lookup;

            recordsRequest.Issuer        = "NVRA Agency";
            recordsRequest.RequestMethod = RequestMethod.motorvehicleoffice;

            recordsRequest.Subject       = voter;
            recordsRequest.GeneratedDate = DateTime.Now;
            recordsRequest.TransactionId = "vri-request" + DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "").Replace("AM", "").Replace("PM", "");

            TextWriter write = new StreamWriter("C:\\dev\\nvraout.xml");

            xmlSerializer.Serialize(write, recordsRequest, ns);

            XmlDocument res = responseRecord(recordsRequest);

            using (MemoryStream ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, recordsRequest, ns);
                ms.Position = 0;
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreWhitespace = true;

                using (var xtr = XmlReader.Create(ms, settings)) {
                    output = new XmlDocument();
                    output.Load(xtr);
                }
            }

            return(res);
        }
Exemple #14
0
        public override IEnumerable <(string, int, ScoreBallot)> GetPotentialStrategicBallots(List <List <int> > ranking, Voter v)
        {
            var favorites          = ranking.Favorites();
            var maxFavoriteUtility = favorites.Max(w => v.Utilities[w]);
            var maxUtility         = v.Utilities.Max();

            // Approves of all candidates they like better or equal to the polling EV
            yield return("Exaggeration", 1, new ScoreBallot(v.Utilities.Select(u => u >= maxFavoriteUtility ? c_scale : 1)));

            // Maximizes chances for favorite (mostly)
            if (maxUtility != maxFavoriteUtility)
            {
                yield return("Truncation", 1, new ScoreBallot(v.Utilities.Select(u => u == maxUtility ? c_scale : 1)));
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    var voter = new Voter
                    {
                        Email = user.Email,
                        Name  = Input.Name,
                    };

                    dataContext.Add(voter);

                    dataContext.SaveChanges();
                    var roleExistsResult = await _roleManager.RoleExistsAsync("voter");

                    if (!roleExistsResult)
                    {
                        var roleReuslt = await _roleManager.CreateAsync(new IdentityRole("voter"));

                        if (roleReuslt.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "voter");
                        }
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "voter");
                    }



                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemple #16
0
        /// <summary>
        /// description: ......
        /// </summary>
        /// <param name="sessionId">description .....</param>
        /// <param name="surveyId">description ....</param>
        /// <param name="anonymousEntries">description ..</param>
        /// <param name="mailingEmails">description .......</param>
        /// <param name="message">description ......</param>
        public void MailIt(string sessionId, int surveyId, bool anonymousEntries, string mailingEmails, EmailingMessage message)
        {
            IEmailing mailService   = EmailingFactory.Create();
            string    guid          = null,
                      taggedMessage = message.Body,
                      email;

            string[] mailingList = mailingEmails.Split(',');

            SyncDataStore.SetRecords(sessionId + ":" + "Progress", 0);
            SyncDataStore.SetRecords(sessionId + ":" + "FailedEmails", 0);

            int failedEmails = 0;

            // Send the invitation email to the list
            for (int i = 0; i < mailingList.Length; i++)
            {
                email = mailingList[i].Trim();
                guid  = null;
                try
                {
                    guid            = new Voter().GenerateVoterInvitationUId(surveyId, email, anonymousEntries);
                    message.Body    = message.Body.Replace("[--invitationid-]", guid);
                    message.ToEmail = email;
                    mailService.SendEmail(message);
                    message.Body = taggedMessage;
                }
                catch (Exception ex)
                {
                    try
                    {
                        if (guid != null)
                        {
                            // rollback db state if an email has been saved
                            new Voter().DeleteVoterInvitation(surveyId, email);
                        }

                        InvitationLogData invitationLogs = new InvitationLogData();
                        InvitationLogData.InvitationLogsRow invitationLog = invitationLogs.InvitationLogs.NewInvitationLogsRow();
                        invitationLog.ExceptionMessage = (ex.InnerException != null && ex.InnerException.InnerException != null) ?
                                                         ex.InnerException.InnerException.Message : ex.Message.ToString();
                        invitationLog.ExceptionType = (ex.InnerException != null && ex.InnerException.InnerException != null) ?
                                                      ex.InnerException.InnerException.GetType().ToString() : ex.GetType().ToString();
                        invitationLog.SurveyId  = surveyId;
                        invitationLog.Email     = email;
                        invitationLog.ErrorDate = DateTime.Now;
                        invitationLogs.InvitationLogs.AddInvitationLogsRow(invitationLog);

                        // Log error in the database
                        new Voter().LogInvitationError(invitationLogs);
                        failedEmails++;
                    }
                    catch (Exception e)
                    {
                        SyncDataStore.SetRecords(sessionId + ":" + "Error", e);
                    }
                }

                SyncDataStore.UpdateRecords(sessionId + ":" + "Progress", (i * 100) / mailingList.Length);
                SyncDataStore.UpdateRecords(sessionId + ":" + "FailedEmails", failedEmails);
            }
        }
Exemple #17
0
        public override IEnumerable <(string, int, ScoreBallot)> GetPotentialStrategicBallots(List <List <int> > ranking, Voter v)
        {
            var favorites          = ranking.Favorites();
            var maxFavoriteUtility = favorites.Max(w => v.Utilities[w]);
            var minFavoriteUtility = favorites.Min(w => v.Utilities[w]);
            var maxUtility         = v.Utilities.Max();
            var minUtility         = v.Utilities.Max();

            // Approves of all candidates they like better or equal to the polling EV
            // If two "viable" candidates both meet that condition, knock the least-preferred down one peg.
            // If two "viable" candidates both fail that condition, bump the most-preferred up one peg.
            yield return("Exaggeration", 1, new ScoreBallot(v.Utilities.Select(u =>
                                                                               u == maxUtility || u > maxFavoriteUtility ? c_scale
                : u == maxFavoriteUtility ? c_scale - 1
                : u == minUtility || u < minFavoriteUtility ? 1
                : 2)));

            if (maxUtility != maxFavoriteUtility)
            {
                // Maximizes chances for favorite (mostly)
                yield return("Truncation", 1, new ScoreBallot(v.Utilities.Select(u =>
                                                                                 u == maxUtility ? c_scale
                    : u >= maxFavoriteUtility ? 2
                    : 1)));
            }
        }
Exemple #18
0
 public bool VoterPrefersFirstCandidate(Voter voter, int candidate1, int candidate2)
 {
     return(voter.CandidateScores[candidate1] < voter.CandidateScores[candidate2]);
 }
Exemple #19
0
        protected void pdfButton_Click(object sender, EventArgs e)
        {
            Document doc  = new Document(PageSize.A4, 36, 72, 108, 180);
            string   path = @"D:\";

            PdfWriter.GetInstance(doc, new FileStream(path + "/Treatment.pdf", FileMode.Create));
            doc.Open();
            Voter aVoter = new Voter();

            aVoter.Id      = nationalIdTextBox.Text;
            aVoter.Name    = nameTextBox.Text;
            aVoter.Address = addressTextBox.Text;
            Paragraph paragraph = new Paragraph();

            paragraph.Add("National Id : " + aVoter.Id);
            paragraph.Add(Environment.NewLine);
            paragraph.Add("Name : " + aVoter.Name);
            paragraph.Add(Environment.NewLine);
            paragraph.Add("Address :" + aVoter.Address);
            paragraph.Add(Environment.NewLine);
            paragraph.Add(Environment.NewLine);
            doc.Add(paragraph);

            Patient aPatient = new Patient();

            aPatient.VoterId = nationalIdTextBox.Text;
            GetPatientInformation(aPatient.VoterId);
            aPatient.Id = patientManager.GetPatientId(aPatient);

            int count = 0;
            List <Treatment> ObservationList = treatmentManager.GetObservationList(aPatient);

            foreach (var observation in ObservationList)
            {
                count++;
                PdfPTable table      = new PdfPTable(1);
                Paragraph aParagraph = new Paragraph();
                Chunk     chunk      = new Chunk("Treatment-" + count, FontFactory.GetFont("dax-black"));
                chunk.SetUnderline(0.5f, -1.5f);
                doc.Add(chunk);

                string centerName = centerManager.GetCenterName(observation.CenterId);
                aParagraph.Add("Center Name : " + centerName);
                aParagraph.Add(Environment.NewLine);
                string Date = observation.Date;
                aParagraph.Add("Date : " + Date);
                aParagraph.Add(Environment.NewLine);
                string DoctorName = doctorManager.GetDoctorName(observation.DoctorId);
                aParagraph.Add("Doctor Name : " + DoctorName);
                aParagraph.Add(Environment.NewLine);
                string Observation = observation.Observation;
                aParagraph.Add("Observation : " + Observation);
                aParagraph.Add(Environment.NewLine);
                table.AddCell(aParagraph);
                doc.Add(table);
                List <Treatment> treatmentList  = treatmentManager.GetTreatmentList(observation.ObservationId);
                List <Treatment> aTreatmentList = new List <Treatment>();
                foreach (var treatment in treatmentList)
                {
                    string    diseaseName  = diseaseManager.GetDiseaseName(treatment.DiseaseId);
                    string    medicineName = medicineManager.GetMedicineName(treatment.MedicineId);
                    Treatment aTreatment   = new Treatment();
                    aTreatment.NameOfDisease  = diseaseName;
                    aTreatment.NameOfMedicine = medicineName;
                    aTreatment.Dose           = treatment.Dose;
                    aTreatment.TakenTime      = treatment.TakenTime;
                    aTreatment.Quantity       = treatment.Quantity;
                    aTreatment.Note           = treatment.Note;

                    aTreatmentList.Add(aTreatment);
                }
                ShowAllTreatment(centerName, Date, DoctorName, Observation, count, aTreatmentList);
                PdfPTable aTable = new PdfPTable(6);
                aTable.AddCell("Disease");
                aTable.AddCell("Medicine");
                aTable.AddCell("Dose");
                aTable.AddCell("Before/After meal");
                aTable.AddCell("Quantity");
                aTable.AddCell("Note");
                foreach (var eachTreatment in aTreatmentList)
                {
                    aTable.AddCell(eachTreatment.NameOfDisease);
                    aTable.AddCell(eachTreatment.NameOfMedicine);
                    aTable.AddCell(eachTreatment.Dose);
                    aTable.AddCell(eachTreatment.TakenTime);
                    aTable.AddCell(eachTreatment.Quantity.ToString());
                    aTable.AddCell(eachTreatment.Note);
                }
                doc.Add(aTable);
            }
            doc.Close();
            Response.Redirect("OpenPdfUI.aspx");
            megLabel.Text = "PDF Creation Successful!";
        }
Exemple #20
0
        public IActionResult Edit(VoterStateViewModel voterstate)
        {
            _logger.LogInformation("Voter/Edit() action is called");
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogError("Model is not valid");
                    if (voterstate.States == null)
                    {
                        //in caase the object received doesn't have a list of states
                        voterstate.States = _stateBusiness.GetAll();
                    }
                    _logger.LogInformation("Returning to the view to display validation messages");
                    //so there is a business rule not met, lets throw a businessException and catch it
                    throw new BusinessException(_messagesLoclizer["Information provided not valid"]);
                }
                Voter v = new Voter
                {
                    Id        = voterstate.Id,
                    FirstName = voterstate.FirstName,
                    LastName  = voterstate.LastName,
                    StateId   = voterstate.StateID
                };

                _logger.LogInformation("Calling VoterRepository.Edit() method");

                int updatedRows = _voterBusiness.Edit(voterstate.Id, v);
                if (updatedRows > 0)
                {
                    //row updated successfully in the DB
                    _logger.LogInformation("Redirecting to Index action");
                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    //row not updated in the DB
                    throw new DataNotUpdatedException(_messagesLoclizer["Data not updated, operation failed."]);
                }
            }
            catch (DataNotUpdatedException bnu)
            {
                _logger.LogError(bnu.Message);
                //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it
                //by whatever we want
                BusinessMessage bm = new BusinessMessage("Error", bnu.Message);
                ViewBag.BusinessMessage = bm;
                return(View());
            }
            catch (BusinessException be)
            {
                _logger.LogError(be.Message);
                //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it
                //by whatever we want
                BusinessMessage bm = new BusinessMessage("Error", be.Message);
                ViewBag.BusinessMessage = bm;
                //lets refill States list
                voterstate.States = _stateBusiness.GetAll();
                return(View(voterstate));
            }
            catch (Exception E)
            {
                _logger.LogError("Exception, " + E.Message);
                throw E;
            }
        }
        public override void Parse(object subject, string msg)
        {
            Voter voter = (Voter)subject;

            voter.disableConnectionProxyButton();
        }
        public async Task CreateVoterAsync(Voter voter, string password, string role)
        {
            await _userManager.CreateAsync(voter, password);

            await _userManager.AddToRoleAsync(voter, role);
        }
Exemple #23
0
        public Voter UpdateVoteValidity(Voter voterData)
        {
            //TODO: Add Validatiom

            return(_votingInformationRepository.UpdateVoteValidity(voterData));
        }
 public async Task <bool> CheckPasswordAsync(Voter voter, string password)
 {
     return(await _userManager.CheckPasswordAsync(voter, password));
 }
Exemple #25
0
        public async Task <IActionResult> Confirm_Codebehind(string id)
        {
            if (HttpContext.Session.GetString("ControlNumber") == null)
            {
                return(await Task.Run <IActionResult>(() => { return RedirectToAction("Login"); }));
            }

            string controlNumber = HttpContext.Session.GetString("ControlNumber");

            MainVM viewModel = new MainVM();

            if (id != "0")
            {
                IMongoQueryable <VoteSubmission> voteSubmission = _context.votesubmission.AsQueryable();

                var savedVotes = voteSubmission.Where(e => e._id == id);

                viewModel.VoteSubmissionId = id;
                if (savedVotes.Any())
                {
                    viewModel.activeQuestions = savedVotes.FirstOrDefault().VoteSelections;
                    viewModel.activeQuestions.ForEach(q => q.orderNum = (q.questionIndex) + 1);
                    viewModel.activeQuestions = viewModel.activeQuestions.OrderBy(q => q.orderNum).ToList();

                    viewModel.voteSubmissionStatus = savedVotes.FirstOrDefault().voteSubmissionStatus;
                    if (savedVotes.FirstOrDefault().dateSubmitted != null)
                    {
                        viewModel.dateSubmitted = savedVotes.FirstOrDefault().dateSubmitted;
                    }
                    else
                    {
                        viewModel.dateSubmitted = DateTime.Now;
                    }
                }
            }
            else
            {
                viewModel.VoteSubmissionId = id;
                SHOAccount shoaccount = _context.shoaccounts.AsQueryable().Where(sho => sho.ControlNumber == controlNumber).FirstOrDefault();
                Voter      voter1     = await _blockchainContext.getVoteAnswersByVoterId(shoaccount.maskedVoters[0].voterId);

                string          voteString = voter1.voteSelections;
                List <Question> questions  = _blockchainContext.questions;

                viewModel.activeQuestions = (from q in questions
                                             orderby q.questionIndex
                                             select new QuestionVM
                {
                    quid = q.quid,
                    boardRecommendation = q.boardRecommendation,
                    text = q.text,
                    text_ru = q.text_ru,
                    questionIndex = q.questionIndex,
                    keyid = q.quid + "|",
                    SelectedAnswerId = "Z"
                }
                                             ).ToList();

                viewModel.activeQuestions.ForEach(q => q.orderNum = (q.questionIndex) + 1);
                viewModel.activeQuestions = viewModel.activeQuestions.OrderBy(q => q.orderNum).ToList();

                for (int x = 0; x < viewModel.activeQuestions.Count(); x++)
                {
                    viewModel.activeQuestions[x].SelectedAnswerId = voteString.Substring(x, 1);
                }

                viewModel.voteSubmissionStatus = VoteSubmissionStatus.VotesConfirmed;
            }

            return(await Task.Run <IActionResult>(() => { return View(viewModel); }));
        }
        public async Task <string> GetVoterRoleAsync(Voter voter)
        {
            var roles = await _userManager.GetRolesAsync(voter);

            return(roles.FirstOrDefault());
        }
Exemple #27
0
        public ActionResult Create(Leader leader, string newWorkPlace)
        {
            if (ModelState.IsValid)
            {
                if (leader.WorkPlaceId == 9999)
                {
                    if (!string.IsNullOrEmpty(newWorkPlace))
                    {
                        var workPlace = new WorkPlace
                        {
                            Name = newWorkPlace,
                        };
                        db.WorkPlaces.Add(workPlace);
                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            if (ex.InnerException != null &&
                                ex.InnerException.InnerException != null &&
                                ex.InnerException.InnerException.Message.Contains("_Index"))
                            {
                                ModelState.AddModelError(string.Empty, "Ya existe un lugar de trabajo con ese nombre");
                            }
                            else
                            {
                                ModelState.AddModelError(string.Empty, ex.ToString());
                            }
                            ViewBag.CountryId = new SelectList(
                                CombosHelper.GetCountries(),
                                "CountryId",
                                "Name",
                                leader.CountryId);

                            ViewBag.CityId = new SelectList(
                                CombosHelper.GetCities(),
                                "CityId",
                                "Name",
                                leader.CityId);

                            ViewBag.CompanyId = new SelectList(
                                CombosHelper.GetCompanies(),
                                "CompanyId",
                                "Name",
                                leader.CompanyId);

                            ViewBag.DepartmentId = new SelectList(
                                CombosHelper.GetDepartments(),
                                "DepartmentId",
                                "Name",
                                leader.DepartmentId);

                            ViewBag.CommuneId = new SelectList(
                                CombosHelper.GetCommunes(),
                                "CommuneId",
                                "Name",
                                leader.CommuneId);

                            ViewBag.WorkPlaceId = new SelectList(
                                CombosHelper.GetWorkPlaces(),
                                "WorkPlaceId",
                                "Name",
                                leader.WorkPlaceId);

                            ViewBag.VotingPlaceId = new SelectList(
                                CombosHelper.GetVotingPlaces(),
                                "VotingPlaceId",
                                "Name",
                                leader.VotingPlaceId);
                            return(View(leader));
                        }
                        db.SaveChanges();
                        leader.WorkPlaceId = workPlace.WorkPlaceId;
                    }
                }
                var refer = db.Refers.Find(leader.ReferId);
                if (leader.userId == 1)
                {
                    leader.BossId = refer.UserId;
                }
                if (leader.userId == 2)
                {
                    leader.LinkId = refer.UserId;
                }
                if (leader.userId == 3)
                {
                    leader.CoordinatorId = refer.UserId;
                }

                db.Leaders.Add(leader);
                try
                {
                    db.SaveChanges();
                    //UsersHelper.CreateUserASP(leader.UserName, "Leader");
                    if (leader.PhotoFile != null)
                    {
                        var folder   = "~/Content/Leader";
                        var file     = string.Format("{0}.jpg", leader.LeaderId);
                        var response = FilesHelper.UploadPhoto(leader.PhotoFile, folder, file);
                        if (response)
                        {
                            var pic = string.Format("{0}/{1}", folder, file);
                            leader.Photo           = pic;
                            db.Entry(leader).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }

                    var Refer = new Refer
                    {
                        ReferType = 4,
                        UserId    = leader.LeaderId,
                        FullName  = leader.FullName,
                        Active    = 1
                    };
                    db.Refers.Add(Refer);
                    db.SaveChanges();


                    var city        = db.Cities.Find(leader.CityId);
                    var department  = db.Departments.Find(leader.DepartmentId);
                    var country     = db.Countries.Find(leader.CountryId);
                    var comune      = db.Communes.Find(leader.CommuneId);
                    var votingPlace = db.VotingPlaces.Find(leader.VotingPlaceId);
                    var Voter       = new Voter
                    {
                        Address       = leader.Address,
                        BossId        = leader.BossId,
                        LinkId        = leader.LinkId,
                        CoordinatorId = leader.CoordinatorId,
                        CityId        = city.Name,
                        CommuneId     = comune.Name,
                        CompanyId     = leader.CompanyId,
                        CountryId     = leader.Country.Name,
                        DepartmentId  = department.Name,
                        Document      = leader.Document,
                        FirstName     = leader.FirstName,
                        LastName      = leader.LastName,
                        Phone         = leader.Phone,
                        UserName      = leader.UserName,
                        VotingPlaceId = votingPlace.Name,
                        userId        = 4,
                        ReferId       = refer.ReferId,
                        PerfilId      = leader.userId,
                        Fname         = string.Format("{0} {1}", leader.FirstName, leader.LastName),
                        Barrio        = leader.Barrio,
                        Profesion     = leader.Profesion,
                        DateBorn      = leader.DateBorn,
                    };
                    db.Voters.Add(Voter);

                    db.SaveChanges();

                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null &&
                        ex.InnerException.InnerException != null &&
                        ex.InnerException.InnerException.Message.Contains("_Index"))
                    {
                        ModelState.AddModelError(string.Empty, "Ya existe un Registro con esa descripción");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.ToString());
                    }
                }
            }

            ViewBag.CountryId = new SelectList(
                CombosHelper.GetCountries(),
                "CountryId",
                "Name",
                leader.CountryId);

            ViewBag.CityId = new SelectList(
                CombosHelper.GetCities(),
                "CityId",
                "Name",
                leader.CityId);

            ViewBag.CompanyId = new SelectList(
                CombosHelper.GetCompanies(),
                "CompanyId",
                "Name",
                leader.CompanyId);

            ViewBag.DepartmentId = new SelectList(
                CombosHelper.GetDepartments(),
                "DepartmentId",
                "Name",
                leader.DepartmentId);

            ViewBag.CommuneId = new SelectList(
                CombosHelper.GetCommunes(),
                "CommuneId",
                "Name",
                leader.CommuneId);

            ViewBag.VotingPlaceId = new SelectList(
                CombosHelper.GetVotingPlaces(),
                "VotingPlaceId",
                "Name",
                leader.VotingPlaceId);

            ViewBag.userId = new SelectList(
                CombosHelper.GetTypeUserCoordinator(),
                "userId",
                "name",
                leader.userId);

            ViewBag.WorkPlaceId = new SelectList(
                CombosHelper.GetWorkPlaces(),
                "WorkPlaceId",
                "Name",
                leader.WorkPlaceId);

            ViewBag.ReferId = new SelectList(
                CombosHelper.GetRefer(),
                "ReferId",
                "FullName",
                leader.ReferId);

            return(View(leader));
        }
        public override IEnumerable <(string, int, BucketBallot <Bucket>)> GetPotentialStrategicBallots(List <List <int> > ranking, Voter v)
        {
            var favorites          = ranking.Favorites();
            var winnerUtility      = ranking[0].Max(w => v.Utilities[w]);
            var maxFavoriteUtility = favorites.Max(w => v.Utilities[w]);
            var maxUtility         = v.Utilities.Max();
            var minUtility         = v.Utilities.Min();

            var(best, bad) = GetThresholds(v.Utilities);

            // Explicitly approve of all candidates one likes better or equal to the favored frontrunner
            yield return("Exaggeration", 1, NewBallot(u => u >= maxFavoriteUtility ? Bucket.Best : Bucket.Bad));

            if (maxUtility != maxFavoriteUtility)
            {
                // Maximizes chances for favorite alone
                yield return("Truncation", 1, NewBallot(u => u == maxUtility ? Bucket.Best : Bucket.Bad));
            }

            if (winnerUtility >= bad && winnerUtility != maxUtility)
            {
                // Artificially rank the winner lower.
                yield return("Burying", 1, NewBallot(u => u == winnerUtility ? Bucket.Bad : null));
            }

            // Maybe our favorite was someone else's bogeyman?
            yield return("Favorite Betrayal Mild", 1, NewBallot(u => u == maxUtility ? Bucket.Good : null));

            yield return("Favorite Betrayal", 2, NewBallot(u => u == maxUtility ? Bucket.Bad : null));

            if (winnerUtility == maxFavoriteUtility && maxUtility != maxFavoriteUtility)
            {
                yield return("Post-Winner Truncation", 1, NewBallot(u =>
                                                                    u > winnerUtility ? Bucket.Best
                    : u == winnerUtility ? Bucket.Good
                    : Bucket.Bad));
            }

            if (winnerUtility <= best && minUtility != winnerUtility)
            {
                // Support everyone we like **worse* than winner in hopes that more people will rally around the favored frontrunner
                yield return("Dark Horse", 3, NewBallot(u =>
                                                        u < winnerUtility ? Bucket.Good
                    : u == winnerUtility ? Bucket.Bad
                    : null));

                yield return("Dark Horse", 3, NewBallot(u =>
                                                        u < winnerUtility ? Bucket.Best
                    : null));
            }

            // Vote for *no-one*.
            yield return("Abstain", 3, NewBallot(u => Bucket.Bad));

            BucketBallot <Bucket> NewBallot(Func <int, Bucket?> getBucket) => new BucketBallot <Bucket>(v.Utilities.SelectToArray(u => getBucket(u) ?? (
                                                                                                                                      u > best ? Bucket.Best
                : u < bad ? Bucket.Bad
                : Bucket.Good)));
        }
Exemple #29
0
        public ActionResult Importexcel1(int userId, int ReferId)
        {
            var user = db.Users.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();

            if (user == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            int boss        = 0;
            int link        = 0;
            int coordinator = 0;
            int leader      = 0;

            if (Request.Files["FileUpload1"].ContentLength > 0)
            {
                var refer = db.Refers.Find(ReferId);
                if (userId == 1)
                {
                    boss = refer.UserId;
                }
                if (userId == 2)
                {
                    link = refer.UserId;
                }
                if (userId == 3)
                {
                    coordinator = refer.UserId;
                }
                if (userId == 4)
                {
                    leader = refer.UserId;
                }

                string   extension      = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
                string   query          = null;
                string   connString     = "";
                string[] validFileTypes = { ".xlsx" };

                string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
                if (!Directory.Exists(path1))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
                }
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(path1))
                    {
                        System.IO.File.Delete(path1);
                    }
                    Request.Files["FileUpload1"].SaveAs(path1);

                    List <Mistakes> errores = new List <Mistakes>();

                    if (extension.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        DataTable dt         = Utility.ConvertXSLXtoDataTable(path1, connString);
                        int       contador   = 0;
                        int       mistakes   = 0;
                        int       existentes = 0;
                        ViewBag.Message  = string.Empty;
                        ViewBag.Message1 = string.Empty;
                        ViewBag.Message2 = string.Empty;
                        foreach (DataRow row in dt.Rows)
                        {
                            //ACA VAN LAS VALIDACIONES
                            if (Utilidades.isNumeric(row[2].ToString()))               //valido que el documento sea un campo numerico
                            {
                                double document = Convert.ToDouble(row[2].ToString()); //documento de identidad
                                var    voter    = db.Voters.Where(v => v.Document == document).ToList();
                                if (voter.Count == 0)
                                {
                                    string pais        = "Colombia";
                                    string departmento = "Norte de Santander";
                                    string ciudad      = "Cúcuta";
                                    var    Country     = db.Countries.Where(c => c.Name == pais).ToList();
                                    var    Department  = db.Departments.Where(c => c.Name == departmento).ToList();
                                    var    City        = db.Cities.Where(c => c.Name == ciudad).ToList();
                                    if (Country.Count > 0)
                                    {
                                        if (Department.Count > 0)
                                        {
                                            if (City.Count > 0)
                                            {
                                                string comune      = row[8].ToString();
                                                string votacion    = row[6].ToString();
                                                var    comuna      = db.Communes.Where(c => c.Name == comune).ToList();
                                                var    votingplace = db.VotingPlaces.Where(v => v.Name == votacion).ToList();
                                                if (comuna.Count > 0)
                                                {
                                                    if (votingplace.Count > 0)
                                                    {
                                                        using (var transaction = db.Database.BeginTransaction())
                                                        {
                                                            try
                                                            {
                                                                DateTime value;
                                                                DateTime dateBorn;
                                                                if (!DateTime.TryParse(row[3].ToString(), out value))
                                                                {
                                                                    dateBorn = DateTime.Now;
                                                                }
                                                                else
                                                                {
                                                                    dateBorn = Convert.ToDateTime(row[3].ToString());
                                                                }
                                                                var Voter = new Voter
                                                                {
                                                                    FirstName     = row[0].ToString(),
                                                                    LastName      = row[1].ToString(),
                                                                    Document      = Convert.ToDouble(row[2].ToString()),
                                                                    DateBorn      = dateBorn,
                                                                    CountryId     = pais,
                                                                    DepartmentId  = departmento,
                                                                    CityId        = ciudad,
                                                                    Address       = row[4].ToString(),
                                                                    UserName      = row[10].ToString(),
                                                                    Phone         = row[5].ToString(),
                                                                    CommuneId     = row[8].ToString(),
                                                                    Barrio        = row[7].ToString(),
                                                                    Profesion     = row[9].ToString(),
                                                                    VotingPlaceId = row[6].ToString(),
                                                                    BossId        = boss,
                                                                    LinkId        = link,
                                                                    CoordinatorId = coordinator,
                                                                    LeaderId      = leader,
                                                                    CompanyId     = user.CompanyId,
                                                                    Fname         = string.Format("{0} {1}", row[0].ToString(), row[1].ToString()),
                                                                    ReferId       = ReferId,
                                                                    PerfilId      = userId,
                                                                    userId        = 5,
                                                                };
                                                                db.Voters.Add(Voter);
                                                                db.SaveChanges();
                                                                contador += 1;
                                                                transaction.Commit();
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                transaction.Rollback();
                                                                ViewBag.Error = "Se ha presentado un error al subir la información. No se han afectado los registros";
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        mistakes += 1;
                                                        errores.Add(new Mistakes
                                                        {
                                                            document           = row[2].ToString(),
                                                            mistakeDescription = "No se suministro Lugar de Votacion"
                                                        });
                                                    }
                                                }
                                                else
                                                {
                                                    mistakes += 1;
                                                    errores.Add(new Mistakes
                                                    {
                                                        document           = row[2].ToString(),
                                                        mistakeDescription = "No se suministro Comuna"
                                                    });
                                                }
                                            }
                                            else
                                            {
                                                mistakes += 1;
                                                errores.Add(new Mistakes
                                                {
                                                    document           = row[2].ToString(),
                                                    mistakeDescription = "No se suministro Ciudad"
                                                });
                                            }
                                        }
                                        else
                                        {
                                            mistakes += 1;
                                            errores.Add(new Mistakes
                                            {
                                                document           = row[2].ToString(),
                                                mistakeDescription = "No se suministro Departamento"
                                            });
                                        }
                                    }
                                    else
                                    {
                                        mistakes += 1;
                                        errores.Add(new Mistakes
                                        {
                                            document           = row[2].ToString(),
                                            mistakeDescription = "No se suministro País"
                                        });
                                    }
                                }
                                else
                                {
                                    existentes += 1;
                                    errores.Add(new Mistakes
                                    {
                                        document           = row[2].ToString(),
                                        mistakeDescription = "Este registro ya existe"
                                    });
                                }
                            }
                            else
                            {
                                mistakes += 1;
                                errores.Add(new Mistakes
                                {
                                    document           = row[2].ToString(),
                                    mistakeDescription = "El documento de identidad es inválido"
                                });
                            }
                        }
                        if (contador > 0)
                        {
                            ViewBag.Message = "Se han ingresado correctamente " + contador + " Registros";
                        }
                        if (errores.Count > 0)
                        {
                            ViewBag.Message1 = errores;
                        }

                        contador   = 0;
                        mistakes   = 0;
                        existentes = 0;
                    }
                }
                else
                {
                    ViewBag.Error = "Solo se permiten archivos con formato .xls, .xlsx";
                }
            }
            ViewBag.userId = new SelectList(
                CombosHelper.GetUser(),
                "userId",
                "name");

            ViewBag.ReferId = new SelectList(
                CombosHelper.GetRefer(),
                "ReferId",
                "FullName");
            return(View());
        }
        public async Task <Voter> CheckVoterAsync(Voter entity)
        {
            try
            {
                try
                {
                    // Requests to VAN have been failing - appears to be offline. So if requests doesn't work, for now let's treat as unregistered
                    var dto = new NetworkNeighbors.DTOs.VAN.PersonDTO
                    {
                        firstName = entity.first_name,
                        lastName  = entity.last_name
                    };
                    if (!String.IsNullOrEmpty(entity.email))
                    {
                        dto.emails = new List <EmailDTO> {
                            new EmailDTO {
                                email = entity.email
                            }
                        };
                    }
                    if (!String.IsNullOrEmpty(entity.phone))
                    {
                        dto.phones = new List <PhoneDTO> {
                            new PhoneDTO {
                                phoneNumber = entity.phone
                            }
                        };
                    }
                    if (!String.IsNullOrEmpty(entity.address_1) && !String.IsNullOrEmpty(entity.city) && !String.IsNullOrEmpty(entity.state) && !String.IsNullOrEmpty(entity.zip_code))
                    {
                        dto.addresses = new List <AddressDTO> {
                            new AddressDTO {
                                addressLine1 = entity.address_1, addressLine2 = entity.address_2, city = entity.city, stateOrProvince = entity.state, zipOrPostalCode = entity.zip_code
                            }
                        };
                    }
                    if (entity.dob.HasValue)
                    {
                        dto.dateOfBirth = entity.dob.Value;
                    }
                    var match = await FindPersonInVANAsync(dto);

                    if (match != null)
                    {
                        entity.van_id = match.vanId;
                        entity.registration_status = match.status;
                    }
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Trace.Warn(ex.ToString());
                }
                entity.voter_id = SaveVoter(entity);
                if (!String.IsNullOrEmpty(entity.voter_id))
                {
                    return(entity);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Trace.Warn(ex.ToString());
            }
            return(null);
        }
        public override void Parse(object subject, string msg)
        {
            Voter voter = (Voter)subject;

            voter.saveSignedColumnAndToken(msg);
        }
Exemple #32
0
        public static void Main(string[] _args)
        {
            var settings = null as Settings;
            if(File.Exists("vote_settings.json"))
            {
                settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText("vote_settings.json"));
            }
            else
            {
                settings = new Settings();
                File.WriteAllText("vote_settings.json", JsonConvert.SerializeObject(settings));
            }

            args = new ArgsManager<Args>(_args);

            var levelsFile = args.GetValue(Args.OptionLevelsFile);
            var votesFile = args.GetValue(Args.OptionVotesFile);

            if(!File.Exists(levelsFile))
            {
                Console.WriteLine("Couldn't find levels file: {0}", levelsFile);
                Console.ReadKey();
                return;
            }

            if (!File.Exists(votesFile))
            {
                Console.WriteLine("Couldn't find votes file: {0}", votesFile);
                Console.ReadKey();
                return;
            }

            try
            {
                // load the levels
                var _levels = File.ReadAllLines(levelsFile);
                var levels = new List<Level>();

                foreach (var _level in _levels)
                {
                    levels.Add(new Level(_level, settings));
                }

                // load the votes
                var _votes = File.ReadAllLines(votesFile);
                var voters = new List<Voter>();
                var voter = null as Voter;

                int line = 0;
                foreach (var _vote in _votes)
                {
                    line++;
                    if (Char.IsLetter(_vote[0]))
                        continue;

                    if (_vote[0] == '/')
                    {
                        voter = new Voter(_vote.Substring(1), settings);
                        voters.Add(voter);
                    }
                    else
                        voter.AddVote(new Vote(_vote, line));
                }

                // match the votes to the levels

                Console.WriteLine("Some votes may have been mispelled. Please verify the following fuzzy matches:");
                foreach (var _voter in voters)
                {
                    if (!_voter.IsComplete())
                        throw new Exception("User " + _voter.Username + " voted incorrectly.");

                    foreach(var vote in _voter.Votes)
                    {
                        var match = vote.FindClosestMatch(levels);

                        if (!match.IsExact)
                            Console.WriteLine("Fuzzy Matched: {0}\n" +
                                              "         with: {1}\n", vote.Level, match.Level.FullTitle);

                        match.Level.Vote(vote.VoteNumber);
                    }
                }

                // output the results

                // first calculate the column widths
                int place = 0;
                int[] cols = { 0, 0, 0 };
                foreach (var level in levels)
                {
                    int c1 = (place + ".").Length + 1;
                    int c2 = Math.Min(level.FullTitle.Length+1, 60);
                    int c3 = (level.Points.ToString("0.0") + " points ("+level.NthVotes[0]+" 1st place votes)").Length;

                    if (c1 > cols[0]) cols[0] = c1;
                    if (c2 > cols[1]) cols[1] = c2;
                    if (c3 > cols[2]) cols[2] = c3;

                    place++;
                }

                // now output
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("############  RESULTS  ############");
                levels.Sort(delegate (Level x, Level y) {
                    int cmp = y.Points.CompareTo(x.Points);
                    if (cmp == 0)
                        cmp = y.NthVotes[0].CompareTo(x.NthVotes[0]);

                    return cmp;
                });

                place = 0;
                foreach (var level in levels)
                {
                    place++;
                    PrintColumn(place + ".", cols[0]);
                    PrintColumn(level.FullTitle, cols[1]);
                    PrintColumn(level.Points.ToString("0.0") + " points (" + level.NthVotes[0] + " 1st place votes)", cols[2]);

                    Console.WriteLine();
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine();
            Console.WriteLine();

            Console.ReadKey();
        }
Exemple #33
0
 public Voter UpdateVoteValidity(
     [FromBody] Voter request
     )
 {
     return(_votingInformationService.UpdateVoteValidity(request));
 }
        //
        // GET: /Voter/Edit/5

        public ActionResult Edit(int id)
        {
            Voter theVoter = work.VoterRepository.GetByID(id);

            return(View(theVoter));
        }
Exemple #35
0
 protected override bool IsVoterAuthorized(Voter voter)
 {
     return(true);
 }
        public async Task <int> AddVotes(List <string> candidateIdList)
        {
            try
            {
                if (candidateIdList == null || candidateIdList.Count <= 0)
                {
                    //_logger.LogError("Cannot validate votes of empty list of candidates");
                    throw new BusinessException(_messagesLocalizer["Cannot validate votes of empty list of candidates"]);
                }

                //lets first get the concerned election
                Candidate firstOne = _candidateRepository.GetById(Guid.Parse(candidateIdList.FirstOrDefault()));
                Election  election = _electionRepository.GetById(firstOne.Election.Id);
                if (election == null)
                {
                    //_logger.LogError("Cannot validate vote of null election");
                    throw new BusinessException(_messagesLocalizer["Cannot validate vote of null election"]);
                }

                //lets get the voter instance of the current user, so that we use its id with his votes
                var currentUser = await _userBusiness.GetCurrentUser();

                //declaring an expression that is special to Voter objects
                Expression <Func <Voter, bool> > expr = v => v.UserId == Guid.Parse(currentUser.Id);
                Voter currentVoter = _voterRepository.GetOneFiltered(expr);

                if (currentVoter == null)
                {
                    //_logger.LogError("Voter instance was not found for current user");
                    throw new BusinessException(_messagesLocalizer["Voter instance was not found for current user"]);
                }


                Vote v = new Vote();
                //lets add 'Vote' objects to the db
                foreach (var candidateId in candidateIdList)
                {
                    v.Id = Guid.NewGuid();
                    Candidate candidate = _candidateRepository.GetById(Guid.Parse(candidateId));
                    if (candidate == null)
                    {
                        throw new BusinessException(_messagesLocalizer["Candidate instance was not found for"] + " " + candidateId);
                    }
                    v.CandidateId = candidate.Id;
                    v.VoterId     = currentVoter.Id;
                    v.Datetime    = DateTime.Now;
                    v.ElectionId  = election.Id;

                    int updatedRows = _voteRepository.Add(v);
                    if (updatedRows < 1)
                    {
                        //row not updated in the DB
                        throw new DataNotUpdatedException(_messagesLocalizer["Data not updated, operation failed."]);
                    }
                }
                return(candidateIdList.Count());
            }
            catch (DataNotUpdatedException E)
            {
                throw E;
            }
            catch (BusinessException E)
            {
                throw E;
            }
        }
        public ActionResult Populate(IEnumerable <HttpPostedFileBase> file)
        // public void Populate()
        {
            HttpPostedFileBase theFile = Request.Files[0];
            var fileName = Path.GetFileName(Request.Files[0].FileName);

            IExcelDataReader excelReader = null;

            //if ((fileExtension.EndsWith(".xlsx")))
            //{
            //    //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
            //    excelReader = ExcelReaderFactory.CreateOpenXmlReader(theFile.InputStream);
            //}

            //if ((fileExtension.EndsWith(".xls")))
            //{

            //1. Reading from a binary Excel file ('97-2003 format; *.xls)
            excelReader = ExcelReaderFactory.CreateBinaryReader(theFile.InputStream);
            //  }
            // ExcelDataReader reader = new ExcelDataReader(ExcelFileUpload.PostedFile.InputStream);

            /// FileStream stream = File.Open(Request.Files[0], FileMode.Open, FileAccess.Read);


            //...

            //...
            //3. DataSet - The result of each spreadsheet will be created in the result.Tables
            DataSet result = excelReader.AsDataSet();

            //  ...
            //4. DataSet - Create column names from first row
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result2 = excelReader.AsDataSet();

            //5. Data Reader methods
            int counter = 0;

            int usernameCouner = 5000;
            var chars          = "xbckheayrydzjcmgncb4au9w8xu5ur93hmb3vmzqa4j3n7x3nwkkm3ktvj6c2vj9k48ckdnv3n4bsv6a8ev9xjcvk3n5m7rka9a5xz7hz8zrmn3kz3n4nzmavn3kwn7k8kvc3n2a9s3muabtfbusk347sbua3hdkcks28jk";

            while (excelReader.Read())
            {
                if (counter != 0)
                {
                    var    random         = new Random();
                    string randomPassword = new string(Enumerable.Repeat(chars, 6).Select(s => s[random.Next(s.Length)]).ToArray());

                    Voter theVoter = new Voter();
                    //theVoter.IdentityNumber = theMatric;
                    try
                    {
                        theVoter.Department = excelReader.GetString(1).TrimEnd().TrimStart();; // theBrokenData[0].TrimEnd().TrimStart();


                        usernameCouner     = usernameCouner + 1;
                        theVoter.FirstName = excelReader.GetString(3).TrimEnd().TrimStart();
                        //  theVoter.Matric = "000"; //excelReader.GetString(4).TrimEnd().TrimStart();
                        theVoter.Matric         = excelReader.GetString(4).TrimEnd().TrimStart();
                        theVoter.IdentityNumber = Convert.ToString(usernameCouner);//usernameCouner + 1; //excelReader.GetValue(5).ToString().TrimEnd().TrimStart();

                        theVoter.Password  = randomPassword;
                        theVoter.VotedTime = DateTime.Now;

                        // theVoter.LastName = theBrokenData[5].TrimEnd().TrimStart(); ;
                        theVoter.Voted = false;


                        List <Voter> theVoters = work.VoterRepository.Get(a => a.IdentityNumber == theVoter.IdentityNumber).ToList();
                        if (theVoter.IdentityNumber != null && theVoters.Count() > 0)
                        {
                            string k = "f";
                        }
                        //  theID = WebSecurity.GetUserId(theVoter.IdentityNumber);
                        if (theVoters.Count == 0 && theVoter.FirstName != null && theVoter.IdentityNumber != null && theVoter.Department != null)
                        {
                            work.VoterRepository.Insert(theVoter);

                            Membership.CreateUser(theVoter.IdentityNumber, randomPassword);
                            work.Save();
                            //  WebSecurity.CreateUserAndAccount(theVoter.IdentityNumber, randomPassword);
                        }
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }
                counter = counter + 1;
            }



            //// int theID = 0;

            //var random = new Random();
            //// string result = new string(Enumerable.Repeat(chars,6).Select(s=>s[random.Next(s.Length)]).ToArray());


            //FileStream fs = new FileStream("C:\\Users\\kazeem\\Desktop\\School Projects\\doctorsreal.txt", FileMode.Open, FileAccess.Read);
            //StreamReader sr = new StreamReader(fs);
            //// Math.
            ////  string theLast = null;
            //// string theMatric = null;
            //while (!(sr.EndOfStream))
            //{
            //    string randomPassword = new string(Enumerable.Repeat(chars, 6).Select(s => s[random.Next(s.Length)]).ToArray());
            //    string theMatric = sr.ReadLine().Trim();
            //    string[] theBrokenData = theMatric.Split('\t');

            //    // theBrokenData[6];

            //    Voter theVoter = new Voter();
            //    //theVoter.IdentityNumber = theMatric;
            //    theVoter.IdentityNumber = theBrokenData[3].TrimEnd().TrimStart();
            //    theVoter.Department = theBrokenData[0].TrimEnd().TrimStart();
            //    theVoter.Password = randomPassword;
            //    theVoter.VotedTime = DateTime.Now;
            //    theVoter.FirstName = theBrokenData[2].TrimEnd().TrimStart(); ;
            //    // theVoter.LastName = theBrokenData[5].TrimEnd().TrimStart(); ;
            //    theVoter.Voted = false;

            //    List<Voter> theVoters = work.VoterRepository.Get(a => a.IdentityNumber == theVoter.IdentityNumber).ToList();
            //    //  theID = WebSecurity.GetUserId(theVoter.IdentityNumber);
            //    if (theVoters.Count == 0)
            //    {
            //        work.VoterRepository.Insert(theVoter);

            //        Membership.CreateUser(theVoter.IdentityNumber, randomPassword);
            //        work.Save();
            //        //  WebSecurity.CreateUserAndAccount(theVoter.IdentityNumber, randomPassword);
            //    }
            //    //  theLast  =theMatric;
            //}
            //sr.Close();
            //fs.Close();
            //  theLast = theMatric;
            // List<Post> theposts = work.PostRepository.Get().ToList();
            // return View("Result", theposts);
            return(View());
        }
Exemple #38
0
	public void buyVotes(Voter index, int amount){
		Debug.Log ("INBUYVOTES");
        voters.Remove(index);
		popup.GetComponent<PopupScript>().IncreaseMoney (-index.costtobuy);
		popup.GetComponent<PopupScript> ().IncreasePopularityGeneral (index.numowned);
		makeRows ();
	}