protected override string GetCurrentValue() =>
     ThisControl.Mode == DataMode.ManageCandidates
 ? ElectionsPoliticians.GetIsIncumbentByElectionKeyOfficeKeyPoliticianKey(
         ThisControl.SafeGetElectionKey(), ThisControl.SafeGetOfficeKey(),
         ThisControl.GetPoliticianKeyToEdit(), false)
     .ToString()
 : string.Empty;
Beispiel #2
0
 public void GetData(string electionKey, string congress, string stateSenate,
                     string stateHouse, string countyCode)
 {
     ElectionKey = electionKey;
     DataTable   = ElectionsPoliticians.GetSampleBallotData(electionKey, congress,
                                                            stateSenate, stateHouse, countyCode);
 }
Beispiel #3
0
        private static void MergePrimaryWinners(string generalElectionKey,
                                                DateTime primaryElectionDate, bool isRunoff, ref int candidateDuplicates,
                                                ref int candidatesAdded)
        {
            var offices = ElectionsPoliticians
                          .GetPrimaryWinnersForGeneralElection(generalElectionKey, primaryElectionDate,
                                                               isRunoff).GroupBy(r => r.OfficeKey);

            foreach (var o in offices)
            {
                foreach (var c in o)
                {
                    if (ElectionsPoliticians.ElectionKeyOfficeKeyPoliticianKeyExists(
                            generalElectionKey, c.OfficeKey, c.PoliticianKey))
                    {
                        candidateDuplicates++;
                    }
                    else
                    {
                        Elections.ActualizeElection(generalElectionKey);
                        ActualizeElectionOffice(generalElectionKey, c.OfficeKey);
                        ElectionsPoliticians.Insert(generalElectionKey, c.OfficeKey, c.PoliticianKey,
                                                    c.RunningMateKey, Elections.GetStateElectionKeyFromKey(generalElectionKey),
                                                    Empty, c.StateCode, c.CountyCode, c.LocalKey, c.DistrictCode, 0, false,
                                                    OfficesOfficials.OfficeKeyPoliticianKeyExists(c.OfficeKey, c.PoliticianKey),
                                                    false, Empty, null, null, null, Empty, false, DefaultDbDate, Empty, Empty, false);
                        candidatesAdded++;
                    }
                }
            }
        }
Beispiel #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var query = Request.Url.Query;

            if (IsNullOrWhiteSpace(query))
            {
                Utility.Signal404();
            }
            var info = Server.UrlDecode(query.Substring(1))?.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            Debug.Assert(info != null, nameof(info) + " != null");
            if (info.Length < 3)
            {
                Utility.Signal404();
            }
            var electionKey   = info[0];
            var officeKey     = info[1];
            var politicianKey = info[2];

            var blob = ElectionsPoliticians.GetAdImage(electionKey, officeKey, politicianKey);

            if (blob == null)
            {
                Utility.Signal404();
            }
            ServeImage(blob);
        }
        private Control GenerateOneCandidateVideoContent(string electionKey, string officeKey,
                                                         string politicianKey)
        {
            var container = new PlaceHolder();

            _IssuesDataManager.GetCandidateVideoData(electionKey, officeKey, politicianKey);
            // for older elections show all responese
            var electionDate    = Elections.GetElectionDateFromKey(electionKey);
            var oldAnswerCutoff = electionDate > DateTime.UtcNow.AddMonths(-6)
        ? ElectionsOffices.GetOldAnswerCutoffDate(electionKey, officeKey)
        : DateTime.MinValue;
            var issuesData = _IssuesDataManager.GetDataSubset()
                             .Where(r => r.YouTubeDate() >= oldAnswerCutoff);

            //var isRunningMateOffice = Offices.GetIsRunningMateOffice(officeKey, false) &&
            //  !Elections.IsPrimaryElection(electionKey);
            var isRunningMateOffice = Offices.IsRunningMateOfficeInElection(electionKey, officeKey);

            var     politician  = Politicians.GetPoliticianIntroReportData(politicianKey);
            DataRow runningMate = null;

            var    name            = Politicians.FormatName(politician);
            string runningMateKey  = null;
            string runningMateName = null;

            if (isRunningMateOffice)
            {
                //var cache = PageCache.GetTemporary();
                //name = cache.Politicians.GetPoliticianName(politicianKey);
                runningMateKey = ElectionsPoliticians
                                 .GetRunningMateKeyByElectionKeyOfficeKeyPoliticianKey(
                    electionKey, officeKey, politicianKey);
                runningMate = Politicians.GetPoliticianIntroReportData(runningMateKey);
                //runningMateName = cache.Politicians.GetPoliticianName(runningMateKey);
                runningMateName = Politicians.FormatName(runningMate);
            }

            var videos = issuesData
                         .Where(r => r.PoliticianKey().IsEqIgnoreCase(politicianKey)).ToList();
            var qas = GetQuestionAndAnswerList(videos, politician, true, true);

            if (qas.Any())
            {
                ReportCandidateVideos(container, politician, qas, name, isRunningMateOffice);
            }

            if (!IsNullOrWhiteSpace(runningMateKey))
            {
                var runningMateVideos = issuesData
                                        .Where(r => r.PoliticianKey().IsNeIgnoreCase(politicianKey)).ToList();
                qas = GetQuestionAndAnswerList(runningMateVideos, runningMate, true, true);
                if (qas.Any())
                {
                    ReportCandidateVideos(container, runningMate, qas, runningMateName, true);
                }
            }

            return(container);
        }
   public void GetCandidateVideoData(string electionKey, string officeKey, string politicianKey)
   {
       DataTable = VotePage.EnableIssueGroups
 ? ElectionsPoliticians.GetCompareCandidateVideosNew3(electionKey, officeKey,
                                                      politicianKey)
 : ElectionsPoliticians.GetCompareCandidateVideosNew(electionKey, officeKey,
                                                     politicianKey);
   }
Beispiel #7
0
 private void CopyRunoffAdvancers()
 {
     try
     {
         bool success;
         var  candidatesAdded   = 0;
         var  officesAdded      = 0;
         var  runoffElectionKey = GetElectionKey();
         if (!Elections.IsRunoffElection(runoffElectionKey))
         {
             throw new VoteException("This function may only be used with runoff elections.");
         }
         var runoffElectionDate =
             Elections.GetElectionDateFromKey(runoffElectionKey);
         var previousElectionDate = FeedbackMasterOnly.ValidateDate(
             ControlMasterOnlyElectionDateToCopy, out success,
             "Previous Election Date", runoffElectionDate.AddYears(-1),
             runoffElectionDate.AddDays(-7));
         if (!success)
         {
             return;
         }
         var offices =
             ElectionsPoliticians.GetRunoffAdvancersForElection(
                 runoffElectionKey, previousElectionDate)
             .GroupBy(r => r.OfficeKey);
         ElectionsOffices.DeleteByElectionKey(runoffElectionKey);
         ElectionsPoliticians.DeleteByElectionKey(runoffElectionKey);
         foreach (var o in offices)
         {
             var office = o.First();
             InsertElectionOffice(runoffElectionKey, office.OfficeKey);
             officesAdded++;
             foreach (var c in o)
             {
                 ElectionsPoliticians.Insert(runoffElectionKey, c.OfficeKey,
                                             c.PoliticianKey, c.RunningMateKey,
                                             Elections.GetStateElectionKeyFromKey(runoffElectionKey),
                                             string.Empty,
                                             Elections.GetCountyElectionKeyFromKey(runoffElectionKey),
                                             Elections.GetLocalElectionKeyFromKey(runoffElectionKey), c.StateCode,
                                             c.CountyCode, c.LocalCode, c.DistrictCode, 0, false,
                                             OfficesOfficials.OfficeKeyPoliticianKeyExists(c.OfficeKey,
                                                                                           c.PoliticianKey), false);
                 candidatesAdded++;
             }
         }
         FeedbackMasterOnly.AddInfo(
             $"{candidatesAdded} candidates were added, {officesAdded} offices were added.");
     }
     catch (Exception ex)
     {
         FeedbackMasterOnly.PostValidationError(ControlMasterOnlyPrimaryDateToCopy,
                                                "The candidates could not be copied: " + ex.Message);
     }
 }
