public override void LoadControl()
            {
                OfficeCount = 0;
                var table = Elections.GetWinnersData(Page.GetElectionKey());
                var incumbentsToEliminate =
                    ElectionsOffices.GetOfficesWithCandidatesToEliminate(Page.GetElectionKey());

                if (table.Rows.Count == 0)
                {
                    Page.IdentifyWinnersMessage.RemoveCssClass("hidden");
                    Page.IdentifyWinnersInstructions.RemoveCssClass("hidden");
                    Page.IdentifyWinnersControl.AddCssClasses("hidden");
                    Page.IdentifyWinnersMessage.InnerHtml = "No offices were found for this election";
                }
                else if (incumbentsToEliminate.Count > 0)
                {
                    Page.IdentifyWinnersMessage.RemoveCssClass("hidden");
                    Page.IdentifyWinnersInstructions.AddCssClasses("hidden");
                    Page.IdentifyWinnersControl.AddCssClasses("hidden");
                    Page.IdentifyWinnersMessage.InnerHtml =
                        "<em>There are too many incumbents for the following offices:</em><br/><br/>" +
                        Join("<br/>",
                             incumbentsToEliminate.Select(g => Offices.FormatOfficeName(g.First()))) +
                        "<br/><br/><em>Please use the </em>Adjust Incumbents<em> tab to remove the extra incumbents or use the </em>Add/Remove Offices<em> tab to remove the office contest.</em>";
                }
                else
                {
                    Page.IdentifyWinnersMessage.AddCssClasses("hidden");
                    Page.IdentifyWinnersInstructions.RemoveCssClass("hidden");
                    Page.IdentifyWinnersControl.RemoveCssClass("hidden");
                    OfficeCount =
                        Page.PopulateWinnersTree(table, Page.PlaceHolderIdentifyWinnersTree);
                }
            }
Esempio n. 2
0
 private static void ActualizeElectionOffice(string electionKey, string officeKey)
 {
     if (!ElectionsOffices.ElectionKeyOfficeKeyExists(electionKey, officeKey))
     {
         InsertElectionOffice(electionKey, officeKey);
     }
 }
        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 List <SimpleListItem> GetVoteUsaOffices(string electionKey) => ElectionsOffices
 .GetElectionOffices(electionKey)
 .Rows.Cast <DataRow>()
 .Select(
     row =>
     new SimpleListItem(row.OfficeKey(),
                        Offices.FormatOfficeName(row)))
 .ToList();
Esempio n. 5
0
 public static List <SimpleListItem> GetPreviewOfficeItems(string electionKey)
 {
     return(new List <SimpleListItem> {
         new SimpleListItem(Empty, "<none>")
     }.Union(
                ElectionsOffices.GetElectionOffices(electionKey).Rows.Cast <DataRow>().Select(row =>
                                                                                              new SimpleListItem(row.OfficeKey(), Offices.FormatOfficeName(row)))).ToList());
 }
Esempio n. 6
0
        private void GetLocalElections(Control container, string countyElectionKey)
        {
            var stateCode        = Elections.GetStateCodeFromKey(countyElectionKey);
            var countyCode       = Elections.GetCountyCodeFromKey(countyElectionKey);
            var stateElectionKey = Elections.GetStateElectionKeyFromKey(countyElectionKey);

            // We get a dictionary of locals with elections that match the stateElectionKey
            // Key: localCode; Value: local electionKey
            // Locals without an election will not be in the dictionary
            var localElectionDictionary =
                ElectionsOffices.GetLocalElections(stateElectionKey, countyCode);
            // We can't forget the Ballot Measures...
            var localReferendumDictionary =
                Referendums.GetLocalElections(stateElectionKey, countyCode);

            // merge them into the first dictionary
            foreach (var kvp in localReferendumDictionary)
            {
                if (!localElectionDictionary.ContainsKey(kvp.Key))
                {
                    localElectionDictionary.Add(kvp.Key, kvp.Value);
                }
            }
            if (localElectionDictionary.Count == 0)
            {
                return;
            }

            // We also get a dictionary of all local names for the county
            var localNamesDictionary = LocalDistricts.GetNamesDictionary(stateCode,
                                                                         countyCode);

            new HtmlDiv {
                InnerText = "Local District Elections"
            }.AddTo(container, "accordion-header");
            var content = new HtmlDiv().AddTo(container, "category-content accordion-content");

            // For reporting we filter only locals with elections and sort by name,
            var locals = localNamesDictionary.Where(
                kvp => localElectionDictionary.ContainsKey(kvp.Key))
                         .OrderBy(kvp => kvp.Value)
                         .ToList();

            foreach (var kvp in locals)
            {
                var localCode        = kvp.Key;
                var localName        = kvp.Value;
                var localElectionKey = localElectionDictionary[localCode];

                new HtmlDiv {
                    InnerText = localName
                }.AddTo(content, "accordion-header");
                new ElectionReportResponsive().GenerateReport(ReportUser, localElectionKey)
                .AddTo(content, "accordion-content");
            }
        }
Esempio n. 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);
     }
 }
Esempio n. 8
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);
            }
Esempio n. 9
0
        private void GetCountyElections(Control container, string stateElectionKey)
        {
            var stateCode = Elections.GetStateCodeFromKey(stateElectionKey);

            // We get a dictionary of counties with elections that match the stateElectionKey
            // Key: countyCode; Value: county electionKey
            // Counties without an election will not be in the dictionary
            // We include local elections too, to account for situations where there is no county
            // election but there are local elections.
            var countyElectionDictionary =
                ElectionsOffices.GetCountyAndLocalElections(stateElectionKey);
            // We can't forget the Ballot Measures...
            var countyReferendumDictionary =
                Referendums.GetCountyAndLocalElections(stateElectionKey);

            // merge them into the first dictionary
            foreach (var kvp in countyReferendumDictionary)
            {
                if (!countyElectionDictionary.ContainsKey(kvp.Key))
                {
                    countyElectionDictionary.Add(kvp.Key, kvp.Value);
                }
            }
            if (countyElectionDictionary.Count == 0)
            {
                return;
            }

            new HtmlDiv {
                InnerText = "County Elections"
            }.AddTo(container, "accordion-header");
            var content = new HtmlDiv().AddTo(container, "category-content accordion-content");

            // For reporting we start with all counties for the state (it will be in
            // order by county name) and select only those in the election dictionary.

            var counties = CountyCache.GetCountiesByState(stateCode)
                           .Where(countyElectionDictionary.ContainsKey)
                           .ToList();

            // each county report is in its own accordion
            foreach (var countyCode in counties)
            {
                var countyName        = CountyCache.GetCountyName(stateCode, countyCode);
                var countyElectionKey = countyElectionDictionary[countyCode];

                new HtmlDiv {
                    InnerText = countyName
                }.AddTo(content, "accordion-header");
                new ElectionReportResponsive().GenerateReport(ReportUser, countyElectionKey)
                .AddTo(content, "accordion-content");
            }
        }
Esempio n. 10
0
        private string GetLatestViewableElectionKey()
        {
            if (!string.IsNullOrEmpty(GetQueryParm("Office")))
            {
                return
                    (ElectionsOffices.GetLatestViewableElectionKeyStateByOfficeKey(
                         GetQueryParm("Office"), string.Empty));
            }

            return
                (Elections.GetLatestViewableElectionKeyByStateCode(
                     UrlManager.FindStateCode(), String.Empty));
        }