Beispiel #8
0
 protected override bool Update(object newValue)
 {
     if (Column != "AdImageChanged" && Column != "AdImageUpdated")
     {
         ElectionsPoliticians.UpdateColumn(ElectionsPoliticians.GetColumn(Column), newValue,
                                           ThisControl.SafeGetElectionKey(), ThisControl.SafeGetOfficeKey(),
                                           ThisControl.AdSetupCandidate.Value);
     }
     return(true);
 }
Beispiel #9
0
 protected override string GetCurrentValue()
 {
     if (Column == "AdImageChanged" || Column == "AdImageUpdated")
     {
         return("False"); // always unchanged from db
     }
     return(ToDisplay(ElectionsPoliticians.GetColumn(ElectionsPoliticians.GetColumn(Column),
                                                     ThisControl.SafeGetElectionKey(), ThisControl.SafeGetOfficeKey(),
                                                     ThisControl.AdSetupCandidate.Value)));
 }
Beispiel #10
0
 public static List <SimpleListItem> GetPreviewCandidateItems(string electionKey,
                                                              string officeKey)
 {
     return(new List <SimpleListItem> {
         new SimpleListItem(Empty, "<none>")
     }.Union(
                ElectionsPoliticians.GetPoliticiansForOfficeInElection(electionKey, officeKey).Rows
                .Cast <DataRow>().Select(row =>
                                         new SimpleListItem(row.PoliticianKey(), Politicians.FormatName(row)))).ToList());
 }
 protected override bool Update(object newValue)
 {
     if (ThisControl.Mode == DataMode.ManageCandidates)
     {
         ElectionsPoliticians.UpdateIsIncumbentByElectionKeyOfficeKeyPoliticianKey(
             (bool)newValue, ThisControl.SafeGetElectionKey(), ThisControl.SafeGetOfficeKey(),
             ThisControl.GetPoliticianKeyToEdit());
     }
     return(true);
 }
Beispiel #12
0
            //public void GetData(string electionKey, string congress, string stateSenate,
            //  string stateHouse, string countyCode)
            //{
            //  _StateCode = Elections.GetStateCodeFromKey(electionKey);
            //  ElectionKey = electionKey;
            //  DataTable = ElectionsPoliticians.GetSampleBallotData(electionKey, congress,
            //    stateSenate, stateHouse, countyCode);
            //}

            public void GetData(string electionKey, string congress, string stateSenate,
                                string stateHouse, string countyCode, string district, string place, string elementary,
                                string secondary, string unified, string cityCouncil, string countySupervisors,
                                string schoolDistrictDistrict)
            {
                //_StateCode = Elections.GetStateCodeFromKey(electionKey);
                ElectionKey = electionKey;
                DataTable   = ElectionsPoliticians.GetSampleBallotData(electionKey, congress, stateSenate,
                                                                       stateHouse, countyCode, district, place, elementary, secondary, unified, cityCouncil,
                                                                       countySupervisors, schoolDistrictDistrict);
            }
            public void GetData(string partyKey, string electionKey)
            {
                var electionKeys   = new List <string>(new[] { electionKey });
                var altElectionKey = Elections.GetElectionKeyToInclude(electionKey);

                if (!string.IsNullOrWhiteSpace(altElectionKey))
                {
                    electionKeys.Add(altElectionKey);
                }
                DataTable = ElectionsPoliticians.GetPartyCandidatesInElections(electionKeys, partyKey);
            }
Beispiel #14
0
            protected override bool Update(object newValue)
            {
                var electionKey = Page.GetElectionKey();
                var changed     = false;
                var stringValue = newValue.ToString();

                // get the list of officeKeys
                var officeKeys = stringValue.Split(new[] { '|' },
                                                   StringSplitOptions.RemoveEmptyEntries).ToList();

                // actualize any virtuals
                foreach (var officeKey in officeKeys)
                {
                    Offices.ActualizeOffice(officeKey, Page.CountyCode, Page.LocalCode);
                }

                // create a dictionary of office keys from the updated tree
                var officeKeyDictionary = officeKeys
                                          .ToDictionary(ActualizeOfficeKey, key => false, StringComparer.OrdinalIgnoreCase);

                // get the current list of office keys for the election
                var offices = ElectionsOffices.GetOfficeKeysData(electionKey);

                // delete any that aren't in the dictionary (and from
                // ElectionsPoliticians too), and mark those that are there
                // so we know what to add
                foreach (var office in offices)
                {
                    var officeKey = office.OfficeKey;
                    if (officeKeyDictionary.ContainsKey(officeKey))
                    {
                        officeKeyDictionary[officeKey] = true;
                    }
                    else
                    {
                        LogElectionsOfficesDelete(electionKey, officeKey);
                        ElectionsOffices.DeleteByElectionKeyOfficeKey(electionKey, officeKey);
                        ElectionsPoliticians.DeleteByElectionKeyOfficeKey(electionKey,
                                                                          officeKey);
                        changed = true;
                    }
                }

                // add offices from the dictionary that aren't marked
                foreach (var officeKey in officeKeyDictionary.Where(kvp => !kvp.Value)
                         .Select(kvp => kvp.Key))
                {
                    LogElectionsOfficesInsert(electionKey, officeKey);
                    InsertElectionOffice(electionKey, officeKey);
                    changed = true;
                }
                LoadControl();
                return(changed);
            }
        private Control GenerateOneCandidateVideoContent(string electionKey, string officeKey,
                                                         string politicianKey)
        {
            var container = new PlaceHolder();

            _IssuesDataManager.GetCandidateVideoData(electionKey, officeKey, politicianKey);
            var issuesData = _IssuesDataManager.GetDataSubset();

            var isRunningMateOffice = Offices.GetIsRunningMateOffice(officeKey, false) &&
                                      !Elections.IsPrimaryElection(electionKey);

            var     politician  = Politicians.GetPoliticianIntroReportData(politicianKey);
            DataRow runningMate = null;

            var    name            = Politicians.FormatName(politician);
            string runningMateKey  = null;
            string runningMateName = null;

            if (isRunningMateOffice)
            {
                //var cache = PageCache.GetTemporary();
                //name = cache.Politicians.GetPoliticianName(politicianKey);
                runningMateKey = ElectionsPoliticians
                                 .GetRunningMateKeyByElectionKeyOfficeKeyPoliticianKey(
                    electionKey, officeKey, politicianKey);
                runningMate = Politicians.GetPoliticianIntroReportData(runningMateKey);
                //runningMateName = cache.Politicians.GetPoliticianName(runningMateKey);
                runningMateName = Politicians.FormatName(runningMate);
            }

            var videos = issuesData
                         .Where(r => r.PoliticianKey().IsEqIgnoreCase(politicianKey)).ToList();
            var qas = GetQuestionAndAnswerList(videos, politician, true, true);

            if (qas.Any())
            {
                ReportCandidateVideos(container, politician, qas, name, isRunningMateOffice);
            }

            if (!string.IsNullOrWhiteSpace(runningMateKey))
            {
                var runningMateVideos = issuesData
                                        .Where(r => r.PoliticianKey().IsNeIgnoreCase(politicianKey)).ToList();
                qas = GetQuestionAndAnswerList(runningMateVideos, runningMate, true, true);
                if (qas.Any())
                {
                    ReportCandidateVideos(container, runningMate, qas, runningMateName, true);
                }
            }

            return(container);
        }
 private static void DeleteAllDistictReferences(string stateCode, string localKey)
 {
     Elections.DeleteByStateCodeLocalKey(stateCode, localKey);
     ElectionsIncumbentsRemoved.DeleteByStateCodeLocalKey(stateCode, localKey);
     ElectionsOffices.DeleteByStateCodeLocalKey(stateCode, localKey);
     ElectionsPoliticians.DeleteByStateCodeLocalKey(stateCode, localKey);
     QuestionsJurisdictions.DeleteByIssueLevelStateCodeCountyOrLocal(Issues.IssueLevelLocal,
                                                                     stateCode, localKey);
     Offices.DeleteByStateCodeLocalKey(stateCode, localKey);
     //OfficesAllIdentified.DeleteByStateCodeLocalKey(stateCode, localKey);
     OfficesOfficials.DeleteByStateCodeLocalKey(stateCode, localKey);
     Referendums.DeleteByStateCodeLocalKey(stateCode, localKey);
 }
 private static void DeleteAllPoliticianReferences(string politicianKey)
 {
     Answers2.DeleteByPoliticianKey(politicianKey);
     ElectionsIncumbentsRemoved.DeleteByPoliticianKey(politicianKey);
     ElectionsIncumbentsRemoved.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey);
     ElectionsPoliticians.DeleteByPoliticianKey(politicianKey);
     ElectionsPoliticians.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey);
     OfficesOfficials.DeleteByPoliticianKey(politicianKey);
     OfficesOfficials.UpdateRunningMateKeyByRunningMateKey(Empty, politicianKey);
     PoliticiansImagesBlobs.DeleteByPoliticianKey(politicianKey);
     PoliticiansImagesData.DeleteByPoliticianKey(politicianKey);
     TempEmail.DeleteByPoliticianKey(politicianKey);
 }
            public void GetData(string electionKey, string officeKey, string questionKey = null)
            {
                int?questionId = null;

                if (int.TryParse(questionKey, out var id))
                {
                    questionId = id;
                }
                DataTable = VotePage.EnableIssueGroups
          ? ElectionsPoliticians.GetCompareCandidateIssuesNew3(electionKey, officeKey,
                                                               questionId)
          : ElectionsPoliticians.GetCompareCandidateIssuesNew(electionKey, officeKey,
                                                              questionId);
            }
 public List <VoteUsaCandidate> GetVoteUsaCandidates(string electionKey,
                                                     string officeKey) =>
 ElectionsPoliticians
 .GetPoliticiansForOfficeInElection(electionKey, officeKey)
 .Rows.Cast <DataRow>()
 .Select(
     row =>
     new VoteUsaCandidate
 {
     Value      = row.PoliticianKey(),
     Text       = Politicians.FormatName(row),
     FirstThree = row.LastName().Substring(0,
                                           Math.Min(3, row.LastName().Length)).ToLowerInvariant()
 })
 .ToList();
        public static void Update()
        {
            string message;

            try
            {
                VotePage.LogInfo("UpdateSingleCandidateContestWinners", "Started");

                message =
                    $"{ElectionsPoliticians.MarkWinnersForSingleCandidatePastContests(0)} winners updated";
            }
            catch (Exception ex)
            {
                VotePage.LogException("UpdateSingleCandidateContestWinners", ex);
                message = $"Exception: {ex.Message} [see exception log for details]";
            }

            VotePage.LogInfo("UpdateSingleCandidateContestWinners", message);
        }
Beispiel #21
0
        private static void MergePrimaryWinners(string generalElectionKey,
                                                DateTime primaryElectionDate, bool isRunoff, ref int candidateDuplicates,
                                                ref int candidatesAdded /*, ref int candidatesSkippedOfficeMissing*/)
        {
            var offices = ElectionsPoliticians.GetPrimaryWinnersForGeneralElection(
                generalElectionKey, primaryElectionDate, isRunoff)
                          .GroupBy(r => r.OfficeKey);

            foreach (var o in offices)
            {
                //var office = o.First();
                //if (ElectionsOffices.ElectionKeyOfficeKeyExists(generalElectionKey,
                //  office.OfficeKey))
                foreach (var c in o)
                {
                    if (
                        ElectionsPoliticians.ElectionKeyOfficeKeyPoliticianKeyExists(
                            generalElectionKey, c.OfficeKey, c.PoliticianKey))
                    {
                        candidateDuplicates++;
                    }
                    else
                    {
                        Elections.ActualizeElection(generalElectionKey);
                        ActualizeElectionOffice(generalElectionKey, c.OfficeKey);
                        ElectionsPoliticians.Insert(generalElectionKey, c.OfficeKey,
                                                    c.PoliticianKey, c.RunningMateKey,
                                                    Elections.GetStateElectionKeyFromKey(generalElectionKey), string.Empty,
                                                    Elections.GetCountyElectionKeyFromKey(generalElectionKey),
                                                    Elections.GetLocalElectionKeyFromKey(generalElectionKey), c.StateCode,
                                                    c.CountyCode, c.LocalCode, c.DistrictCode, 0, false,
                                                    OfficesOfficials.OfficeKeyPoliticianKeyExists(c.OfficeKey,
                                                                                                  c.PoliticianKey), false);
                        candidatesAdded++;
                    }
                }
                //  else candidatesSkippedOfficeMissing += o.Count();
            }
        }