Esempio n. 11
0
        private static void InsertElectionOffice(string electionKey, string officeKey)
        {
            var stateCode          = Elections.GetStateCodeFromKey(electionKey);
            var countyCode         = Elections.GetCountyCodeFromKey(electionKey);
            var localKey           = Elections.GetLocalKeyFromKey(electionKey);
            var federalElectionKey = CreateFederalElectionIfNeeded(electionKey, officeKey);
            var officeClass        = Offices.GetOfficeClass(officeKey);
            var districtCode       = Offices.GetValidDistrictCode(officeKey);
            var stateElectionKey   = Elections.GetStateElectionKeyFromKey(electionKey);

            ElectionsOffices.Insert(electionKey, officeKey, stateElectionKey, federalElectionKey,
                                    stateCode, countyCode, localKey, districtCode, officeClass.ToInt(), false);
        }
Esempio n. 12
0
 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);
 }
    // ReSharper disable MemberCanBePrivate.Global
    // ReSharper disable MemberCanBeProtected.Global
    // ReSharper disable UnusedMember.Global
    // ReSharper disable UnusedMethodReturnValue.Global
    // ReSharper disable UnusedAutoPropertyAccessor.Global
    // ReSharper disable UnassignedField.Global

    #endregion ReSharper disable

    public static void GetReport(Control container, string countyElectionKey, bool openAll = false)
    {
      var stateCode = Elections.GetStateCodeFromKey(countyElectionKey);
      var countyCode = Elections.GetCountyCodeFromKey(countyElectionKey);
      var stateElectionKey = Elections.GetStateElectionKeyFromKey(countyElectionKey);

      // We get a dictionary of locals with elections that match the stateElectionKey
      // Key: localKey; Value: local electionKey
      // Locals without an election will not be in the dictionary
      // We can't forget the Ballot Measures...
      var localKeys = LocalDistricts.GetLocalKeysForCounty(stateCode, countyCode);
      var localElectionDictionary = ElectionsOffices.GetLocalElections(stateElectionKey,
        countyCode, localKeys);
      var localReferendumDictionary = Referendums.GetLocalElections(stateElectionKey, countyCode,
        localKeys);
      // merge them into the first dictionary
      foreach (var kvp in localReferendumDictionary)
        if (!localElectionDictionary.ContainsKey(kvp.Key))
          localElectionDictionary.Add(kvp.Key, kvp.Value);
      if (localElectionDictionary.Count == 0) return;

      // We also get a dictionary of all local names for the county
      var localNamesDictionary = LocalDistricts.GetNamesDictionary(stateCode, countyCode);

      new HtmlDiv {InnerText = "Local District Elections"}.AddTo(container,
        "accordion-header");
      var content = new HtmlDiv().AddTo(container, "local-anchors accordion-content");

      // For reporting we filter only locals with elections and sort by name, 
      var locals =
        localNamesDictionary.Where(kvp => localElectionDictionary.ContainsKey(kvp.Key))
          .OrderBy(kvp => kvp.Value, new AlphanumericComparer())
          .ToList();

      // get a dictionary of other county names for multiple counties
      var otherCountyNames =
        LocalIdsCodes.FormatOtherCountyNamesDictionary(stateCode, countyCode,
          locals.Select(l => l.Key));

      foreach (var kvp in locals)
      {
        var localKey = kvp.Key;
        var localName = kvp.Value;
        var otherCounties = otherCountyNames[localKey];
        if (!IsNullOrWhiteSpace(otherCounties))
          localName += $" (also in {otherCounties})";
        var localElectionKey = localElectionDictionary[localKey];
        CreatePublicElectionAnchor(localElectionKey, localName, openAll)
          .AddTo(content, "local-anchor");
      }
    }
        // ReSharper disable MemberCanBePrivate.Global
        // ReSharper disable MemberCanBeProtected.Global
        // ReSharper disable UnusedMember.Global
        // ReSharper disable UnusedMethodReturnValue.Global
        // ReSharper disable UnusedAutoPropertyAccessor.Global
        // ReSharper disable UnassignedField.Global

        #endregion ReSharper disable

        public static void GetReport(Control container, string stateElectionKey, bool openAll = false)
        {
            var stateCode = Elections.GetStateCodeFromKey(stateElectionKey);

            // We get a dictionary of counties with elections that match the stateElectionKey
            // Key: countyCode; Value: county electionKey
            // Counties without an election will not be in the dictionary
            // Update: we now include local elections too, to account for situations where there is no county
            // election but there are local elections.
            var countyElectionDictionary =
                ElectionsOffices.GetCountyAndLocalElections(stateElectionKey);
            // We can't forget the Ballot Measures...
            var countyReferendumDictionary =
                Referendums.GetCountyAndLocalElections(stateElectionKey);

            // merge them into the first dictionary
            foreach (var kvp in countyReferendumDictionary)
            {
                if (!countyElectionDictionary.ContainsKey(kvp.Key))
                {
                    countyElectionDictionary.Add(kvp.Key, kvp.Value);
                }
            }
            if (countyElectionDictionary.Count == 0)
            {
                return;
            }

            new HtmlDiv {
                InnerText = "County Elections"
            }.AddTo(container, "accordion-header");
            var content = new HtmlDiv().AddTo(container, "local-anchors accordion-content");

            // For reporting we start with all counties for the state (it will be in
            // order by county name) and select only those in the election dictionary.

            var counties = CountyCache.GetCountiesByState(stateCode)
                           .Where(countyElectionDictionary.ContainsKey)
                           .ToList();

            foreach (var countyCode in counties)
            {
                var countyName        = CountyCache.GetCountyName(stateCode, countyCode);
                var countyElectionKey = countyElectionDictionary[countyCode];
                CreatePublicElectionAnchor(countyElectionKey, countyName, openAll)
                .AddTo(content, "local-anchor");
            }
        }
        private Control GenerateReport(string electionKey, string officeKey, bool forBallotPage = false)
        {
            _CandidatesDataManager.GetData(electionKey, officeKey);
            var candidates = _CandidatesDataManager.GetDataSubset(new RunningMateFilter());

            if (candidates.Count > 0)
            {
                var isRunningMateOffice = Offices.IsRunningMateOfficeInElection(electionKey, candidates[0].OfficeKey());

                if (!forBallotPage)
                {
                    var candidatesContainer = new HtmlDiv()
                                              .AddTo(ReportContainer, "candidates-container office-cell");
                    candidatesContainer.Attributes.Add("data-key", officeKey.ToUpperInvariant());
                    var positions = GetElectionPositions(electionKey, candidates[0]);
                    if (positions > 1)
                    {
                        candidatesContainer.Attributes.Add("data-positions",
                                                           positions.ToString(CultureInfo.InvariantCulture));
                    }
                    ReportOffice(candidatesContainer, isRunningMateOffice, candidates, _CandidatesDataManager,
                                 true, true);
                }

                CreateIssueListLink(officeKey);

                var candidateKeys = GetCandidateKeys(isRunningMateOffice, candidates);

                _IssuesDataManager.GetData(electionKey, officeKey);
                if (VotePage.EnableIssueGroups)
                {
                    ReportIssues3(candidateKeys, _IssuesDataManager.GetDataSubset(),
                                  isRunningMateOffice, candidates.Count);
                }
                else
                {
                    // for older elections show all responese
                    var electionDate    = Elections.GetElectionDateFromKey(electionKey);
                    var oldAnswerCutoff = electionDate > DateTime.UtcNow.AddMonths(-6)
            ? ElectionsOffices.GetOldAnswerCutoffDate(electionKey, officeKey)
            : DateTime.MinValue;
                    ReportIssues(candidateKeys, _IssuesDataManager.GetDataSubset(), oldAnswerCutoff,
                                 isRunningMateOffice, candidates.Count);
                }
            }

            return(ReportContainer.AddCssClasses("compare-candidates-report ballot-checks-container"));
        }
        // ReSharper disable MemberCanBePrivate.Global
        // ReSharper disable MemberCanBeProtected.Global
        // ReSharper disable UnusedMember.Global
        // ReSharper disable UnusedMethodReturnValue.Global
        // ReSharper disable UnusedAutoPropertyAccessor.Global
        // ReSharper disable UnassignedField.Global

        #endregion ReSharper disable

        public static Control GetReport(ReportUser reportUser, string countyElectionKey)
        {
            var stateCode        = Elections.GetStateCodeFromKey(countyElectionKey);
            var countyCode       = Elections.GetCountyCodeFromKey(countyElectionKey);
            var stateElectionKey = Elections.GetStateElectionKeyFromKey(countyElectionKey);

            // We get a dictionary of locals with elections that match the stateElectionKey
            // Key: localCode; Value: local electionKey
            // Locals without an election will not be in the dictionary
            var localElectionDictionary =
                ElectionsOffices.GetLocalElections(stateElectionKey, countyCode);

            if (localElectionDictionary.Count == 0)
            {
                return(null);
            }

            // We also get a dictionary of all local names for the county
            var localNamesDictionary = LocalDistricts.GetNamesDictionary(stateCode,
                                                                         countyCode);

            // For reporting we filter only locals with elections, sort by name,
            // then reorder for vertical presentation
            var reorderedLocals = localNamesDictionary.Where(
                kvp => localElectionDictionary.ContainsKey(kvp.Key))
                                  .OrderBy(kvp => kvp.Value)
                                  .ToList()
                                  .ReorderVertically(MaxCellsInRow);

            var          htmlTable           = CreateHtmlTableWithHeading(reportUser, false);
            HtmlTableRow tr                  = null;
            var          cellsDisplayedInRow = MaxCellsInRow; // force new row

            foreach (var kvp in reorderedLocals)
            {
                var localCode        = kvp.Key;
                var localName        = kvp.Value;
                var localElectionKey = localElectionDictionary[localCode];
                cellsDisplayedInRow = CreateOneAnchorCell(reportUser, htmlTable, ref tr,
                                                          localName, localElectionKey, cellsDisplayedInRow);
            }

            return(htmlTable);
        }
            public override void LoadControl()
            {
                var incumbentsToEliminate =
                    ElectionsOffices.GetOfficesWithCandidatesToEliminate(Page.GetElectionKey());

                OfficeCount = incumbentsToEliminate.Count;
                Page.ControlAdjustIncumbentsListValue.Value = string.Empty;
                if (OfficeCount == 0)
                {
                    Page.AdjustIncumbentsMessage.RemoveCssClass("hidden");
                    Page.AdjustIncumbentsControl.AddCssClasses("hidden");
                    Page.AdjustIncumbentsMessage.InnerHtml =
                        "No offices that require incumbents to be removed were found for this election";
                }
                else
                {
                    Page.AdjustIncumbentsMessage.AddCssClasses("hidden");
                    Page.AdjustIncumbentsControl.RemoveCssClass("hidden");
                    PopulateIncumbentsToAdjustList(incumbentsToEliminate,
                                                   Page.PlaceHolderAdjustIncumbentsList);
                }
            }
        // ReSharper disable MemberCanBePrivate.Global
        // ReSharper disable MemberCanBeProtected.Global
        // ReSharper disable UnusedMember.Global
        // ReSharper disable UnusedMethodReturnValue.Global
        // ReSharper disable UnusedAutoPropertyAccessor.Global
        // ReSharper disable UnassignedField.Global

        #endregion ReSharper disable

        public static Control GetReport(ReportUser reportUser, string stateElectionKey)
        {
            var stateCode = Elections.GetStateCodeFromKey(stateElectionKey);

            // We get a dictionary of counties with elections that match the stateElectionKey
            // Key: countyCode; Value: county electionKey
            // Counties without an election will not be in the dictionary
            var countyElectionDictionary =
                ElectionsOffices.GetCountyAndLocalElections(stateElectionKey);

            if (countyElectionDictionary.Count == 0)
            {
                return(null);
            }

            // For reporting we start with all counties for the state (it will be in
            // order by county name). Then we select only those in the election dictionary
            // and reorder for vertical presentation.
            var reorderedCounties = CountyCache.GetCountiesByState(stateCode)
                                    .Where(countyElectionDictionary.ContainsKey)
                                    .ToList()
                                    .ReorderVertically(MaxCellsInRow);

            var          htmlTable           = CreateHtmlTableWithHeading(reportUser, true);
            HtmlTableRow tr                  = null;
            var          cellsDisplayedInRow = MaxCellsInRow; // force new row

            foreach (var countyCode in reorderedCounties)
            {
                var countyName        = CountyCache.GetCountyName(stateCode, countyCode);
                var countyElectionKey = countyElectionDictionary[countyCode];
                cellsDisplayedInRow = CreateOneAnchorCell(reportUser, htmlTable, ref tr,
                                                          countyName, countyElectionKey, cellsDisplayedInRow);
            }

            return(htmlTable);
        }
        private Control GenerateOneAnswerContent(string electionKey, string officeKey,
                                                 string questionKey)
        {
            _CandidatesDataManager.GetData(electionKey, officeKey);
            var candidates = _CandidatesDataManager.GetDataSubset(new RunningMateFilter());
            var container  = new PlaceHolder();

            if (candidates.Count > 0)
            {
                //var isRunningMateOffice = candidates[0].IsRunningMateOffice() &&
                //  !Elections.IsPrimaryElection(electionKey);
                var isRunningMateOffice = Offices.IsRunningMateOfficeInElection(electionKey, candidates[0].OfficeKey());

                var candidateKeys = GetCandidateKeys(isRunningMateOffice, candidates);

                _IssuesDataManager.GetData(electionKey, officeKey, questionKey);
                var oldAnswerCutoff =
                    ElectionsOffices.GetOldAnswerCutoffDate(electionKey, officeKey);
                CreateOneAnswerContent(container, candidateKeys, _IssuesDataManager.GetDataSubset(),
                                       isRunningMateOffice, questionKey, false, oldAnswerCutoff);
            }

            return(container);
        }
        private static void GetLocalElections(Control container, string countyElectionKey, Control multiCountySection = null)
        {
            var stateCode        = Elections.GetStateCodeFromKey(countyElectionKey);
            var countyCode       = Elections.GetCountyCodeFromKey(countyElectionKey);
            var stateElectionKey = Elections.GetStateElectionKeyFromKey(countyElectionKey);

            // We get a dictionary of locals with elections that match the stateElectionKey
            // Key: localKey; Value: local electionKey
            // Locals without an election will not be in the dictionary
            var localElectionDictionary =
                ElectionsOffices.GetLocalElections(stateElectionKey, countyCode);
            // We can't forget the Ballot Measures...
            var localReferendumDictionary =
                Referendums.GetLocalElections(stateElectionKey, countyCode);

            // merge them into the first dictionary
            foreach (var kvp in localReferendumDictionary)
            {
                if (!localElectionDictionary.ContainsKey(kvp.Key))
                {
                    localElectionDictionary.Add(kvp.Key, kvp.Value);
                }
            }
            if (localElectionDictionary.Count == 0)
            {
                return;
            }

            // We also get a dictionary of all local names for the county
            var localNamesDictionary = LocalDistricts.GetNamesDictionary(stateCode, countyCode);

            // For reporting we filter only locals with elections and sort by name,
            var locals = localNamesDictionary
                         .Where(kvp => localElectionDictionary.ContainsKey(kvp.Key))
                         .OrderBy(kvp => kvp.Value, new AlphanumericComparer()).ToList();

            // Get all counties for the locals NB: the counties are pre-sorted by county name
            var countiesForLocals =
                LocalIdsCodes.FindCountiesWithNames(stateCode, locals.Select(kvp => kvp.Key));

            foreach (var kvp in locals)
            {
                var localKey         = kvp.Key;
                var localName        = kvp.Value;
                var localElectionKey = localElectionDictionary[localKey];
                var countiesForLocal = countiesForLocals[localKey];

                var electionReport = new ElectionReportResponsive();
                var localReport    = electionReport.GenerateReport(localElectionKey, true);

                // this will be either a state or county report (for local reports, GenerateReport
                // is called directly)

                //for either county or state, inject the name of the local district into the office
                // if this is an office-title oe a referendum header
                for (var inx = 0; inx < localReport.Controls.Count; inx += 2)
                {
                    var header = localReport.Controls[inx] as HtmlContainerControl;
                    if (header?.HasClass("office-title") == true || header?.HasClass("referendum-header") == true)
                    {
                        header.Controls.AddAt(0,
                                              new HtmlSpan {
                            InnerText = $"{localName}, "
                        }.AddCssClasses("local-name"));
                    }
                }

                //switch (reportLevel)
                //{
                //case ReportLevel.StateLevel:
                //  {
                while (localReport.Controls.Count > 0)
                {
                    if (countiesForLocal.Length > 1 && multiCountySection != null)
                    {
                        // if the county is the first in the counties, inject a multi-county message
                        // and move the pair (header and content) to the multi-counties section.
                        // Otherwise, discard it (it's a duplicate)
                        if (countyCode == countiesForLocal[0].Value)
                        {
                            //var countyMessage = "Parts of this district are in" +
                            //  $" {LocalIdsCodes.FormatCountyNames(countiesForLocal, true)}";
                            //var header = localReport.Controls[0] as HtmlContainerControl;
                            //header?.Controls.Add(
                            //  new HtmlP { InnerText = countyMessage }.AddCssClasses("county-message"));
                            //Debug.Assert(multiCountySection != null, "multiCountySection != null");
                            multiCountySection.Controls.Add(localReport.Controls[0]);
                            multiCountySection.Controls.Add(localReport.Controls[0]);
                        }
                        else
                        {
                            localReport.Controls.RemoveAt(0);
                            localReport.Controls.RemoveAt(0);
                        }
                    }
                    else
                    {
                        // move the pair (header and content) to the outer content
                        container.Controls.Add(localReport.Controls[0]);
                        container.Controls.Add(localReport.Controls[0]);
                    }
                }
                //  }
                //  break;

                //case ReportLevel.CountyLevel:
                //  {
                //var first = true;
                //while (localReport.Controls.Count > 0)
                //{
                //  // for multi-county districts, inject an "other counties" message into the
                //  // first office header if multi county
                //  var countyMessage = Empty;
                //  if (first && countiesForLocal.Length > 1)
                //    countyMessage = "Parts of this local district are also in" +
                //      $" {LocalIdsCodes.FormatCountyNames(countiesForLocal, true, countyCode)}";
                //  var header = localReport.Controls[0] as HtmlContainerControl;
                //  if (!IsNullOrWhiteSpace(countyMessage))
                //    header?.Controls.Add(
                //      new HtmlP { InnerText = countyMessage }.AddCssClasses("county-message"));
                //  first = false;
                //  // move the pair (header and content) to the outer content
                //  container.Controls.Add(localReport.Controls[0]);
                //  container.Controls.Add(localReport.Controls[0]);
                //}
                //}
                //break;
                //}
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Server.ScriptTimeout = 1800;
            var electionKey           = Request.QueryString["election"];
            var csvType               = Request.QueryString["type"];
            var includeCandidates     = csvType != "BM";
            var includeCandidateInfo  = csvType == "NA" || csvType == "WA";
            var includeAnswers        = csvType == "OA" || csvType == "WA";
            var includeBallotMeasures = csvType == "BM";

            if (IsNullOrWhiteSpace(electionKey))
            {
                throw new VoteException("Election key is missing.");
            }
            var electionDescription = Elections.GetElectionDesc(electionKey);

            if (IsNullOrWhiteSpace(electionDescription))
            {
                throw new VoteException("Election key is invalid.");
            }

            // make sure it's a valid filename
            var invalidFileChars = Path.GetInvalidFileNameChars();

            electionDescription = Regex.Replace(electionDescription, ".",
                                                match => new[] { ' ', ',', '"', '\'' }.Contains(match.Value[0]) ||
                                                invalidFileChars.Contains(match.Value[0])
            ? "_"
            : match.Value);
            electionDescription = Regex.Replace(electionDescription, "__+", "_");

            // get the data
            var table = includeBallotMeasures
        ? Referendums.GetElectionCsvReferendumData(electionKey)
        : ElectionsPoliticians.GetElectionCsvCandidateData(electionKey);

            // if we're including answers, get the answers data for each office in the election
            var qas     = new List <QuestionAndAnswer>();
            var columns = new List <dynamic>();

            if (includeAnswers)
            {
                var answers = new List <DataRow>();
                // get a list of all offices in the election
                var allOfficeKeys = table.Rows.OfType <DataRow>().Select(r => r.OfficeKey()).Distinct()
                                    .ToList();
                // collect all the answers
                foreach (var officeKey in allOfficeKeys)
                {
                    var oldAnswerCutoff =
                        ElectionsOffices.GetOldAnswerCutoffDate(electionKey, officeKey);
                    // the GroupBy is to eliminate duplicate answers if a question is in more than one issue
                    answers.AddRange(ElectionsPoliticians.GetCompareCandidateIssuesNew(electionKey, officeKey)
                                     .Rows.OfType <DataRow>()
                                     .GroupBy(r => new
                    {
                        PoliticianKey = r.PoliticianKey(),
                        QuestionKey   = r.QuestionKey(),
                        Sequence      = r.Sequence()
                    })
                                     .Select(g => g.First()));
                    // convert the answers to QuestionAndAnswer format
                    foreach (var p in answers.GroupBy(r => r.PoliticianKey()))
                    {
                        qas.AddRange(ResponsiveIssuesReport.SplitOutVideos(ResponsiveIssuesReport.GetQuestionAndAnswerList(p,
                                                                                                                           Politicians.GetData(p.Key)[0], false)).Where(qa => qa.ResponseDate > oldAnswerCutoff));
                    }
                }
                // analyze qas to determine which topic columns we need to include
                columns.AddRange(qas
                                 .GroupBy(qa =>
                                          new { qa.QuestionKey, IsYouTube = !IsNullOrWhiteSpace(qa.YouTubeUrl) }).Select(
                                     g => new
                {
                    g.Key.QuestionKey,
                    g.Key.IsYouTube,
                    Topic = $"{g.First().Question}{(g.Key.IsYouTube ? " Video" : Empty)}"
                }).OrderBy(q => q.Topic));
            }

            // create the csv
            string csv;

            using (var ms = new MemoryStream())
            {
                var streamWriter = new StreamWriter(ms);
                var csvWriter    = new SimpleCsvWriter();

                // write headers
                csvWriter.AddField("Jurisdiction");
                csvWriter.AddField("State Code");
                if (csvType != "OK")
                {
                    csvWriter.AddField("County");
                    csvWriter.AddField("City or District");
                    csvWriter.AddField("Election Name");
                    csvWriter.AddField("Election Date");
                    csvWriter.AddField("VoteUSA Election Id");
                }

                if (includeCandidates && csvType != "OK")
                {
                    csvWriter.AddField("Office");
                    csvWriter.AddField("Office Class");
                    csvWriter.AddField("District");
                    csvWriter.AddField("VoteUSA Office Id");
                    csvWriter.AddField("Running Mate?");
                    csvWriter.AddField("Candidate");
                    csvWriter.AddField("First Name");
                    csvWriter.AddField("Middle Name");
                    csvWriter.AddField("Nickname");
                    csvWriter.AddField("Last Name");
                    csvWriter.AddField("Suffix");
                    csvWriter.AddField("Party");
                    csvWriter.AddField("VoteUSA Id");
                }

                if (csvType == "OK")
                {
                    csvWriter.AddField("County Code");
                    csvWriter.AddField("County");
                    csvWriter.AddField("Local Key");
                    csvWriter.AddField("Local Name");
                    csvWriter.AddField("Election Key");
                    csvWriter.AddField("Office Key");
                    csvWriter.AddField("Office");
                    csvWriter.AddField("Politician Key");
                    csvWriter.AddField("Politician Password");
                    csvWriter.AddField("Candidate");
                    csvWriter.AddField("Party Code");
                    csvWriter.AddField("Ad Enabled");
                    csvWriter.AddField("YouTube Video Url");
                    csvWriter.AddField("YouTube Channel or Playlist Url");
                    csvWriter.AddField("Compare Candidates Url");
                    csvWriter.AddField("Type");
                    csvWriter.AddField("Date");
                    csvWriter.AddField("Amount");
                    csvWriter.AddField("Email");
                    csvWriter.AddField("Banner Ad Url");
                }

                if (includeCandidateInfo)
                {
                    csvWriter.AddField("Intro Url");
                    csvWriter.AddField("Photo100 Url");
                    csvWriter.AddField("Photo200 Url");
                    csvWriter.AddField("Photo300 Url");
                    csvWriter.AddField("Postal Street Address");
                    csvWriter.AddField("Postal City, State Zip");
                    csvWriter.AddField("Phone");
                    csvWriter.AddField("Email");
                    csvWriter.AddField("Date of Birth");
                }

                if (!includeAnswers && !includeBallotMeasures && csvType != "OK")
                {
                    csvWriter.AddField("General Philosophy");
                    csvWriter.AddField("Personal and Family");
                    csvWriter.AddField("Education");
                    csvWriter.AddField("Profession");
                    csvWriter.AddField("Military");
                    csvWriter.AddField("Civic");
                    csvWriter.AddField("Political Experience");
                    csvWriter.AddField("Religious Affiliation");
                    csvWriter.AddField("Accomplishment and Awards");
                }

                if (includeCandidateInfo)
                {
                    csvWriter.AddField("Website Url");
                    csvWriter.AddField("Facebook Url");
                    csvWriter.AddField("YouTube Url");
                    csvWriter.AddField("Flickr Url");
                    csvWriter.AddField("Twitter Url");
                    csvWriter.AddField("RSS Feed Url");
                    csvWriter.AddField("Wikipedia Url");
                    csvWriter.AddField("BallotPedia Url");
                    csvWriter.AddField("Vimeo Url");
                    csvWriter.AddField("Google+ Url");
                    csvWriter.AddField("LinkedIn Url");
                    csvWriter.AddField("Pinterest Url");
                    csvWriter.AddField("Blogger Url");
                    csvWriter.AddField("Podcast Url");
                    csvWriter.AddField("Instagram Url");
                    csvWriter.AddField("GoFundMe Url");
                    csvWriter.AddField("Crowdpac Url");
                }

                if (includeAnswers)
                {
                    foreach (var column in columns)
                    {
                        csvWriter.AddField(column.Topic);
                    }
                }

                if (includeBallotMeasures)
                {
                    csvWriter.AddField("Ballot Measure Title");
                    csvWriter.AddField("Ballot Measure Description");
                    csvWriter.AddField("Ballot Measure Detail");
                    csvWriter.AddField("Ballot Measure Detail URL");
                    csvWriter.AddField("Ballot Measure Full Text");
                    csvWriter.AddField("Ballot Measure Full Text URL");
                    csvWriter.AddField("Ballot Measure Passed");
                }

                csvWriter.Write(streamWriter);

                var stateCode = Elections.GetStateCodeFromKey(electionKey);

                // do a first pass to get counties for all locals
                var allLocals = new List <string>();
                foreach (var row in table.Rows.Cast <DataRow>())
                {
                    if (!IsNullOrWhiteSpace(row.LocalKey()))
                    {
                        allLocals.Add(row.LocalKey());
                    }
                }

                var countiesForLocals =
                    LocalIdsCodes.FindCountiesWithNames(stateCode, allLocals.Distinct());

                var rows = table.Rows.Cast <DataRow>();

                if (csvType == "OK")
                {
                    rows = rows.OrderBy(r => r.OfficeLevel())
                           //.ThenBy(r => r.DistrictCode())
                           //.ThenBy(r => r.OfficeOrderWithinLevel())
                           //.ThenBy(r => r.OfficeLine1())
                           //.ThenBy(r => r.OfficeLine2())
                           .ThenBy(r => Offices.FormatOfficeName(r),
                                   MixedNumericComparer.Instance)
                           .ThenBy(r => r.OrderOnBallot())
                           .ThenBy(r => r.PoliticianKey(), StringComparer.OrdinalIgnoreCase)
                           .ThenBy(r => r.IsRunningMate());
                }

                foreach (var row in rows)
                {
                    string jurisdiction;
                    var    politicianKey = Empty;
                    if (includeBallotMeasures)
                    {
                        if (!IsNullOrWhiteSpace(row.LocalKey()))
                        {
                            jurisdiction = "Local";
                        }
                        else if (!IsNullOrWhiteSpace(row.CountyCode()))
                        {
                            jurisdiction = "County";
                        }
                        else
                        {
                            jurisdiction = "State";
                        }
                    }
                    else
                    {
                        politicianKey = row.IsRunningMate()
              ? row.RunningMateKey()
              : row.PoliticianKey();
                        switch (Offices.GetElectoralClass(row.OfficeClass()))
                        {
                        case ElectoralClass.USPresident:
                        case ElectoralClass.USSenate:
                        case ElectoralClass.USHouse:
                            jurisdiction = "Federal";
                            break;

                        case ElectoralClass.USGovernors:
                        case ElectoralClass.State:
                            jurisdiction = "State";
                            break;

                        case ElectoralClass.County:
                            jurisdiction = "County";
                            break;

                        case ElectoralClass.Local:
                            jurisdiction = "Local";
                            break;

                        default:
                            jurisdiction = Empty;
                            break;
                        }
                    }

                    var photo100Url = Empty;
                    if (includeCandidateInfo)
                    {
                        var qsc100 = new QueryStringCollection
                        {
                            {
                                "id", politicianKey
                            },
                            {
                                "Col", "Headshot100"
                            }
                        };
                        var photo100Uri = UrlManager.GetSiteUri("image.aspx", qsc100);
                        photo100Url = new UriBuilder(photo100Uri)
                        {
                            Scheme = Uri.UriSchemeHttps,
                            Host   = UrlManager.GetCanonicalLiveHostName(photo100Uri.Host),
                            Port   = 443
                        }.Uri.ToString();
                    }

                    var photo200Url = Empty;
                    if (includeCandidateInfo)
                    {
                        var qsc200 = new QueryStringCollection
                        {
                            { "id", politicianKey }, { "Col", "Profile200" }
                        };
                        var photo200Uri = UrlManager.GetSiteUri("image.aspx", qsc200);
                        photo200Url = new UriBuilder(photo200Uri)
                        {
                            Scheme = Uri.UriSchemeHttps,
                            Host   = UrlManager.GetCanonicalLiveHostName(photo200Uri.Host),
                            Port   = 443
                        }.Uri.ToString();
                    }

                    var photo300Url = Empty;
                    if (includeCandidateInfo)
                    {
                        var qsc300 = new QueryStringCollection
                        {
                            { "id", politicianKey }, { "Col", "Profile300" }
                        };
                        var photo300Uri = UrlManager.GetSiteUri("image.aspx", qsc300);
                        photo300Url = new UriBuilder(photo300Uri)
                        {
                            Scheme = Uri.UriSchemeHttps,
                            Host   = UrlManager.GetCanonicalLiveHostName(photo300Uri.Host),
                            Port   = 443
                        }.Uri.ToString();
                    }

                    var introUrl = Empty;
                    if (includeCandidateInfo)
                    {
                        var introUri = UrlManager.GetIntroPageUri(politicianKey);
                        introUrl = new UriBuilder(introUri)
                        {
                            Scheme = Uri.UriSchemeHttps,
                            Host   = UrlManager.GetCanonicalLiveHostName(introUri.Host),
                            Port   = 443
                        }.Uri.ToString();
                    }

                    var district = Empty;
                    if (includeCandidates)
                    {
                        if (int.TryParse(row.DistrictCode(), out var districtNumber))
                        {
                            district = districtNumber.ToString(CultureInfo.InvariantCulture);
                        }
                    }

                    // convert to simple name if national
                    var partyName = Empty;
                    if (includeCandidates)
                    {
                        partyName = Parties.GetNationalPartyDescription(row.PartyCode(),
                                                                        row.PartyName());
                    }

                    var county = IsNullOrWhiteSpace(row.County()) ? Empty : row.County();
                    var local  = Empty;
                    if (!IsNullOrWhiteSpace(row.LocalKey()))
                    {
                        local  = row.LocalDistrict();
                        county = Join(", ", countiesForLocals[row.LocalKey()].Select(c => c.Text));
                    }

                    csvWriter.AddField(jurisdiction);
                    csvWriter.AddField(stateCode);
                    if (csvType != "OK")
                    {
                        csvWriter.AddField(county);
                        csvWriter.AddField(local);
                        csvWriter.AddField(row.ElectionDescription());
                        csvWriter.AddField(row.ElectionDate().ToString("d"));
                        csvWriter.AddField(row.ElectionKey());
                    }

                    if (includeCandidates && csvType != "OK")
                    {
                        csvWriter.AddField(Offices.FormatOfficeName(row));
                        csvWriter.AddField(Offices.GetOfficeClassShortDescriptionExtended(row));
                        csvWriter.AddField(district);
                        csvWriter.AddField(row.OfficeKey());
                        csvWriter.AddField(row.IsRunningMate() ? row.PoliticianKey() : Empty);
                        csvWriter.AddField(Politicians.FormatName(row));
                        csvWriter.AddField(row.FirstName());
                        csvWriter.AddField(row.MiddleName());
                        csvWriter.AddField(row.Nickname());
                        csvWriter.AddField(row.LastName());
                        csvWriter.AddField(row.Suffix());
                        csvWriter.AddField(partyName);
                        csvWriter.AddField(politicianKey);
                    }

                    if (csvType == "OK")
                    {
                        var youTubeVideoUrl     = Empty;
                        var youTubeAdWebAddress = row.AdUrl();
                        if (!IsNullOrWhiteSpace(youTubeAdWebAddress))
                        {
                            youTubeVideoUrl = youTubeAdWebAddress.IsValidYouTubeVideoUrl()
                ? youTubeAdWebAddress
                : "channel or playlist";
                        }

                        var adEnabled = Empty;
                        if (!IsNullOrWhiteSpace(row.AdType()))
                        {
                            adEnabled = row.AdEnabled() ? "E" : "D";
                        }

                        var compareUrl =
                            UrlManager.GetCompareCandidatesPageUri(row.ElectionKey(), row.OfficeKey()) +
                            $"&ad={politicianKey}";

                        csvWriter.AddField(row.CountyCode());
                        csvWriter.AddField(row.County().SafeString());
                        csvWriter.AddField(row.LocalKey());
                        csvWriter.AddField(row.LocalDistrict().SafeString());
                        csvWriter.AddField(row.ElectionKey());
                        csvWriter.AddField(row.OfficeKey());
                        csvWriter.AddField(Offices.FormatOfficeName(row.OfficeLine1(),
                                                                    row.OfficeLine2(), row.OfficeKey()));
                        csvWriter.AddField(politicianKey);
                        csvWriter.AddField(row.Password());
                        csvWriter.AddField(Politicians.FormatName(row));
                        csvWriter.AddField(row.PartyCode().SafeString());
                        csvWriter.AddField(adEnabled);
                        csvWriter.AddField(youTubeVideoUrl);
                        csvWriter.AddField(row.YouTubeWebAddress());
                        csvWriter.AddField($"=HYPERLINK(\"{compareUrl}\",\"{compareUrl}\")");
                        csvWriter.AddField(Empty);
                        csvWriter.AddField(Empty);
                        csvWriter.AddField(Empty);
                        csvWriter.AddField(Empty);
                        csvWriter.AddField(Empty);
                    }

                    if (includeCandidateInfo)
                    {
                        csvWriter.AddField(introUrl);
                        csvWriter.AddField(photo100Url);
                        csvWriter.AddField(photo200Url);
                        csvWriter.AddField(photo300Url);
                        csvWriter.AddField(row.PublicAddress());
                        csvWriter.AddField(row.PublicCityStateZip());
                        csvWriter.AddField(row.PublicPhone());
                        csvWriter.AddField(row.PublicEmail());
                        csvWriter.AddField(row.DateOfBirth().ToString("d"));
                    }

                    if (!includeAnswers && !includeBallotMeasures && csvType != "OK")
                    {
                        csvWriter.AddField(row.GeneralStatement().SafeString());
                        csvWriter.AddField(row.Personal().SafeString());
                        csvWriter.AddField(row.Education().SafeString());
                        csvWriter.AddField(row.Profession().SafeString());
                        csvWriter.AddField(row.Military().SafeString());
                        csvWriter.AddField(row.Civic().SafeString());
                        csvWriter.AddField(row.Political().SafeString());
                        csvWriter.AddField(row.Religion().SafeString());
                        csvWriter.AddField(row.Accomplishments().SafeString());
                    }

                    if (includeCandidateInfo)
                    {
                        csvWriter.AddField(row.PublicWebAddress());
                        csvWriter.AddField(row.FacebookWebAddress());
                        csvWriter.AddField(row.YouTubeWebAddress());
                        csvWriter.AddField(row.FlickrWebAddress());
                        csvWriter.AddField(row.TwitterWebAddress());
                        csvWriter.AddField(row.RssFeedWebAddress());
                        csvWriter.AddField(row.WikipediaWebAddress());
                        csvWriter.AddField(row.BallotPediaWebAddress());
                        csvWriter.AddField(row.VimeoWebAddress());
                        csvWriter.AddField(row.GooglePlusWebAddress());
                        csvWriter.AddField(row.LinkedInWebAddress());
                        csvWriter.AddField(row.PinterestWebAddress());
                        csvWriter.AddField(row.BloggerWebAddress());
                        csvWriter.AddField(row.PodcastWebAddress());
                        csvWriter.AddField(row.WebstagramWebAddress());
                        csvWriter.AddField(row.GoFundMeWebAddress());
                        csvWriter.AddField(row.CrowdpacWebAddress());
                    }

                    if (includeAnswers)
                    {
                        var data = qas.Where(qa => qa.PoliticianKey == politicianKey)
                                   .OrderByDescending(qa => qa.ResponseDate)
                                   .ToList();
                        foreach (var column in columns)
                        {
                            var response = data.FirstOrDefault(d => d.QuestionKey == column.QuestionKey &&
                                                               d.HasVideo == column.IsYouTube);
                            var field = Empty;
                            if (response != null)
                            {
                                if (response.HasVideo)
                                {
                                    field = response.YouTubeUrl;
                                }
                                else
                                {
                                    field = $"{response.Answer}" +
                                            $"\n\n{(IsNullOrWhiteSpace(response.AnswerSource) ? Empty : $" Source: {response.AnswerSource}")}" +
                                            $" ({response.AnswerDate:M/d/yyyy})";
                                }
                            }
                            csvWriter.AddField(field);
                        }
                    }

                    if (includeBallotMeasures)
                    {
                        csvWriter.AddField(row.ReferendumTitle());
                        csvWriter.AddField(row.ReferendumDescription());
                        csvWriter.AddField(row.ReferendumDetail());
                        csvWriter.AddField(row.ReferendumDetailUrl());
                        csvWriter.AddField(row.ReferendumFullText());
                        csvWriter.AddField(row.ReferendumFullTextUrl());
                        csvWriter.AddField(row.IsPassed() ? "Y" : Empty);
                    }

                    csvWriter.Write(streamWriter);
                }
                streamWriter.Flush();
                ms.Position = 0;
                csv         = new StreamReader(ms).ReadToEnd();
            }

            // download
            var filename = electionDescription;

            switch (csvType)
            {
            case "NA":
                filename += " without topics";
                break;

            case "OA":
                filename += " - topics only";
                break;

            case "WA":
                filename += " - all data including topics";
                break;

            case "OK":
                filename += " - names and keys only";
                break;

            case "BM":
                filename += " - Ballot Measures";
                break;
            }
            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition",
                               $"attachment;filename=\"{filename}.csv\"");
            Response.Write("\xfeff"); // BOM
            Response.Write(csv);
            Response.End();
        }
Esempio n. 22
0
        protected void ButtonDeleteDistricts_OnClick(object sender, EventArgs e)
        {
            switch (DeleteDistrictsReloading.Value)
            {
            case "reloading":
            {
                DeleteDistrictOverride.AddCssClasses("hidden");
                ControlDeleteDistrictOverride.Checked = false;
                _DeleteDistrictsTabInfo.ClearValidationErrors();
                DeleteDistrictsReloading.Value = Empty;
                PopulateLocalDistrictDropdown();
                _DeleteDistrictsTabInfo.LoadControls();
                FeedbackDeleteDistricts.AddInfo("Delete Districts information loaded.");
            }
            break;

            case "":
            {
                // normal update
                DeleteDistrictOverride.AddCssClasses("hidden");
                _DeleteDistrictsTabInfo.ClearValidationErrors();
                var localKey      = ControlDeleteDistrictsLocalKey.GetValue();
                var localDistrict = LocalDistricts.GetLocalDistrictByStateCodeLocalKey(StateCode,
                                                                                       localKey);

                var referenceList = new List <string>();
                if (!ControlDeleteDistrictOverride.Checked)
                {
                    // check for references in other counties
                    var otherCounties = new List <string>();
                    foreach (var oc in
                             LocalIdsCodes.GetOtherCountyReferences(StateCode, CountyCode, localKey)
                             .Rows.OfType <DataRow>())
                    {
                        otherCounties.Add(oc.County());
                    }

                    // check for meaningful usages
                    FormatReferences(referenceList, "Elections",
                                     Elections.CountByStateCodeLocalKey(StateCode, localKey));
                    FormatReferences(referenceList, "ElectionsOffices",
                                     ElectionsOffices.CountByStateCodeLocalKey(StateCode, localKey));
                    FormatReferences(referenceList, "ElectionsPoliticians",
                                     ElectionsPoliticians.CountByStateCodeLocalKey(StateCode, localKey));
                    FormatReferences(referenceList, "QuestionsJurisdictions",
                                     QuestionsJurisdictions.CountByIssueLevelStateCodeCountyOrLocal(
                                         Issues.IssueLevelLocal, StateCode, localKey));
                    FormatReferences(referenceList, "Offices",
                                     Offices.CountByStateCodeLocalKey(StateCode, localKey));
                    FormatReferences(referenceList, "OfficesOfficials",
                                     OfficesOfficials.CountByStateCodeLocalKey(StateCode, localKey));
                    FormatReferences(referenceList, "Referendums",
                                     Referendums.CountByStateCodeLocalKey(StateCode, localKey));

                    if (referenceList.Count > 0 || otherCounties.Count > 0)
                    {
                        DeleteDistrictOverride.RemoveCssClass("hidden");
                        if (otherCounties.Count > 0)
                        {
                            FeedbackDeleteDistricts.PostValidationError(ControlDeleteDistrictsLocalKey,
                                                                        "The district is referenced in the following other counties. If you delete this" +
                                                                        " district it will be removed from the other counties also. Check the box to" +
                                                                        " override.");
                            foreach (var oc in otherCounties)
                            {
                                FeedbackDeleteDistricts.AddError(oc);
                            }
                        }
                        if (referenceList.Count > 0)
                        {
                            FeedbackDeleteDistricts.PostValidationError(ControlDeleteDistrictsLocalKey,
                                                                        "Cannot delete because the LocalKey is referenced in the following tables. Check the box to override.");
                            foreach (var @ref in referenceList)
                            {
                                FeedbackDeleteDistricts.AddError(@ref);
                            }
                        }
                        return;
                    }
                }

                // delete
                ControlDeleteDistrictOverride.Checked = false;
                DeleteAllDistictReferences(StateCode, localKey);
                LocalDistricts.DeleteByStateCodeLocalKey(StateCode, localKey);

                // delete TigerPlacesCounties rows if type Vote -- these are not intrinsically tied
                // to county(s)
                var localIdsCodes = LocalIdsCodes.GetDataByStateCodeLocalKey(StateCode, localKey);
                Debug.Assert(localIdsCodes.Count == 1);
                if (localIdsCodes[0].LocalType == LocalIdsCodes.LocalTypeVote)
                {
                    TigerPlacesCounties.DeleteByStateCodeTigerTypeTigerCode(StateCode,
                                                                            LocalIdsCodes.LocalTypeVote, localIdsCodes[0].LocalId);
                }
                LocalIdsCodes.DeleteByStateCodeLocalKey(StateCode, localKey);
                _DeleteDistrictsTabInfo.ClearValidationErrors();
                PopulateLocalDistrictDropdown();
                _DeleteDistrictsTabInfo.LoadControls();
                NavigateJurisdictionUpdatePanel.Update();
                NavigateJurisdiction.Initialize();

                FeedbackDeleteDistricts.AddInfo(
                    $"Local District {localDistrict} ({localKey}) deleted.");
            }
            break;

            default:
                throw new VoteException(
                          $"Unknown reloading option: '{DeleteDistrictsReloading.Value}'");
            }
        }
        private static void GetCountyElections(Control container, string stateElectionKey)
        {
            var stateCode = Elections.GetStateCodeFromKey(stateElectionKey);

            // We get a dictionary of counties with elections that match the stateElectionKey
            // Key: countyCode; Value: countyElectionKey
            // Counties without an election will not be in the dictionary
            // We include local elections too, to account for situations where there is no county
            // election but there are local elections.
            var countyElectionDictionary =
                ElectionsOffices.GetCountyAndLocalElections(stateElectionKey);
            // We can't forget the Ballot Measures...
            var countyReferendumDictionary =
                Referendums.GetCountyAndLocalElections(stateElectionKey);

            // merge them into the first dictionary
            foreach (var kvp in countyReferendumDictionary)
            {
                if (!countyElectionDictionary.ContainsKey(kvp.Key))
                {
                    countyElectionDictionary.Add(kvp.Key, kvp.Value);
                }
            }
            if (countyElectionDictionary.Count == 0)
            {
                return;
            }

            // For reporting we start with all counties for the state (it will be in
            // order by county name) and select only those in the election dictionary.
            var counties = CountyCache.GetCountiesByState(stateCode)
                           .Where(countyElectionDictionary.ContainsKey).ToList();

            var multiCountySection = new PlaceHolder();

            multiCountySection.AddTo(container);

            // each county report is in its own accordion
            foreach (var countyCode in counties)
            {
                var countyName        = CountyCache.GetCountyName(stateCode, countyCode);
                var countyElectionKey = countyElectionDictionary[countyCode];

                var electionReport = new ElectionReportResponsive();
                var countyReport   = electionReport.GenerateReport(countyElectionKey, true, multiCountySection);

                for (var inx = 0; inx < countyReport.Controls.Count; inx += 2)
                {
                    // this will always be a state report (for county reports, GenerateReport
                    // is called directly. Inject the county name into the office title header for context
                    var header = countyReport.Controls[inx] as HtmlContainerControl;
                    header?.Controls.Add(
                        new HtmlP {
                        InnerText = countyName
                    }.AddCssClasses("county-message"));
                }

                // move them to the content
                while (countyReport.Controls.Count > 0)
                {
                    container.Controls.Add(countyReport.Controls[0]);
                }
            }
        }