Beispiel #22
0
        //public static string RenderAds(string electionKey, string officeKey, string adKey = null)
        //{
        //  var table = ElectionsPoliticians.GetAds(electionKey, officeKey, adKey);
        //  if (table.Rows.Count == 0) return Empty;
        //  var ads = new List<string>();
        //  var cache = VotePage.GetPageCache().Politicians;
        //  foreach (var ad in table.Rows.OfType<DataRow>())
        //  {
        //    var thumbnailId = IsNullOrWhiteSpace(ad.AdThumbnailUrl())
        //      ? ad.AdUrl().GetYouTubeVideoId()
        //      : ad.AdThumbnailUrl().GetYouTubeVideoId();
        //    ads.Add(RenderOneAd(ad.PoliticianKey(), cache.GetPoliticianName(ad.PoliticianKey()),
        //      ad.AdUrl(), thumbnailId, ad.AdSponsor(), ad.AdSponsorUrl(), ad.AdIsCandidateSponsored()));
        //  }

        //  return $"<div class=\"ads-outer\">{Join(Empty, ads)}</div>";
        //}

        //public static string RenderOneAd(string politicianKey, string politicianName,
        //  string videoUrl, string thumbnailId, string sponsor, string sponsorUrl, bool isCandidateSponsored)
        //{
        //  string paidMessage;
        //  if (isCandidateSponsored)
        //    paidMessage =
        //      "Paid advertisement by <a target=\"_blank\"" +
        //      $" href=\"{UrlManager.GetIntroPageUri(politicianKey)}\">candidate&rsquo;s campaign</a>";
        //  else if (!IsNullOrWhiteSpace(sponsor))
        //    paidMessage = IsNullOrWhiteSpace(sponsorUrl)
        //      ? $"Paid advertisement by {sponsor}"
        //      : $"Paid advertisement by <a target=\"_blank\" href=\"{VotePage.NormalizeUrl(sponsorUrl)}\">" +
        //        $"{sponsor}</a>";
        //  else
        //    paidMessage = "Paid advertisement";


        //  return "<div class=\"ad-outer\"><div class=\"ad-inner\"><div class=\"ad-copy\">" +
        //    $"<p class=\"ad-name\">{politicianName}</p>" +
        //    $"<p class=\"paid-ad\">{paidMessage}</p></div>" +
        //    $"<a class=\"video-wrapper-outer\" target=\"youtube\" href=\"{VotePage.NormalizeUrl(videoUrl)}\">" +
        //    "<div class=\"video-container\"><div class=\"video-player\"><div>" +
        //    $"<img class=\"video-thumb\" src=\"http://i.ytimg.com/vi/{thumbnailId}/hqdefault.jpg\"/>" +
        //    "<div class=\"video-play-button\"></div></div></div></div></a>" +
        //    $"<img class=\"ad-profile\" src=\"/Image.aspx?Id={politicianKey}&Col=Headshot100\"/>" +
        //    "<div style=\"clear:both\"></div></div></div>";
        //}

        public static string RenderAds(string electionKey, string officeKey, string adKey = null)
        {
            var table = ElectionsPoliticians.GetAds(electionKey, officeKey, adKey);

            if (table.Rows.Count == 0)
            {
                return(Empty);
            }
            var ads   = new List <string>();
            var cache = VotePage.GetPageCache().Politicians;

            foreach (var ad in table.Rows.OfType <DataRow>())
            {
                var thumbnailId = IsNullOrWhiteSpace(ad.AdThumbnailUrl())
          ? ad.AdUrl().GetYouTubeVideoId()
          : ad.AdThumbnailUrl().GetYouTubeVideoId();
                ads.Add(RenderOneAd(electionKey, officeKey, ad.AdType(), ad.PoliticianKey(),
                                    cache.GetPoliticianName(ad.PoliticianKey()), ad.AdUrl(), thumbnailId,
                                    ad.AdSponsor(), ad.AdSponsorUrl(), ad.AdIsCandidateSponsored()));
            }

            return($"<div class=\"ads-outer\">{Join(Empty, ads)}</div>");
        }
Beispiel #23
0
        protected void ButtonAddElection_OnClick(object sender, EventArgs e)
        {
            try
            {
                _AddElectionTabInfo.ClearValidationErrors();
                var electionType      = ControlAddElectionElectionType.SelectedValue;
                var nationalPartyCode = ControlAddElectionNationalParty.SelectedValue;

                var electionDate = ValidateElectionDate(ControlAddElectionElectionDate,
                                                        FeedbackAddElection, ControlAddElectionPastElection.Checked, out var success);
                if (!success)
                {
                    return;
                }

                // if election type is not primary, the nationalPartyCode is always
                // NationalPartyAll
                if (Elections.IsPrimaryElectionType(electionType))
                {
                    FeedbackAddElection.ValidateRequired(ControlAddElectionNationalParty, "Party",
                                                         out success);
                    if (!success)
                    {
                        return;
                    }
                }
                else
                {
                    nationalPartyCode = Parties.NationalPartyAll;
                }

                // special for Presidential candidates
                if (StateCode == "US" && electionType == "A" && nationalPartyCode == "A")
                {
                    electionType = "G";
                }

                // This tab is now for state elections only
                var newElectionKey = Elections.FormatElectionKey(electionDate, electionType,
                                                                 nationalPartyCode, StateCode);

                // Make sure the election isn't a duplicate
                if (Elections.ElectionKeyExists(newElectionKey))
                {
                    PostAddElectionValidationError("This election already exists.");
                    return;
                }

                // for ElectionTypeStatePrimary, we need to check party conflicts:
                //   ● if it's NationalPartyNonPartisan, there can't be other party primaries
                //     on the same day
                //   ● if it's not NationalPartyNonPartisan, there can't be a NationalPartyNonPartisan
                //     on the same day
                // It is necessary to allow this sometimes, so this has been replaced by a client-side
                // warning/override
                var alreadyHasPartyPrimary = false;
                if (electionType == Elections.ElectionTypeStatePrimary)
                {
                    alreadyHasPartyPrimary = Elections.GetPartyPrimaryExists(StateCode, electionDate);
                }

                bool addPresident;
                switch (electionType)
                {
                case Elections.ElectionTypeStatePresidentialPrimary:
                case Elections.ElectionTypeUSPresidentialPrimary:
                    addPresident = true;
                    break;

                case Elections.ElectionTypeStatePrimary:
                    addPresident = ControlAddElectionIncludePresident.Checked;
                    break;

                case Elections.ElectionTypeGeneralElection:
                    addPresident = StateCode == "US" && nationalPartyCode == "A";
                    break;

                default:
                    addPresident = false;
                    break;
                }

                var includePresidentialCandidates = false;
                if (addPresident && electionType != Elections.ElectionTypeUSPresidentialPrimary)
                {
                    includePresidentialCandidates = ControlAddElectionIncludePresidentCandidates
                                                    .Checked;
                }

                var electionKeyToCopyOfficesAndDatesFrom = Empty;
                if (electionType == Elections.ElectionTypeStatePrimary)
                {
                    electionKeyToCopyOfficesAndDatesFrom = AddElectionCopyOfficesHidden.Value.Trim();
                }

                var copyCandidates = ControlAddElectionCopyCandidates.Checked;

                // Build the tables to add

                var electionsTable            = new ElectionsTable();
                var electionsOfficesTable     = new ElectionsOfficesTable();
                var electionsPoliticiansTable = new ElectionsPoliticiansTable();

                LogElectionsInsert(newElectionKey);

                // The election
                InsertElection(electionsTable, newElectionKey,
                               electionKeyToCopyOfficesAndDatesFrom);

                // Offices
                if (addPresident)
                {
                    InsertOffice(electionsOfficesTable, newElectionKey, Offices.USPresident,
                                 OfficeClass.USPresident, Empty);
                }

                if (!IsNullOrWhiteSpace(electionKeyToCopyOfficesAndDatesFrom))
                {
                    var copyTable =
                        ElectionsOffices.GetOfficeKeysData(electionKeyToCopyOfficesAndDatesFrom);
                    foreach (var row in copyTable.Where(row => row.OfficeKey != Offices.USPresident))
                    {
                        InsertOffice(electionsOfficesTable, newElectionKey, row.OfficeKey,
                                     row.OfficeLevel.ToOfficeClass(), row.DistrictCode);
                    }
                }

                // Candidates
                if (includePresidentialCandidates)
                {
                    var candidateTable =
                        ElectionsPoliticians.GetPresidentialCandidatesFromTemplate(electionDate,
                                                                                   nationalPartyCode);
                    if (candidateTable == null)
                    {
                        throw new ApplicationException($"Presidential candidate template for national party {nationalPartyCode} with date >= {electionDate} not found");
                    }
                    foreach (var row in candidateTable.Rows.OfType <DataRow>())
                    {
                        InsertCandidate(electionsPoliticiansTable, newElectionKey, row.OfficeKey(),
                                        row.PoliticianKey(), row.OrderOnBallot());
                    }
                }

                if (!IsNullOrWhiteSpace(electionKeyToCopyOfficesAndDatesFrom) &&
                    copyCandidates)
                {
                    var candidateTable =
                        ElectionsPoliticians.GetPrimaryCandidatesToCopy(
                            electionKeyToCopyOfficesAndDatesFrom);
                    foreach (var row in candidateTable.Rows.OfType <DataRow>())
                    {
                        InsertCandidate(electionsPoliticiansTable, newElectionKey, row.OfficeKey(),
                                        row.PoliticianKey(), row.OrderOnBallot());
                    }
                }

                Elections.UpdateElectionsAndOffices(electionsTable, electionsOfficesTable,
                                                    electionsPoliticiansTable);

                ReloadElectionControl(newElectionKey);
                _AddElectionTabInfo.Reset();
                FeedbackAddElection.AddInfo(
                    $"Election added: {Elections.FormatElectionDescription(newElectionKey)}");

                if (electionType == Elections.ElectionTypeStatePrimary && !alreadyHasPartyPrimary)
                {
                    FeedbackAddElection.AddInfo(
                        "Your next step is to use the Add/Remove Offices tab to add office contests for" +
                        " this party primary. You can then copy these office for the remaining party primaries.");
                }

                if (!StateCache.IsValidStateCode(StateCode)) // Presidential Primary
                {
                    FeedbackAddElection.AddInfo(
                        "Use the Setup Candidates for Office tab to identify the presidential candidates.");
                }
            }
            catch (Exception ex)
            {
                FeedbackAddElection.HandleException(ex);
            }
        }