Esempio n. 24
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);
            }
        }
Esempio n. 25
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);
            }
        }
Esempio n. 26
0
        private void CopyCandidates()
        {
            var candidatesCopied = 0;
            var officesCopied    = 0;
            var officesSkipped   = 0;

            try
            {
                //if (ElectionsPoliticians.CountByElectionKey(GetElectionKey()) > 0)
                //  throw new VoteException(
                //    "This function can only be used if no candidates have been added for the election.");
                var offices = ElectionsOffices.GetDataByElectionKey(GetElectionKey());
                if (offices.Count == 0)
                {
                    throw new VoteException(
                              "There are no offices for this election to copy. Use the Add/Remove Offices tab to add the offices you want to copy.");
                }
                var electionKeyToCopy = MasterOnlyElectionKeyToCopy.Value;
                foreach (var office in offices)
                {
                    if (
                        ElectionsPoliticians.CountByElectionKeyOfficeKey(GetElectionKey(),
                                                                         office.OfficeKey) > 0)
                    {
                        officesSkipped++;
                        continue;
                    }
                    var oldPoliticians =
                        ElectionsPoliticians.GetDataByElectionKeyOfficeKey(electionKeyToCopy,
                                                                           office.OfficeKey);
                    if (oldPoliticians.Count == 0)
                    {
                        continue;
                    }
                    officesCopied++;
                    candidatesCopied += oldPoliticians.Count;
                    var newPoliticians = new ElectionsPoliticiansTable();
                    foreach (var oldPolitician in oldPoliticians)
                    {
                        newPoliticians.AddRow(office.ElectionKey, office.OfficeKey,
                                              oldPolitician.PoliticianKey, oldPolitician.RunningMateKey,
                                              office.ElectionKeyState, office.ElectionKeyFederal,
                                              office.ElectionKeyCounty, office.ElectionKeyLocal, office.StateCode,
                                              office.CountyCode, office.LocalCode, office.DistrictCode,
                                              oldPolitician.OrderOnBallot, false,
                                              OfficesOfficials.OfficeKeyPoliticianKeyExists(office.OfficeKey,
                                                                                            oldPolitician.PoliticianKey), false);
                    }
                    ElectionsPoliticians.UpdateTable(newPoliticians);
                }
                FeedbackMasterOnly.AddInfo(
                    officesCopied > 0
            ? $"{candidatesCopied} candidates were copied for {officesCopied} offices."
            : "There were no candidates that could be copied.");
                if (officesSkipped > 0)
                {
                    FeedbackMasterOnly.AddInfo(
                        $"{officesSkipped} offices were skipped because there were already candidates entered.");
                }
            }
            catch (Exception ex)
            {
                FeedbackMasterOnly.PostValidationError(ControlMasterOnlyElectionToCopy,
                                                       "The candidates could not be copied: " + ex.Message);
            }
        }
Esempio n. 27
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);
            }
        }
Esempio n. 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPoliticianUser)
            {
                Page.Title = H1.InnerHtml = "Database Statistics";
                CandidatesCount.InnerText        = Politicians.CountTable().ToString("N0");
                CandidatePicturesCount.InnerText =
                    PoliticiansImagesData.CountTable().ToString("N0");
                OfficesCount.InnerText = Offices.CountAllActualOffices().ToString("N0");

                var officeCandidates = ElectionsPoliticians.GetOfficeCandidatesByYear();
                OfficeCandidatesCount.InnerText = officeCandidates.Sum(y => y.Value).ToString("N0");
                var officeCandidatesRowIndex =
                    OfficeCandidatesRow.Parent.Controls.IndexOf(OfficeCandidatesRow);
                foreach (var kvp in officeCandidates.OrderBy(i => i.Key))
                {
                    var newRow = new HtmlTableRow();
                    newRow.AddCssClasses("office-candidates-year");
                    newRow.AddCssClasses(OfficeCandidatesRow.Attributes["class"].SafeString());
                    OfficeCandidatesRow.Parent.Controls.AddAt(++officeCandidatesRowIndex, newRow);
                    new Literal
                    {
                        Text = kvp.Key
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "year"));
                    new Literal
                    {
                        Text = kvp.Value.ToString("N0")
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "value"));
                }

                var officeContests = ElectionsOffices.GetOfficeContestsByYear();
                OfficeContestCount.InnerText = officeContests.Sum(y => y.Value).ToString("N0");
                var officeContestsRowIndex =
                    OfficeContestsRow.Parent.Controls.IndexOf(OfficeContestsRow);
                foreach (var kvp in officeContests.OrderBy(i => i.Key))
                {
                    var newRow = new HtmlTableRow();
                    newRow.AddCssClasses("office-contests-year");
                    newRow.AddCssClasses(OfficeContestsRow.Attributes["class"].SafeString());
                    OfficeContestsRow.Parent.Controls.AddAt(++officeContestsRowIndex, newRow);
                    new Literal
                    {
                        Text = kvp.Key
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "year"));
                    new Literal
                    {
                        Text = kvp.Value.ToString("N0")
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "value"));
                }

                var electionsCount = Elections.CountStateElectionsByYear();
                ElectionsCount.InnerText = electionsCount.Sum(y => y.Value).ToString("N0");
                var electionsRowIndex =
                    ElectionsRow.Parent.Controls.IndexOf(ElectionsRow);
                foreach (var kvp in electionsCount.OrderBy(i => i.Key))
                {
                    var newRow = new HtmlTableRow();
                    newRow.AddCssClasses("elections-year");
                    newRow.AddCssClasses(ElectionsRow.Attributes["class"].SafeString());
                    ElectionsRow.Parent.Controls.AddAt(++electionsRowIndex, newRow);
                    new Literal
                    {
                        Text = kvp.Key
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "year"));
                    new Literal
                    {
                        Text = kvp.Value.ToString("N0")
                    }.AddTo(new HtmlTableCell().AddTo(newRow, "value"));
                }

                SocialMediaLinksCount.InnerText =
                    Politicians.CountAllSocialMediaLinks().ToString("N0");
                BioInfoCount.InnerText        = Answers.CountBioAnswersNew().ToString("N0");
                PersonalCount.InnerText       = Answers.CountPersonalAnswersNew().ToString("N0");
                IssueResponsesCount.InnerText = Answers.CountActiveIssueAnswersNew().ToString("N0");
            }
        }