Beispiel #24
0
 public void GetData(string electionKey, string congress, string stateSenate, string stateHouse, string countyCode, bool includeOptionalData)
 {
     DataTable = ElectionsPoliticians.GetSampleBallotData(electionKey, congress,
                                                          stateSenate, stateHouse, countyCode, includeOptionalData);
 }
Beispiel #25
0
        protected void ButtonEditPolitician_OnClick(object sender, EventArgs e)
        {
            var toEdit        = GetPoliticianKeyToEdit();
            var politicianKey = toEdit.Key;

            CandidateHtml.Controls.Clear();
            var isRunningMate = !IsNullOrWhiteSpace(MainCandidateIfRunningMate.Value);

            if (Politicians.GetStateCodeFromKey(politicianKey) != "DC")
            {
                AddOnEditElement.AddCssClasses("hidden");
            }

            switch (EditPoliticianReloading.Value)
            {
            case "reloading":
            {
                EditPoliticianReloading.Value = Empty;
                ControlEditPoliticianPartyKey.Items.Clear();
                VotePage.LoadPartiesDropdown(Politicians.GetStateCodeFromKey(politicianKey),
                                             ControlEditPoliticianPartyKey, Empty, VotePage.PartyCategories.None,
                                             VotePage.PartyCategories.StateParties, VotePage.PartyCategories.NationalParties,
                                             VotePage.PartyCategories.NonParties);
                _EditPoliticianDialogInfo.LoadControls();
                FeedbackEditPolitician.AddInfo("Politician information loaded.");
                var href = SecurePoliticianPage.GetUpdateIntroPageUrl(politicianKey);
                UpdateIntroLink.HRef             = href;
                UpdateIntroLinkProfessional.HRef = href + "#bio2-ALLBio333333";
            }
            break;

            case "":
            {
                // normal update
                _EditPoliticianDialogInfo.ClearValidationErrors();
                _EditPoliticianDialogInfo.Update(FeedbackEditPolitician);
                var partyCodeToSuppress = Empty;
                if (isRunningMate)
                {
                    partyCodeToSuppress =
                        Parties.GetPartyCode(
                            Politicians.GetPartyKey(MainCandidateIfRunningMate.Value));
                }
                var row = Politicians.GetCandidateData(SafeGetElectionKey(), politicianKey,
                                                       isRunningMate);
                // use current dynamic IsIncumbent
                row["IsIncumbent"] = toEdit.ShowAsIncumbent;
                CandidateHtml.Controls.Add(CreateCandidateEntry(row, Mode, partyCodeToSuppress,
                                                                !isRunningMate && ElectionsPoliticians.ElectionKeyOfficeKeyPoliticianKeyExists(
                                                                    SafeGetElectionKey(), SafeGetOfficeKey(), politicianKey)));
            }
            break;

            default:
                throw new VoteException(
                          $"Unknown reloading option: '{EditPoliticianReloading.Value}'");
            }

            NameOnBallots.InnerText = PageCache.GetTemporary().Politicians
                                      .GetPoliticianName(politicianKey);
            UpdateIntroPage.SetPartyNameAndLink(ControlEditPoliticianPartyKey.GetValue(),
                                                PartyName);
        }
Beispiel #26
0
            protected override bool Update(object newValue)
            {
                //Parse the value from the UI tree
                var valueStr = newValue as string;

                if (valueStr == null)
                {
                    return(false);
                }
                var offices = valueStr.Split(new[] { '|' },
                                             StringSplitOptions.RemoveEmptyEntries)
                              .Select(officeStr =>
                {
                    var selected    = officeStr[0] == '*';
                    var officeSplit = officeStr.Substring(selected ? 1 : 0)
                                      .Split('=');
                    var isRunoff = officeSplit[1].StartsWith("*", StringComparison.Ordinal);
                    if (isRunoff)
                    {
                        officeSplit[1] = officeSplit[1].Substring(1);
                    }
                    return
                    (new
                    {
                        Selected = selected,
                        OfficeKey = officeSplit[0],
                        IsRunoff = isRunoff,
                        Ids = officeSplit[1].Split(',')
                    });
                });

                var electionKey = Page.GetElectionKey();
                var table       = ElectionsPoliticians.GetWinnersData(electionKey);

                foreach (var o in offices)
                {
                    var office      = o;
                    var politicians = table.Where(row => row.OfficeKey()
                                                  .IsEqIgnoreCase(office.OfficeKey))
                                      .ToList();
                    foreach (var politician in politicians)
                    {
                        if (office.IsRunoff)
                        {
                            var advance = office.Ids.Contains(politician.PoliticianKey,
                                                              StringComparer.OrdinalIgnoreCase);
                            if (politician.AdvanceToRunoff != advance)
                            {
                                LogDataChange.LogUpdate(
                                    ElectionsPoliticians.Column.AdvanceToRunoff,
                                    politician.AdvanceToRunoff, advance, DateTime.UtcNow, electionKey,
                                    politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.AdvanceToRunoff = advance;
                            politician.IsWinner        = false;
                        }
                        else // non-runoff
                        {
                            var isWinner = office.Ids.Contains(politician.PoliticianKey,
                                                               StringComparer.OrdinalIgnoreCase);
                            if (politician.IsWinner != isWinner)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsWinner,
                                                        politician.IsWinner, isWinner, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.IsWinner        = isWinner;
                            politician.AdvanceToRunoff = false;
                        }
                    }
                    if (office.Selected)
                    {
                        // Update incumbents
                        var positions           = Offices.GetPositionsDataByOfficeKey(office.OfficeKey)[0];
                        var incumbents          = OfficesOfficials.GetData(office.OfficeKey);
                        var politicianKeysToAdd = new List <string>(office.Ids.Where(id => id != "vacant"));
                        foreach (var incumbent in incumbents)
                        {
                            var index =
                                politicianKeysToAdd.FindIndex(
                                    key => key.IsEqIgnoreCase(incumbent.PoliticianKey));
                            if (index >= 0)
                            {
                                politicianKeysToAdd.RemoveAt(index);
                            }
                            // we don't remove old incumbents for offices with
                            // Incumbents > ElectionPositions
                            else if (positions.ElectionPositions == positions.Incumbents)
                            {
                                incumbent.Delete();
                            }
                        }
                        foreach (var keyToAdd in politicianKeysToAdd)
                        {
                            var politician =
                                politicians.FirstOrDefault(
                                    row => row.PoliticianKey.IsEqIgnoreCase(keyToAdd));
                            var runningMateKey = politician == null
                ? string.Empty
                : politician.RunningMateKey;
                            incumbents.AddRow(officeKey: office.OfficeKey,
                                              politicianKey: keyToAdd, runningMateKey: runningMateKey,
                                              stateCode: Offices.GetStateCodeFromKey(office.OfficeKey),
                                              countyCode: Offices.GetCountyCodeFromKey(office.OfficeKey),
                                              localCode: Offices.GetLocalCodeFromKey(office.OfficeKey),
                                              districtCode: string.Empty,
                                              //LDSVersion: String.Empty, LDSUpdateDate: DefaultDbDate,
                                              dataLastUpdated: DateTime.UtcNow,
                                              userSecurity: UserSecurityClass, userName: UserName);
                            LogDataChange.LogInsert(OfficesOfficials.TableName, DateTime.UtcNow,
                                                    office.OfficeKey, keyToAdd);
                        }

                        // Update if any changes
                        var incumbentsChanged =
                            incumbents.FirstOrDefault(
                                row => row.RowState != DataRowState.Unchanged) != null;
                        if (incumbentsChanged)
                        {
                            OfficesOfficials.UpdateTable(incumbents);
                        }
                    }
                }

                // Update if any changes
                var winnersChanged =
                    table.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) !=
                    null;

                if (winnersChanged)
                {
                    ElectionsPoliticians.UpdateTable(table,
                                                     ElectionsPoliticiansTable.ColumnSet.Winners);
                }

                LoadControl();
                return(winnersChanged);
            }
            protected override bool Update(object newValue)
            {
                //Parse the value from the UI tree
                if (!(newValue is string valueStr))
                {
                    return(false);
                }
                var offices = valueStr.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(officeStr =>
                {
                    var selected    = officeStr[0] == '*';
                    var officeSplit = officeStr.Substring(selected ? 1 : 0).Split('=');
                    var isRunoff    = officeSplit[1].StartsWith("*", StringComparison.Ordinal);
                    if (isRunoff)
                    {
                        officeSplit[1] = officeSplit[1].Substring(1);
                    }
                    return(new
                    {
                        Selected = selected,
                        OfficeKey = officeSplit[0],
                        IsRunoff = isRunoff,
                        Ids = officeSplit[1].Split(',')
                    });
                });

                var electionKey = Page.GetElectionKey();
                var table       = ElectionsPoliticians.GetWinnersData(electionKey);

                foreach (var o in offices)
                {
                    var office      = o;
                    var politicians = table
                                      .Where(row => row.OfficeKey().IsEqIgnoreCase(office.OfficeKey)).ToList();
                    foreach (var politician in politicians)
                    {
                        if (office.IsRunoff)
                        {
                            var advance = office.Ids.Contains(politician.PoliticianKey,
                                                              StringComparer.OrdinalIgnoreCase);
                            if (politician.AdvanceToRunoff != advance)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.AdvanceToRunoff,
                                                        politician.AdvanceToRunoff, advance, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.AdvanceToRunoff = advance;
                            politician.IsWinner        = false;
                        }
                        else // non-runoff
                        {
                            var isWinner = office.Ids.Contains(politician.PoliticianKey,
                                                               StringComparer.OrdinalIgnoreCase);
                            if (politician.IsWinner != isWinner)
                            {
                                LogDataChange.LogUpdate(ElectionsPoliticians.Column.IsWinner,
                                                        politician.IsWinner, isWinner, DateTime.UtcNow, electionKey,
                                                        politician.OfficeKey, politician.PoliticianKey);
                            }
                            politician.IsWinner        = isWinner;
                            politician.AdvanceToRunoff = false;
                        }
                    }
                    if (office.Selected)
                    {
                        var keys = politicians.Select(p =>
                                                      (politicianKey: p.PoliticianKey, runningMateKey: p.RunningMateKey)).ToList();
                        OfficesOfficials.UpdateIncumbents(office.OfficeKey, office.Ids, keys, UserSecurityClass,
                                                          UserName);
                        //// Update incumbents
                        //var positions = Offices.GetPositionsDataByOfficeKey(office.OfficeKey)[0];
                        //var incumbents = OfficesOfficials.GetData(office.OfficeKey);
                        //var politicianKeysToAdd =
                        //  new List<string>(
                        //    office.Ids.Where(id => id != "vacant" && id != Empty));
                        //foreach (var incumbent in incumbents)
                        //{
                        //  var index =
                        //    politicianKeysToAdd.FindIndex(
                        //      key => key.IsEqIgnoreCase(incumbent.PoliticianKey));
                        //  if (index >= 0) politicianKeysToAdd.RemoveAt(index);
                        //  // we don't remove old incumbents for offices with
                        //  // Incumbents > ElectionPositions
                        //  else if (positions.ElectionPositions == positions.Incumbents)
                        //    incumbent.Delete();
                        //}
                        //foreach (var keyToAdd in politicianKeysToAdd)
                        //{
                        //  var politician =
                        //    politicians.FirstOrDefault(
                        //      row => row.PoliticianKey.IsEqIgnoreCase(keyToAdd));
                        //  var runningMateKey = politician == null
                        //    ? Empty
                        //    : politician.RunningMateKey;
                        //  incumbents.AddRow(office.OfficeKey, keyToAdd, runningMateKey,
                        //    Offices.GetStateCodeFromKey(office.OfficeKey),
                        //    Offices.GetCountyCodeFromKey(office.OfficeKey),
                        //    Offices.GetLocalKeyFromKey(office.OfficeKey), Empty, DateTime.UtcNow,
                        //    UserSecurityClass, UserName);
                        //  LogDataChange.LogInsert(OfficesOfficials.TableName, DateTime.UtcNow,
                        //    office.OfficeKey, keyToAdd);
                        //}

                        //// Update if any changes
                        //var incumbentsChanged =
                        //  incumbents.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) !=
                        //  null;
                        //if (incumbentsChanged) OfficesOfficials.UpdateTable(incumbents);
                    }
                }

                // Update if any changes
                var winnersChanged =
                    table.FirstOrDefault(row => row.RowState != DataRowState.Unchanged) != null;

                if (winnersChanged)
                {
                    ElectionsPoliticians.UpdateTable(table,
                                                     ElectionsPoliticiansTable.ColumnSet.Winners);
                }

                LoadControl();
                return(winnersChanged);
            }
Beispiel #28
0
        private void Consolidate()
        {
            try
            {
                var key1Item        = _MasterOnlyTabInfo.Single(i => i.Column == "Key1");
                var key2Item        = _MasterOnlyTabInfo.Single(i => i.Column == "Key2");
                var jurisdictionKey = JurisdictionalKey;

                var success = true;

                success &= DataItemBase.ValidateRequired(key1Item);
                var key1Office = key1Item.DataControl.GetValue().Trim();

                success &= DataItemBase.ValidateRequired(key2Item);
                var key2Office = key2Item.DataControl.GetValue().Trim();

                if (success && key1Office.IsEqIgnoreCase(key2Office))
                {
                    key2Item.Feedback.PostValidationError(key2Item.DataControl, key2Item.Description +
                                                          " is identical to " + key1Item.Description);
                    success = false;
                }

                var officeKey1 = jurisdictionKey + key1Office;
                var officeKey2 = jurisdictionKey + key2Office;

                if (!success)
                {
                    return;
                }

                // do the consolidation
                var updateCount = 0;

                if (Offices.OfficeKeyExists(officeKey1))
                {
                    updateCount += Offices.DeleteByOfficeKey(officeKey2);
                }
                else
                {
                    updateCount += Offices.UpdateOfficeKey(officeKey1, officeKey2);
                }
                foreach (var row in ElectionsOffices.GetDataByOfficeKey(officeKey2))
                {
                    if (ElectionsOffices.ElectionKeyOfficeKeyExists(row.ElectionKey, officeKey1))
                    {
                        updateCount += ElectionsOffices.DeleteByElectionKeyOfficeKey(row.ElectionKey, officeKey2);
                    }
                    else
                    {
                        updateCount += ElectionsOffices.UpdateOfficeKeyByElectionKeyOfficeKey(officeKey1,
                                                                                              row.ElectionKey, officeKey2);
                    }
                }
                foreach (var row in ElectionsPoliticians.GetDataByOfficeKey(officeKey2))
                {
                    if (ElectionsPoliticians.ElectionKeyOfficeKeyPoliticianKeyExists(row.ElectionKey,
                                                                                     officeKey1, row.PoliticianKey))
                    {
                        updateCount += ElectionsPoliticians.DeleteByElectionKeyOfficeKeyPoliticianKey(
                            row.ElectionKey, officeKey2, row.PoliticianKey);
                    }
                    else
                    {
                        updateCount += ElectionsPoliticians.UpdateOfficeKeyByElectionKeyOfficeKeyPoliticianKey(
                            officeKey1, row.ElectionKey, officeKey2, row.PoliticianKey);
                    }
                }
                foreach (var row in OfficesOfficials.GetDataByOfficeKey(officeKey2))
                {
                    if (OfficesOfficials.OfficeKeyPoliticianKeyExists(officeKey1, row.PoliticianKey))
                    {
                        updateCount += OfficesOfficials.DeleteByOfficeKeyPoliticianKey(officeKey2,
                                                                                       row.PoliticianKey);
                    }
                    else
                    {
                        updateCount += OfficesOfficials.UpdateOfficeKeyByOfficeKeyPoliticianKey(officeKey1,
                                                                                                officeKey2, row.PoliticianKey);
                    }
                }
                foreach (var row in ElectionsIncumbentsRemoved.GetDataByOfficeKey(officeKey2))
                {
                    if (ElectionsIncumbentsRemoved.ElectionKeyOfficeKeyPoliticianKeyExists(row.ElectionKey,
                                                                                           officeKey1, row.PoliticianKey))
                    {
                        updateCount += ElectionsIncumbentsRemoved.DeleteByElectionKeyOfficeKeyPoliticianKey(
                            row.ElectionKey, officeKey2, row.PoliticianKey);
                    }
                    else
                    {
                        updateCount += ElectionsIncumbentsRemoved
                                       .UpdateOfficeKeyByElectionKeyOfficeKeyPoliticianKey(
                            officeKey1, row.ElectionKey, officeKey2, row.PoliticianKey);
                    }
                }
                updateCount += Politicians.UpdateOfficeKeyByOfficeKey(officeKey1, officeKey2);

                var msg = $"{updateCount} instances of the second office key {officeKey2} were found.";
                if (updateCount > 0)
                {
                    msg += $" They were all changed to the first office key {officeKey1}.";
                }
                FeedbackMasterOnly.AddInfo(msg);
                ResetMasterOnlySubTab(MasterOnlySubTab.Consolidate);
            }
            catch (Exception ex)
            {
                FeedbackMasterOnly.PostValidationError(ControlMasterOnlyNewKey,
                                                       "The office keys could not be consolidated: " + ex.Message);
            }
        }
Beispiel #29
0
        private void ChangeOfficeKey()
        {
            try
            {
                var oldKeyItem      = _MasterOnlyTabInfo.Single(i => i.Column == "OldKey");
                var newKeyItem      = _MasterOnlyTabInfo.Single(i => i.Column == "NewKey");
                var jurisdictionKey = JurisdictionalKey;

                var success = true;

                success &= DataItemBase.ValidateRequired(oldKeyItem);
                var oldKeyOffice = oldKeyItem.DataControl.GetValue().Trim();

                success &= DataItemBase.ValidateRequired(newKeyItem);
                var newKeyOffice = newKeyItem.DataControl.GetValue().Trim();
                if (!string.IsNullOrWhiteSpace(newKeyOffice))
                {
                    // get rid of all non-alphanumerics
                    newKeyOffice = Regex.Replace(newKeyOffice, @"[^\dA-Z]", string.Empty,
                                                 RegexOptions.IgnoreCase);
                    // get rid of leading numerics
                    newKeyOffice = Regex.Replace(newKeyOffice, @"^\d+", string.Empty);
                    var maxLength = Offices.OfficeKeyMaxLength - jurisdictionKey.Length;
                    if (newKeyOffice.Length > maxLength)
                    {
                        newKeyItem.Feedback.PostValidationError(newKeyItem.DataControl, newKeyItem.Description +
                                                                " is too long by " + (newKeyOffice.Length - maxLength) + " characters.");
                        success = false;
                    }
                    if (newKeyOffice.Length == 0)
                    {
                        newKeyItem.Feedback.PostValidationError(newKeyItem.DataControl, newKeyItem.Description +
                                                                " consists entirely of non-key characters.");
                        success = false;
                    }
                }

                if (success && (oldKeyOffice == newKeyOffice))
                {
                    newKeyItem.Feedback.PostValidationError(newKeyItem.DataControl, newKeyItem.Description +
                                                            " is identical to the Old Office Key.");
                    success = false;
                }

                var oldOfficeKey   = jurisdictionKey + oldKeyOffice;
                var newOfficeKey   = jurisdictionKey + newKeyOffice;
                var caseChangeOnly = oldOfficeKey.IsEqIgnoreCase(newOfficeKey);

                if (success && !caseChangeOnly)
                {
                    // Make sure the new office key doesn't already exist
                    var existsInTables = new List <string>();
                    if (Offices.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(Offices.TableName);
                    }
                    if (ElectionsOffices.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(ElectionsOffices.TableName);
                    }
                    if (ElectionsPoliticians.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(ElectionsPoliticians.TableName);
                    }
                    if (OfficesOfficials.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(OfficesOfficials.TableName);
                    }
                    if (ElectionsIncumbentsRemoved.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(ElectionsIncumbentsRemoved.TableName);
                    }
                    if (Politicians.OfficeKeyExists(newOfficeKey))
                    {
                        existsInTables.Add(Politicians.TableName);
                    }

                    if (existsInTables.Count > 0)
                    {
                        newKeyItem.Feedback.PostValidationError(newKeyItem.DataControl, newKeyItem.Description +
                                                                " already exists in the following tables: " + string.Join(", ", existsInTables));
                        success = false;
                    }
                }

                if (!success)
                {
                    return;
                }

                // do the replacement
                var updateCount = 0;

                updateCount += Offices.UpdateOfficeKey(newOfficeKey, oldOfficeKey);
                updateCount += ElectionsOffices.UpdateOfficeKeyByOfficeKey(newOfficeKey, oldOfficeKey);
                updateCount += ElectionsPoliticians.UpdateOfficeKeyByOfficeKey(newOfficeKey, oldOfficeKey);
                updateCount += OfficesOfficials.UpdateOfficeKeyByOfficeKey(newOfficeKey, oldOfficeKey);
                updateCount += ElectionsIncumbentsRemoved.UpdateOfficeKeyByOfficeKey(newOfficeKey,
                                                                                     oldOfficeKey);
                updateCount += Politicians.UpdateOfficeKeyByOfficeKey(newOfficeKey, oldOfficeKey);

                var msg = $"{updateCount} instances of the old office key {oldOfficeKey} were found.";
                if (updateCount > 0)
                {
                    msg += $" They were all changed to the new office key {newOfficeKey}.";
                }
                FeedbackMasterOnly.AddInfo(msg);
                ResetMasterOnlySubTab(MasterOnlySubTab.ChangeKey);
            }
            catch (Exception ex)
            {
                FeedbackMasterOnly.PostValidationError(ControlMasterOnlyNewKey,
                                                       "The office key could not be changed: " + ex.Message);
            }
        }
        private void DoConsolidation()
        {
            try
            {
                var    selectedIndex = ConsolidateSelectedIndex.Value;
                string selectedKey;
                string unselectedKey;
                switch (selectedIndex)
                {
                case "1":
                    selectedKey   = ConsolidateKey1.Value;
                    unselectedKey = ConsolidateKey2.Value;
                    break;

                case "2":
                    selectedKey   = ConsolidateKey2.Value;
                    unselectedKey = ConsolidateKey1.Value;
                    break;

                default:
                    throw new VoteException("Index not 1 or 2");
                }

                //throw new VoteException("An error");

                // Politicians
                var selectedPolitician   = Politicians.GetData(selectedKey);
                var unselectedPolitician = Politicians.GetData(unselectedKey);
                if (selectedPolitician.Count != 1)
                {
                    throw new VoteException("Politician " + selectedPolitician + " not found");
                }
                if (unselectedPolitician.Count != 1)
                {
                    throw new VoteException("Politician " + unselectedKey + " not found");
                }
                var selectedData = UpdatePoliticians(selectedIndex, selectedPolitician, unselectedPolitician);

                // PoliticiansImagesData and PoliticiansImagesBlobs
                var selectedImagesData    = PoliticiansImagesData.GetData(selectedKey);
                var unselectedImagesData  = PoliticiansImagesData.GetData(unselectedKey);
                var selectedImagesBlobs   = PoliticiansImagesBlobs.GetData(selectedKey);
                var unselectedImagesBlobs = PoliticiansImagesBlobs.GetData(unselectedKey);
                UpdateImages(selectedIndex, selectedData, selectedKey, selectedImagesData,
                             selectedImagesBlobs, unselectedImagesData, unselectedImagesBlobs);

                // Answers
                var selectedAnswers   = Answers.GetActiveDataByPoliticianKey(selectedKey);
                var unselectedAnswers = Answers.GetDataByPoliticianKey(unselectedKey);
                UpdateAnswers(selectedKey, selectedAnswers, unselectedAnswers);

                // ElectionsIncumbentsRemoved
                var selectedIncumbentsRemoved =
                    ElectionsIncumbentsRemoved.GetDataByPoliticianKey(selectedKey);
                var unselectedIncumbentsRemoved =
                    ElectionsIncumbentsRemoved.GetDataByPoliticianKey(unselectedKey);
                UpdateIncumbentsRemoved(selectedKey, unselectedIncumbentsRemoved, selectedIncumbentsRemoved);

                // ElectionsPoliticians
                var selectedElectionsPoliticians   = ElectionsPoliticians.GetDataByPoliticianKey(selectedKey);
                var unselectedElectionsPoliticians =
                    ElectionsPoliticians.GetDataByPoliticianKey(unselectedKey);
                UpdateElectionsPoliticians(selectedKey, unselectedElectionsPoliticians,
                                           selectedElectionsPoliticians);

                // OfficesOfficials
                var selectedOfficesOfficials   = OfficesOfficials.GetDataByPoliticianKey(selectedKey);
                var unselectedOfficesOfficials = OfficesOfficials.GetDataByPoliticianKey(unselectedKey);
                UpdateOfficesOfficials(selectedKey, unselectedOfficesOfficials, selectedOfficesOfficials);

                // Update everything as one transaction, politicians last
                PoliticiansImagesData.UpdateTable(selectedImagesData);
                PoliticiansImagesData.UpdateTable(unselectedImagesData);
                PoliticiansImagesBlobs.UpdateTable(selectedImagesBlobs);
                PoliticiansImagesBlobs.UpdateTable(unselectedImagesBlobs);
                Answers.UpdateTable(selectedAnswers);
                Answers.UpdateTable(unselectedAnswers);
                ElectionsIncumbentsRemoved.UpdateTable(unselectedIncumbentsRemoved);
                ElectionsPoliticians.UpdateTable(unselectedElectionsPoliticians);
                OfficesOfficials.UpdateTable(unselectedOfficesOfficials);
                Politicians.UpdateTable(selectedPolitician);
                Politicians.UpdateTable(unselectedPolitician);

                // Log
                LogDataChange.LogUpdate("*ConsolidatePoliticians", "*Various", unselectedKey, selectedKey,
                                        VotePage.UserName, SecurePage.UserSecurityClass, DateTime.UtcNow, selectedKey);

                // After the main update, refresh the LiveOfficeKey, LiveOfficeStatus and LiveElectionKey
                var view = PoliticiansLiveOfficeKeyView.GetData(selectedKey);
                if (view.Count == 1)
                {
                    var keyAndStatus =
                        PoliticianOfficeStatus.FromLiveOfficeKeyAndStatus(
                            view[0].LiveOfficeKeyAndStatus);
                    selectedPolitician[0].LiveOfficeKey    = keyAndStatus.OfficeKey;
                    selectedPolitician[0].LiveOfficeStatus = keyAndStatus.PoliticianStatus.ToString();
                    selectedPolitician[0].LiveElectionKey  = keyAndStatus.ElectionKey;
                    Politicians.UpdateTable(selectedPolitician);
                }
                ConsolidateReloaded.Value = "ok";
            }
            catch (Exception ex)
            {
                FeedbackConsolidate.AddError("There was an unexpected error: " + ex.Message);
            }
        }