Пример #1
0
        protected Control FormatCandidate(DataRow candidate, bool showIncumbent,
                                          bool showParty)
        {
            var placeHolder = new PlaceHolder();

            new LiteralControl(Politicians.FormatName(candidate, true)).AddTo(placeHolder);
            if (showIncumbent && candidate.IsIncumbent())
            {
                new LiteralControl(" *").AddTo(
                    new HtmlSpan().AddTo(placeHolder, "incumbent"));
            }

            if (!showParty || string.IsNullOrWhiteSpace(candidate.PartyCode()))
            {
                return(placeHolder);
            }

            var span = new HtmlSpan().AddTo(placeHolder, "party");

            new Literal {
                Text = " - "
            }.AddTo(span);
            FormatPartyAnchor(candidate)
            .AddTo(span);

            return(placeHolder);
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _PoliticianInfo = Politicians.GetPoliticianIntroReportData(_PoliticianKey);

            if (_PoliticianInfo == null)
            {
                InnerContent.Controls.Clear();
                var p = new HtmlP().AddTo(InnerContent, "not-found-error");
                new LiteralControl($"Could not find Id {_PoliticianKey}").AddTo(p);
                return;
            }

            _PoliticianName  = Politicians.FormatName(_PoliticianInfo);
            _OfficeAndStatus = Politicians.FormatOfficeAndStatus(_PoliticianInfo);

            Title           = Format(TitleTag, GetCandidateInfo(" | "), PublicMasterPage.SiteName);
            MetaDescription = Format(MetaDescriptionTag, GetCandidateInfo(", "), PublicMasterPage.SiteName);
            //MetaKeywords = _PoliticianName;

            PageHeading.MainHeadingText = Format(PageHeading.MainHeadingText,
                                                 _PoliticianName);

            PoliticianInfoResponsive.GetReport(_PoliticianInfo).AddTo(InfoPlaceHolder);
            IntroIssuesReport.GetReport(_PoliticianInfo).AddTo(ReportPlaceHolder);
        }
Пример #3
0
        protected static HtmlAnchor CreatePoliticianIntroAnchor(DataRow politician,
                                                                string anchorText = "", string title = "", string target = "_self")
        {
            var politicianName = Politicians.FormatName(politician, true);

            if (IsNullOrEmpty(anchorText))
            {
                anchorText = politicianName;
            }

            if (IsNullOrEmpty(title))
            {
                title = politicianName +
                        "'s biographical information and positions and views on the issues";
            }

            return(new HtmlAnchor
            {
                HRef = UrlManager.GetIntroPageUri(politician.PoliticianKey())
                       .ToString(),
                Title = title,
                Target = target,
                InnerHtml = anchorText
            });
        }
Пример #4
0
        private static void PopulateIncumbentsToReinstateList(
            IEnumerable <IGrouping <string, DataRow> > incumbentsToReinstate,
            Control parent)
        {
            parent.Controls.Clear();

            var container = new HtmlDiv().AddTo(parent, "offices");

            foreach (var incumbents in incumbentsToReinstate)
            {
                var office = incumbents.First();
                var div    = new HtmlDiv().AddTo(container, "office");
                div.Attributes.Add("rel", office.OfficeKey());
                new HtmlP {
                    InnerHtml = Offices.FormatOfficeName(office)
                }
                .AddTo(div, "office-name");
                foreach (var incumbent in incumbents)
                {
                    var p = new HtmlP().AddTo(div);
                    new HtmlInputCheckBox
                    {
                        Checked = false,
                        Value   = incumbent.PoliticianKey()
                    }.AddTo(p, "incumbent");
                    new LiteralControl(Politicians.FormatName(incumbent)).AddTo(p);
                }
            }
        }
Пример #5
0
 private void FillCandidateRecord(IDictionary record, DataRow row,
                                  IList <DataRow> issues)
 {
     AddField(record, "politicianKey", row.PoliticianKey());
     AddField(record, "name", Politicians.FormatName(row));
     AddField(record, "address", row.PublicAddress());
     AddField(record, "cityStateZip", row.PublicCityStateZip());
     AddField(record, "phone", row.PublicPhone());
     AddField(record, "dateOfBirth", FormatDate(row.DateOfBirth()));
     AddField(record, "partyName", row.PartyName());
     AddField(record, "email", row.PublicEmail());
     AddField(record, "webAddress", row.PublicWebAddress());
     if (_Bio)
     {
         AddSpecialIssue(record, row, issues, "ALLBio", "bio");
     }
     if (_Reasons)
     {
         AddSpecialIssue(record, row, issues, "ALLPersonal", "reasons");
     }
     if (_Issues)
     {
         AddIssues(record, row, issues);
     }
     if (!row.IsRunningMate())
     {
         AddField(record, "isIncumbent", row.IsIncumbent());
         AddField(record, "isWinner", row.IsWinner());
     }
 }
        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);
        }
Пример #7
0
        private Control GenerateVideoContent(DataRow politician)
        {
            var container = new PlaceHolder();

            _DataManager.GetVideoData(politician.PoliticianKey(), politician.LiveOfficeKey());
            ReportCandidateVideos(container, politician, _DataManager.GetDataSubset(),
                                  Politicians.FormatName(politician), false);
            return(container);
        }
Пример #8
0
        protected void ReportPolitician(DataRow politician, bool isWinner,
                                        bool isIncumbent)
        {
            var politicianKey  = politician.PoliticianKey();
            var politicianName = Politicians.FormatName(politician);

            Control anchorHeadshot = null;

            switch (ReportUser)
            {
            case ReportUser.Public:
            {
                anchorHeadshot =
                    CreatePoliticianImageAnchor(UrlManager.GetIntroPageUri(politicianKey)
                                                .ToString(), politicianKey, ImageSize100,
                                                politicianName +
                                                " biographical information and positions and views on the issues");
                break;
            }

            case ReportUser.Admin:
            {
                anchorHeadshot = new HtmlImage
                {
                    Src = VotePage.GetPoliticianImageUrl(politicianKey, ImageSize75)
                };
                break;
            }

            case ReportUser.Master:
            {
                anchorHeadshot =
                    CreatePoliticianImageAnchor(
                        SecurePoliticianPage.GetUpdateIssuesPageUrl(politicianKey),
                        politicianKey, ImageSize75,
                        "Edit Issue Topic Responses", "politician");
                break;
            }
            }

            var td = new HtmlTableCell().AddTo(CurrentPoliticianRow, "tdReportImage");

            Debug.Assert(anchorHeadshot != null, "anchorHeadshot != null");
            anchorHeadshot.AddTo(td);

            var politicianCell = new HtmlTableCell().AddTo(CurrentPoliticianRow,
                                                           "tdReportDetail");

            var nameContainer = new HtmlDiv().AddTo(politicianCell,
                                                    "detail name");

            if (isIncumbent)
            {
                new Literal {
                    Text = "* "
                }
            }
Пример #9
0
        private static string FormatPoliticianName(PoliticiansAdminReportViewRow row,
                                                   bool breakAfterPosition = false, bool includeAddOn = false)
        {
            const int maxNameLineLength = 30;

            return(Politicians.FormatName(row.FirstName, row.MiddleName, row.Nickname,
                                          row.LastName, row.Suffix, includeAddOn ? row.AddOn : null, row.StateCode,
                                          breakAfterPosition ? maxNameLineLength : 0));
        }
        private Control GenerateOneCandidateVideoContent(string electionKey, string officeKey,
                                                         string politicianKey)
        {
            var container = new PlaceHolder();

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

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

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

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

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

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

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

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

            return(container);
        }
Пример #11
0
        protected static HtmlAnchor CreateAdminPoliticianAnchor(DataRow politician,
                                                                string anchorText, string target = "politician")
        {
            var a = new HtmlAnchor
            {
                HRef      = SecureAdminPage.GetPoliticianPageUrl(politician.PoliticianKey()),
                Target    = target,
                Title     = Politicians.FormatName(politician) + " administration data edit form",
                InnerHtml = anchorText
            };

            return(a);
        }
Пример #12
0
 public List <VoteUsaCandidate> GetVoteUsaCandidates(string electionKey,
                                                     string officeKey) =>
 ElectionsPoliticians
 .GetPoliticiansForOfficeInElection(electionKey, officeKey)
 .Rows.Cast <DataRow>()
 .Select(
     row =>
     new VoteUsaCandidate
 {
     Value      = row.PoliticianKey(),
     Text       = Politicians.FormatName(row),
     FirstThree = row.LastName().Substring(0,
                                           Math.Min(3, row.LastName().Length)).ToLowerInvariant()
 })
 .ToList();
Пример #13
0
 public static List <SimpleListItem> GetPreviewCandidateItems(
     string electionKey, string officeKey)
 {
     return
         (new List <SimpleListItem>
     {
         new SimpleListItem(string.Empty, "<none>")
     }.Union(ElectionsPoliticians
             .GetPoliticiansForOfficeInElection(electionKey, officeKey)
             .Rows.Cast <DataRow>()
             .Select(
                 row =>
                 new SimpleListItem(row.PoliticianKey(),
                                    Politicians.FormatName(row))))
          .ToList());
 }
Пример #14
0
        private static void PopulateIncumbentsToAdjustList(
            IEnumerable <IGrouping <string, DataRow> > incumbentsToEliminate,
            Control parent)
        {
            parent.Controls.Clear();

            new HtmlH6
            {
                InnerHtml =
                    "Incumbent(s) must be removed from the following office(s) to make room for newly elected candidate(s).<br />" +
                    "<em>If any incumbents won reelection, remove them here then mark them as winners on the </em>General Winners<em> tab.</em><br />" +
                    "<em>If no incumbents were running for reelection, remove the current office holder whose term is expiring.</em>"
            }.AddTo(parent);

            var container = new HtmlDiv().AddTo(parent, "offices");

            foreach (var incumbents in incumbentsToEliminate)
            {
                var office = incumbents.First();
                var div    = new HtmlDiv().AddTo(container, "office");
                div.Attributes.Add("rel", office.OfficeKey());
                new HtmlP {
                    InnerHtml = Offices.FormatOfficeName(office)
                }
                .AddTo(div, "office-name");
                var extra = office.ElectionPositions() -
                            (office.Incumbents() - incumbents.Count());
                new HtmlP
                {
                    InnerHtml = $"Eliminate {extra}"
                }
                .AddTo(div, "office-extra");
                foreach (var incumbent in incumbents)
                {
                    var p = new HtmlP().AddTo(div);
                    new HtmlInputCheckBox
                    {
                        Checked = true,
                        Value   = incumbent.PoliticianKey()
                    }.AddTo(p, "incumbent");
                    new LiteralControl(Politicians.FormatName(incumbent)).AddTo(p);
                }
            }
        }
Пример #15
0
        private void UnsubscribePolitician()
        {
            var politicianKey = GetQueryString("key");
            var table         = Politicians.GetDataByPoliticianKey(politicianKey);

            if (table.Count == 0)
            {
                Message.InnerText = "The requested email address was not found";
                return;
            }

            foreach (var row in table)
            {
                row.OptOut = true;
            }
            Politicians.UpdateTable(table);
            Message.InnerText =
                $"{Politicians.FormatName(table[0])} has been unsubscribed from all future candidate emails.";
        }
Пример #16
0
        private void BuildTable(IEnumerable <DataRow> unverifiedVideos)
        {
            var even = true;

            foreach (var row in unverifiedVideos)
            {
                var tr = new HtmlTableRow().AddTo(BodyPlaceHolder, even ? "even" : "odd");
                tr.Attributes.Add("data-key", row.PoliticianKey());
                even = !even;

                var td      = new HtmlTableCell().AddTo(tr, "name");
                var content = Politicians.FormatName(row) + " [" + row.StateCode() + "]";
                new HtmlDiv {
                    InnerText = content
                }.AddTo(td).Attributes.Add("title", content);

                td = new HtmlTableCell().AddTo(tr, "video");
                var div = new HtmlDiv().AddTo(td);
                div.Attributes.Add("title", row.YouTubeWebAddress());
                new HtmlAnchor
                {
                    InnerText = row.YouTubeWebAddress().GetYouTubeVideoId(),
                    HRef      = NormalizeUrl(row.YouTubeWebAddress()),
                    Target    = "view"
                }.AddTo(div);

                new HtmlTableCell {
                    InnerHtml = "<div>&nbsp;</div>"
                }.AddTo(tr, "channel-url");
                new HtmlTableCell {
                    InnerHtml = "<div>&nbsp;</div>"
                }.AddTo(tr, "channel-title");
                new HtmlTableCell {
                    InnerHtml = "<div>&nbsp;</div>"
                }.AddTo(tr, "channel-desc");
                new HtmlTableCell {
                    InnerHtml = "<div>&nbsp;</div>"
                }.AddTo(tr, "url-to-use");
            }
        }
Пример #17
0
        //protected Control FormatNameAndParty(DataRow politician, bool showParty = true)
        //{
        //  var span = new HtmlSpan();

        //  var politicianName = Politicians.FormatName(politician, true);
        //  var politicianAnchor = ReportUser == ReportUser.Public
        //    ? CreatePoliticianIntroAnchor(politician, politicianName)
        //    : CreateAdminPoliticianAnchor(politician, politicianName);
        //  politicianAnchor.AddTo(span);

        //  if (showParty && !IsNullOrWhiteSpace(politician.PartyCode()))
        //  {
        //    new Literal { Text = " - " }.AddTo(span);
        //    CreatePartyAnchor(politician, "view").AddTo(span);
        //  }

        //  return span;
        //}

        protected Control FormatNameAndPartyTable(DataRow politician, bool showParty = true)
        {
            var placeHolder = new PlaceHolder();
            var span        = new HtmlSpan().AddTo(placeHolder, "TName");

            var politicianName   = Politicians.FormatName(politician, true);
            var politicianAnchor = ReportUser == ReportUser.Public
        ? CreatePoliticianIntroAnchor(politician, politicianName)
        : CreateAdminPoliticianAnchor(politician, politicianName);

            politicianAnchor.AddTo(span);

            if (showParty && !IsNullOrWhiteSpace(politician.PartyCode()))
            {
                new Literal {
                    Text = " - "
                }.AddTo(span);
                CreatePartyAnchor(politician, "view").AddTo(span);
            }

            return(placeHolder);
        }
Пример #18
0
        protected Control FormatCandidateWebsite(DataRow candidate)
        {
            Control control = new PlaceHolder();

            var publicWebAddress = candidate.PublicWebAddress();

            if (!string.IsNullOrEmpty(publicWebAddress))
            {
                var div = new HtmlDiv().AddTo(control, "website");
                new HtmlImage {
                    Src = "/images/website.png"
                }.AddTo(div);
                new HtmlAnchor
                {
                    HRef      = VotePage.NormalizeUrl(publicWebAddress),
                    Target    = OffsiteTarget,
                    Title     = Politicians.FormatName(candidate) + "'s Website",
                    InnerText = "Website"
                }.AddTo(new HtmlSpan().AddTo(div));
            }

            return(control);
        }
Пример #19
0
        public static Control GetAnchors(DataRow row, out int count, bool addClearBoth = true,
                                         bool useLargeIcons = false)
        {
            var politicianName = Politicians.FormatName(row);

            count = 0;

            var ul = new HtmlUl();

            ul.Attributes.Add("class", "social-media-anchors");

            foreach (var medium in SocialMediaList)
            {
                var webAddress = medium.GetLink(row);
                if (IsNullOrWhiteSpace(webAddress))
                {
                    continue;
                }
                count++;
                CreateOneMediumAnchor(ul, webAddress, medium, politicianName, useLargeIcons);
            }

            // tack on email as a special case
            var email = row.PublicEmail();

            if (!IsNullOrWhiteSpace(email))
            {
                count++;
                CreateEmailAnchor(ul, email, politicianName, useLargeIcons);
            }

            // enclose the <ul> in a div and add a <div style="clear:both">
            // for safety sake

            return(FinishAnchors(ul, addClearBoth));
        }
Пример #20
0
        protected static Control FormatPoliticianWebsiteTable(DataRow politician, int breakTags = 2)
        {
            Control control;

            var publicWebAddress = politician.PublicWebAddress();

            if (!IsNullOrEmpty(publicWebAddress))
            {
                control = new PlaceHolder();
                if (breakTags > 0)
                {
                    new HtmlBreak(breakTags).AddTo(control);
                }
                var span = new HtmlSpan().AddTo(control, "TWebsite");
                CreatePoliticianWebsiteAnchor(publicWebAddress, "Website",
                                              Politicians.FormatName(politician, true, 30) + "'s Website").AddTo(span);
            }
            else
            {
                control = new Literal();
            }

            return(control);
        }
Пример #21
0
        private HtmlTable CreateBioTable()
        {
            var htmlTable =
                new HtmlTable {
                CellSpacing = 0, CellPadding = 0, Border = 0
            }.AddCssClasses(
                "bioTable");

            // Age
            //
            var tr = new HtmlTableRow().AddTo(htmlTable,
                                              "trPoliticianInfoContact trPoliticianInfoContactAge");
            var td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactHeading");

            new HtmlSpan {
                InnerHtml = "Age:"
            }.AddTo(td);
            new HtmlTableCell {
                InnerHtml = _PoliticianInfo.Age()
            }.AddTo(tr,
                    "tdPoliticianInfoContactDetail");

            // Party
            //
            tr = new HtmlTableRow().AddTo(htmlTable, "trPoliticianInfoContact");
            td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactHeading");
            new HtmlSpan {
                InnerHtml = "Party:"
            }.AddTo(td);
            td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactDetail");
            CreatePartyAnchor()
            .AddTo(td);

            // Phone
            //
            tr = new HtmlTableRow().AddTo(htmlTable, "trPoliticianInfoContact");
            td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactHeading");
            new HtmlSpan {
                InnerHtml = "Phone:"
            }.AddTo(td);
            var phone = _PoliticianInfo.PublicPhone();

            new HtmlTableCell
            {
                InnerHtml = string.IsNullOrWhiteSpace(phone) ? "n/a" : phone
            }.AddTo(tr,
                    "tdPoliticianInfoContactDetail");

            // Address
            //
            tr = new HtmlTableRow().AddTo(htmlTable, "trPoliticianInfoContact");
            td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactHeading");
            new HtmlSpan {
                InnerHtml = "Address:"
            }.AddTo(td);
            var address = _PoliticianInfo.PublicAddress();

            if (!string.IsNullOrWhiteSpace(address))
            {
                address += "<br />";
            }
            address += _PoliticianInfo.PublicCityStateZip();
            new HtmlTableCell
            {
                InnerHtml = string.IsNullOrWhiteSpace(address) ? "n/a" : address
            }.AddTo(
                tr, "tdPoliticianInfoContactDetail");

            // Social media
            //
            tr = new HtmlTableRow().AddTo(htmlTable, "trPoliticianInfoContact");
            td = new HtmlTableCell().AddTo(tr, "tdPoliticianInfoContactHeading");
            new HtmlSpan {
                InnerHtml = "&nbsp;"
            }.AddTo(td);
            var webUrl = _PoliticianInfo.PublicWebAddress();

            td = new HtmlTableCell().AddTo(tr,
                                           "tdPoliticianInfoContactDetail socialMedia");
            new HtmlBreak(2).AddTo(td);
            if (!string.IsNullOrWhiteSpace(webUrl))
            {
                var span  = new HtmlSpan().AddTo(td, "TWebsite");
                var title = Politicians.FormatName(_PoliticianInfo) + "'s Website";
                new HtmlAnchor
                {
                    HRef      = VotePage.NormalizeUrl(webUrl),
                    Title     = title,
                    Target    = "view",
                    InnerHtml = "Website"
                }.AddTo(span);
                new HtmlBreak(2).AddTo(td);
            }
            SocialMedia.GetAnchors(_PoliticianInfo)
            .AddTo(td);

            return(htmlTable);
        }
        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();
        }
Пример #23
0
        public void voterInfoQuery(double latitude, double longitude,
                                   string electionDay, string state, string accessKey)
        {
            var result = new VoterBallotIdentifiersRetrieveData
            {
                status = "OK", success = true, latitude = latitude, longitude = longitude, kind = "voteusa#voterInfoQuery"
            };

            state = state.ToUpperInvariant();
            if (StateCache.IsValidStateCode(state))
            {
                result.state = state;
            }
            else
            {
                result.status  = "Invalid state";
                result.success = false;
            }

            if (DateTime.TryParseExact(electionDay, "yyyy-MM-dd", new CultureInfo("en-US"),
                                       DateTimeStyles.None, out var electionDate))
            {
                result.electionDay = electionDay;
            }
            else
            {
                result.status  = "Invalid electionDay";
                result.success = false;
            }

            if (accessKey != "M@gicWord")
            {
                result.status  = "Unauthorized";
                result.success = false;
            }

            // There could be multiple election keys if it's a primary day
            var keys = Elections.GetStateElectionKeysForDate(state, electionDate);

            if (keys.Count < 1)
            {
                result.status  = $"No elections found for {electionDay} in {state}";
                result.success = false;
            }

            if (result.success) // all validation passed
            {
                var tiger = TigerLookup.LookupAll(latitude, longitude);
                // handle the keys -- first one is arbitrarily the main election
                result.election = new ElectionInfo
                {
                    electionDay = electionDay,
                    name        = Elections.GetElectionDesc(keys[0]),
                    id          = keys[0]
                };
                // if there are additional elections, post them
                result.otherElections = new List <ElectionInfo>();
                foreach (var key in keys.Skip(1))
                {
                    result.otherElections.Add(new ElectionInfo
                    {
                        electionDay = electionDay,
                        name        = Elections.GetElectionDesc(key),
                        id          = key
                    });
                }
                result.contests = new List <Contest>();
                foreach (var key in keys)
                {
                    var data = ElectionsPoliticians.GetSampleBallotData(key, tiger.Congress,
                                                                        tiger.Upper, tiger.Lower, tiger.County, tiger.District, tiger.Place,
                                                                        tiger.Elementary, tiger.Secondary, tiger.Unified, tiger.CityCouncil,
                                                                        tiger.CountySupervisors, Empty);
                    var contests = data.Rows.OfType <DataRow>().GroupBy(r =>
                                                                        new { ElectionKey = r.ElectionKey(), OfficeKey = r.OfficeKey() }).ToList();
                    foreach (var contest in contests)
                    {
                        var candidates = new List <Candidate>();
                        foreach (var candidate in contest)
                        {
                            candidates.Add(new Candidate
                            {
                                id   = candidate.PoliticianKey(),
                                name = Politicians.FormatName(candidate)
                            });
                        }
                        result.contests.Add(new Contest
                        {
                            office     = Offices.FormatOfficeName(contest.First()),
                            id         = $"{contest.Key.ElectionKey}|{contest.Key.OfficeKey}",
                            candidates = candidates
                        });
                    }
                }
            }

            var javaScriptSerializer = new JavaScriptSerializer();
            var jsonString           = javaScriptSerializer.Serialize(result);

            Context.Response.Write(jsonString);
        }
Пример #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var stateCode = Request.QueryString["state"];

            if (IsNullOrWhiteSpace(stateCode))
            {
                throw new VoteException("State code is missing.");
            }
            if (!StateCache.IsValidStateCode(stateCode))
            {
                throw new VoteException("State code is invalid.");
            }
            var includeMissing = GetQueryString("m") == "1";
            var includeWith    = GetQueryString("w") == "1";
            var fileDesc       = includeMissing
        ? (includeWith ? ".all" : ".missing-incumbents")
        : ".with-incumbents";

            // get the data
            var rows = LocalDistricts.GetOfficesForCsv(stateCode).Rows.OfType <DataRow>()
                       .Where(r => !IsNullOrWhiteSpace(r.ElectionKey()) &&
                              (includeMissing && IsNullOrWhiteSpace(r.PoliticianKey()) ||
                               includeWith && !IsNullOrWhiteSpace(r.PoliticianKey())))
                       .ToList();

            // apply counties to the data
            var countiesForLocals =
                LocalIdsCodes.FindCountiesWithNames(stateCode, rows.Select(r => r.LocalKey()).Distinct());
            var data = rows.SelectMany(r => countiesForLocals[r.LocalKey()].Select(c =>
                                                                                   new
            {
                Row        = r,
                CountyCode = c.Value,
                County     = c.Text,
                AlsoIn     = countiesForLocals[r.LocalKey()]
                             .Where(o => o.Text != c.Text).Select(o => o.Text).ToArray()
            }))
                       .OrderBy(r => r.County)
                       .ThenBy(r => r.Row.LocalDistrict())
                       .ThenBy(r => r.Row.OfficeLine1())
                       .ThenBy(r => r.Row.OfficeLine2())
                       .ToArray();

            // create the csv
            string csv;

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

                // write headers
                csvWriter.AddField("State Code");
                csvWriter.AddField("County Name");
                csvWriter.AddField("County Code");
                csvWriter.AddField("Also In");
                csvWriter.AddField("Local Name");
                csvWriter.AddField("Local Key");
                csvWriter.AddField("Office Name");
                csvWriter.AddField("Office Key");
                csvWriter.AddField("Incumbent Name");
                csvWriter.AddField("Politician Key");
                csvWriter.AddField("Election Key");
                csvWriter.Write(streamWriter);

                foreach (var row in data)
                {
                    csvWriter.AddField(row.Row.StateCode());
                    csvWriter.AddField(row.County);
                    csvWriter.AddField(row.CountyCode);
                    csvWriter.AddField(Join(", ", row.AlsoIn));
                    csvWriter.AddField(row.Row.LocalDistrict());
                    csvWriter.AddField(row.Row.LocalKey());
                    csvWriter.AddField(Offices.FormatOfficeName(row.Row));
                    csvWriter.AddField(row.Row.OfficeKey() ?? Empty);
                    csvWriter.AddField(Politicians.FormatName(row.Row));
                    csvWriter.AddField(row.Row.PoliticianKey() ?? Empty);
                    csvWriter.AddField(row.Row.ElectionKey() ?? Empty);
                    csvWriter.AddField(
                        row.Row.ElectionKey() == null ?
                        Empty
              : $"=HYPERLINK(\"{UrlManager.GetAdminUri(GetAdminFolderPageUrl("election", "election", row.Row.ElectionKey()))}\",\"Election Report\")");
                    csvWriter.AddField(
                        row.Row.ElectionKey() == null || row.Row.OfficeKey() == null ?
                        Empty
              : $"=HYPERLINK(\"{UrlManager.GetAdminUri(GetOfficeWinnerPageUrl(row.Row.ElectionKey(), row.Row.OfficeKey()))}\",\"Identify Winners\")");

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

            // download
            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition",
                               $"attachment;filename=\"local-offices-{stateCode}{fileDesc}.csv\"");
            Response.Write("\xfeff"); // BOM
            Response.Write(csv);
            Response.End();
        }
        public static void Report()
        {
            // Get yesterday's activity
            var placeholder = new PlaceHolder();
            var date        = DateTime.UtcNow.Date.AddDays(-1);
            var logins      = LogLogins.GetPoliticianLoginsByDateStampRange(date).Rows.OfType <DataRow>()
                              .ToList();

            var message = new HtmlP();

            message.AddTo(placeholder);
            message.Style.Add(HtmlTextWriterStyle.FontFamily, "arial");
            message.Style.Add(HtmlTextWriterStyle.FontSize, "8pt");
            if (logins.Count == 0)
            {
                message.InnerText = $"There were no politician sign-ins on {date:d}";
            }
            else
            {
                message.InnerText = $"These politicians signed in on {date:d}";
                var lines = logins.Select(r =>
                {
                    var tr = new TableRow {
                        TableSection = TableRowSection.TableBody
                    };
                    new TableCell {
                        Text = r.StateCode()
                    }.AddTo(tr);
                    new TableCell {
                        Text = r.PoliticianKey()
                    }.AddTo(tr);
                    new TableCell {
                        Text = Politicians.FormatName(r)
                    }.AddTo(tr);
                    new TableCell {
                        Text = Offices.FormatOfficeName(r)
                    }.AddTo(tr);
                    new TableCell {
                        Text = r.ElectionDescription()
                    }.AddTo(tr);
                    new TableCell {
                        Text = r.LiveOfficeStatus()
                    }.AddTo(tr);
                    foreach (var td in tr.Controls.OfType <TableCell>())
                    {
                        td.Style.Add(HtmlTextWriterStyle.BorderWidth, "1px");
                        td.Style.Add(HtmlTextWriterStyle.BorderStyle, "solid");
                        td.Style.Add(HtmlTextWriterStyle.BorderColor, "#cccccc");
                        td.Style.Add(HtmlTextWriterStyle.Padding, "3px");
                    }
                    return(tr);
                });

                var table = new Table();
                table.AddTo(placeholder);
                table.Style.Add(HtmlTextWriterStyle.BorderCollapse, "collapse");
                table.Style.Add(HtmlTextWriterStyle.FontFamily, "arial");
                table.Style.Add(HtmlTextWriterStyle.FontSize, "8pt");
                table.Style.Add(HtmlTextWriterStyle.MarginTop, "20px");

                // Add the heading row
                var thr = new TableHeaderRow();
                thr.AddTo(table);
                thr.TableSection = TableRowSection.TableHeader;
                thr.Style.Add(HtmlTextWriterStyle.FontWeight, "bold");
                thr.Style.Add(HtmlTextWriterStyle.Color, "#ffffff");
                thr.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#666666");
                new TableHeaderCell {
                    Text = "State"
                }.AddTo(thr);
                new TableHeaderCell {
                    Text = "Politician Key"
                }.AddTo(thr);
                new TableHeaderCell {
                    Text = "Name"
                }.AddTo(thr);
                new TableHeaderCell {
                    Text = "Office"
                }.AddTo(thr);
                new TableHeaderCell {
                    Text = "Election"
                }.AddTo(thr);
                new TableHeaderCell {
                    Text = "Status"
                }.AddTo(thr);
                foreach (var th in thr.Controls.OfType <TableHeaderCell>())
                {
                    th.Style.Add(HtmlTextWriterStyle.BorderWidth, "1px");
                    th.Style.Add(HtmlTextWriterStyle.BorderStyle, "solid");
                    th.Style.Add(HtmlTextWriterStyle.BorderColor, "#666666");
                    th.Style.Add(HtmlTextWriterStyle.Padding, "3px");
                    th.Style.Add(HtmlTextWriterStyle.TextAlign, "left");
                }

                foreach (var line in lines)
                {
                    line.AddTo(table);
                }
            }

            SendEmails(placeholder, date);
        }
Пример #26
0
        private int PopulateWinnersBetaTree(DataTable table, Control root)
        {
            void CreateNode(Control parent,
                            IEnumerable <DataRow> office, string className = null,
                            bool useLine2Only = false)
            {
                var candidates = office.ToList();
                var officeInfo = candidates[0];
                var winners    = candidates.Where(row => row.IsWinner()).ToList();
                var advancers  = candidates.Where(row => row.AdvanceToRunoff()).ToList();
                // if any candidates are marked as AdvanceToRunoff, we default it as a runoff
                var isRunoff = advancers.Count > 0;

                // Now create the node
                // Format the office description
                var text = useLine2Only
          ? officeInfo.OfficeLine2()
          : Offices.FormatOfficeName(officeInfo);

                // Include the position slot count if > 1
                if (officeInfo.PrimaryPositions() > 1)
                {
                    text = $"{text} [{officeInfo.PrimaryPositions()}]";
                }

                var addClass = "office-name no-checkbox";

                if (!IsNullOrWhiteSpace(className))
                {
                    addClass += " " + className;
                }
                var data = "key:'" + officeInfo.OfficeKey() + "',addClass:'" + addClass +
                           "',hideCheckbox:true,unselectable:true";
                var officeNode = new HtmlLi().AddTo(parent);

                officeNode.Attributes.Add("data", data);
                new HtmlDiv {
                    InnerHtml = text
                }.AddTo(officeNode, "label");
                var dropdownDiv = new HtmlDiv().AddTo(officeNode,
                                                      "dropdowns idwinners-" + officeInfo.OfficeKey());

                // if there is a possible runoff, create checkbox and runoff list
                var runoffPositions = officeInfo.PrimaryRunoffPositions();

                if (runoffPositions != 0)
                {
                    var minCandidates = runoffPositions == -1
            ? officeInfo.PrimaryPositions() + 1
            : runoffPositions + 1;
                    if (candidates.Count >= minCandidates)
                    {
                        // if any candidates are marked as AdvanceToRunoff, we default it as a runoff
                        isRunoff = candidates.Any(row => row.AdvanceToRunoff());

                        var runnoffId      = "runoff-" + officeInfo.OfficeKey();
                        var runoffDiv      = new HtmlDiv().AddTo(dropdownDiv);
                        var runoffCheckbox =
                            new HtmlInputCheckBox {
                            Checked = isRunoff
                        }.AddTo(runoffDiv, "runoff-checkbox");
                        if (runoffPositions > 0)
                        {
                            runoffCheckbox.Attributes.Add("rel",
                                                          runoffPositions.ToString(CultureInfo.InvariantCulture));
                        }
                        new HtmlLabel {
                            ID = runnoffId, InnerText = "Runoff is required"
                        }.AddTo(runoffDiv)
                        .Attributes["for"] = runnoffId;
                        var runoffsDiv = new HtmlDiv().AddTo(runoffDiv, "runoff-dropdown");
                        if (!isRunoff)
                        {
                            runoffsDiv.AddCssClasses("hidden");
                        }
                        else
                        {
                            runoffsDiv.RemoveCssClass("hidden");
                        }
                        new HtmlP
                        {
                            InnerText = "Select " +
                                        (runoffPositions == -1
                  ? Empty
                  : runoffPositions.ToString(CultureInfo.InvariantCulture)) +
                                        " candidates to advance"
                        }.AddTo(runoffsDiv);

                        var runoffList = new HtmlSelect
                        {
                            EnableViewState = false,
                            Size            = candidates.Count,
                            Multiple        = true
                        }.AddTo(runoffsDiv);

                        foreach (var politician in candidates)
                        {
                            var name = Politicians.FormatName(politician);
                            if (!IsNullOrWhiteSpace(politician.PartyCode()))
                            {
                                name += $" ({politician.PartyCode()})";
                            }
                            var indicators = Empty;

                            // Add winner indicator
                            if (politician.AdvanceToRunoff())
                            {
                                indicators += "◄";
                            }

                            if (indicators != Empty)
                            {
                                name += " " + indicators;
                            }

                            runoffList.AddItem(name, politician.PoliticianKey(),
                                               politician.AdvanceToRunoff());
                        }
                    }
                }

                var winnersDiv = new HtmlDiv().AddTo(dropdownDiv, "winners-dropdowns");

                if (isRunoff)
                {
                    winnersDiv.AddCssClasses("hidden");
                }
                else
                {
                    winnersDiv.RemoveCssClass("hidden");
                }

                if (candidates.Count <= officeInfo.PrimaryPositions())
                {
                    // uncontested -- create a disabled dropdown for each candidate
                    foreach (var politician in candidates)
                    {
                        var dropdownList = new HtmlSelect {
                            EnableViewState = false
                        }.AddTo(winnersDiv);
                        dropdownList.Attributes.Add("disabled", "disabled");

                        var name = Politicians.FormatName(politician);
                        if (!IsNullOrWhiteSpace(politician.PartyCode()))
                        {
                            name += $" ({politician.PartyCode()})";
                        }
                        var indicators = Empty;

                        // Add winner indicator
                        if (winners.FirstOrDefault(winner => winner.PoliticianKey()
                                                   .IsEqIgnoreCase(politician.PoliticianKey())) != null)
                        {
                            indicators += "◄";
                        }

                        if (indicators != Empty)
                        {
                            name += " " + indicators;
                        }

                        dropdownList.AddItem(name, politician.PoliticianKey(), true);
                    }
                }
                else
                {
                    // contested -- create a dropdown for each already-identified winner,
                    // with the default selection as the winner
                    //// and the other winners removed from the list
                    var dropdownContents = winners.Select(winner => new
                    {
                        DefaultPolitician = winner.PoliticianKey(),
                        List = candidates.Where(row =>
                                                //  row.PoliticianKey() == winner.PoliticianKey() ||
                                                //    !row.IsWinner()
                                                true).ToList()
                    }).ToList();

                    // Create the winner dropdowns
                    foreach (var dropdownContent in dropdownContents)
                    {
                        var dropdownList = new HtmlSelect {
                            EnableViewState = false
                        }.AddTo(winnersDiv);
                        dropdownList.Attributes.Add("title", "Select one");

                        // allow unselect
                        dropdownList.AddItem("Unselect Winner", Empty);

                        // Add an option for each politician
                        foreach (var politician in dropdownContent.List.OrderBy(row => row.LastName())
                                 .ThenBy(row => row.FirstName()))
                        {
                            var name = Politicians.FormatName(politician);
                            if (!IsNullOrWhiteSpace(politician.PartyCode()))
                            {
                                name += $" ({politician.PartyCode()})";
                            }
                            var indicators = Empty;

                            // Add winner indicator
                            if (winners.FirstOrDefault(winner => winner.PoliticianKey()
                                                       .IsEqIgnoreCase(politician.PoliticianKey())) != null)
                            {
                                indicators += "◄";
                            }

                            if (indicators != Empty)
                            {
                                name += " " + indicators;
                            }

                            dropdownList.AddItem(name, politician.PoliticianKey(),
                                                 !isRunoff && dropdownContent.DefaultPolitician == politician.PoliticianKey());
                        }
                    }

                    // if there are more positions than already-identified winners and some non-winning candidates,
                    // fill out with undefaulted lists that contain all candidates
                    if (winners.Count < officeInfo.PrimaryPositions())
                    {
                        var nonWinners = candidates.Where(row => !row.IsWinner()).ToList();
                        var counter    = Math.Min(nonWinners.Count,
                                                  officeInfo.PrimaryPositions() - winners.Count);
                        while (counter-- > 0)
                        {
                            var dropdownList = new HtmlSelect {
                                EnableViewState = false
                            }.AddTo(winnersDiv)
                            .AddCssClasses("bold") as HtmlSelect;
                            Debug.Assert(dropdownList != null, "dropdownList != null");
                            dropdownList.Attributes.Add("title", "Select one");

                            // The first option in each dropdown is a disabled header
                            var option = dropdownList.AddItem("Select Winner", Empty, true);
                            option.Attributes.Add("disabled", "disabled");

                            // Add an option for each politician
                            foreach (var politician in candidates.OrderBy(row => row.LastName())
                                     .ThenBy(row => row.FirstName()))
                            {
                                var name = Politicians.FormatName(politician);
                                if (!IsNullOrWhiteSpace(politician.PartyCode()))
                                {
                                    name += $" ({politician.PartyCode()})";
                                }

                                dropdownList.AddItem(name, politician.PoliticianKey());
                            }
                        }
                    }
                }
            }

            var officeCount = 0;

            root.Controls.Clear();
            var tree = new HtmlUl().AddTo(root);

            const string rootText = "Select the Winner(s) for Each Contested Primary Office";
            const string rootData =
                "addClass:'root-node no-checkbox',hideCheckbox:true,unselectable:true";

            var rootNode = new HtmlLi {
                InnerHtml = rootText
            }.AddTo(tree);

            rootNode.Attributes.Add("data", rootData);
            var rootTree = new HtmlUl().AddTo(rootNode);

            var officeClasses = table.Rows.Cast <DataRow>().GroupBy(row => row.OfficeClass());
            var even          = false;

            foreach (var officeClass in officeClasses)
            {
                var offices = officeClass.GroupBy(row => row.OfficeKey()).ToList();
                officeCount += offices.Count;
                if (offices.Count == 1)
                {
                    CreateNode(rootTree, offices[0], "odd");
                    even = !even;
                }
                else
                {
                    // If all OfficeLine1's are identical, don't show them
                    var hasVariedLine1 = offices.Exists(row => row.First().OfficeLine1() !=
                                                        offices[0].First().OfficeLine1());
                    var text = Offices.GetOfficeClassShortDescription(officeClass.Key, StateCode);
                    var classNode = new HtmlLi {
                        InnerHtml = text
                    }.AddTo(rootTree);
                    classNode.Attributes.Add("data",
                                             "addClass:'office-class no-checkbox office-class-" + officeClass.Key +
                                             "',key:'office-class-" + officeClass.Key +
                                             "',hideCheckbox:true,unselectable:true");
                    var classSubTree = new HtmlUl().AddTo(classNode);
                    foreach (var office in offices)
                    {
                        CreateNode(classSubTree, office,
                                   /*even ? "even" :*/ "odd", !hasVariedLine1);
                        even = !even;
                    }
                }
            }
            return(officeCount);
        }
Пример #27
0
        private void LoadPoliticians()
        {
            _StateDictionary = StateCache.All51StateCodes.ToDictionary(state => state,
                                                                       state =>
                                                                       new StateInfo
            {
                StateCode  = state,
                Unaccented = new Dictionary <string, List <PoliticianInfo> >(),
                Metaphone  = new Dictionary <string, List <PoliticianInfo> >(),
                Stripped   = new Dictionary <string, List <PoliticianInfo> >()
            },
                                                                       StringComparer.OrdinalIgnoreCase);

            var politicians = Politicians.GetAllNameSearchData();

            foreach (var row in politicians)
            {
                var lname = row.LastName.ToLowerInvariant();
                var uname = GetUnaccentedName(row.LastName);
                var mname = row.LastName.DoubleMetaphone()
                            .ToLowerInvariant();
                var sname = GetStrippedName(uname);

                var pi = new PoliticianInfo
                {
                    PoliticianKey      = row.PoliticianKey,
                    LowerLastName      = lname,
                    UnaccentedLastName = uname,
                    MetaphoneLastName  = mname,
                    StrippedLastName   = sname,
                    OfficeKey          = row.LiveOfficeKey,
                    OfficeStatus       = row.LiveOfficeStatus.ToPoliticianStatus(),
                    DisplayName        = Politicians.FormatName(row)
                };

                var stateCode = Politicians.GetStateCodeFromKey(pi.PoliticianKey);
                var si        = _StateDictionary[stateCode];
                List <PoliticianInfo> list;

                var twoCharacterKey = GetTwoCharacterKey(uname);
                if (!si.Unaccented.TryGetValue(twoCharacterKey, out list))
                {
                    list = new List <PoliticianInfo>();
                    si.Unaccented.Add(twoCharacterKey, list);
                }
                list.Add(pi);

                twoCharacterKey = GetTwoCharacterKey(mname);
                if (!si.Metaphone.TryGetValue(twoCharacterKey, out list))
                {
                    list = new List <PoliticianInfo>();
                    si.Metaphone.Add(twoCharacterKey, list);
                }
                list.Add(pi);

                twoCharacterKey = GetTwoCharacterKey(uname);
                if (!si.Stripped.TryGetValue(twoCharacterKey, out list))
                {
                    list = new List <PoliticianInfo>();
                    si.Stripped.Add(twoCharacterKey, list);
                }
                list.Add(pi);
            }

            _OfficeDictionary = Offices.GetAllNameSearchData()
                                .ToDictionary(row => row.OfficeKey,
                                              row =>
                                              new OfficeInfo
            {
                OfficeKey            = row.OfficeKey,
                OfficeLine1          = row.OfficeLine1,
                OfficeLine2          = row.OfficeLine2,
                OfficeClass          = row.OfficeLevel.ToOfficeClass(),
                AlternateOfficeClass = row.AlternateOfficeLevel.ToOfficeClass(),
                CountyCode           = row.CountyCode,
                LocalCode            = row.LocalCode
            });
        }
Пример #28
0
        private void PopulateWinnersTree_CreateNode(Control parent,
                                                    IEnumerable <DataRow> office, string className, bool useLine2Only = false)
        {
            var officeRows          = office.ToList();
            var officeInfo          = officeRows[0];
            var officeState         = Offices.GetStateCodeFromKey(officeInfo.OfficeKey());
            var electionState       = Elections.GetStateCodeFromKey(GetElectionKey());
            var canUpdateIncumbents = StateCache.IsValidStateCode(officeState) &&
                                      StateCache.IsValidStateCode(electionState);

            var winners = officeRows.Where(row => row.IsWinner())
                          .ToList();
            var candidates = officeRows.Where(row => !row.IsIncumbentRow())
                             .ToList();
            var advancers = candidates.Where(row => row.AdvanceToRunoff())
                            .ToList();
            // if any candidates are marked as AdvanceToRunoff, we default it as a runoff
            var isRunoff   = advancers.Count > 0;
            var incumbents = officeRows.Where(row => row.IsIncumbentRow())
                             .ToList();
            var incumbentsInElectionNotMarkedWinners = officeRows
                                                       .Where(row => !row.IsIncumbentRow() && !row.IsWinner() &&
                                                              (incumbents.FirstOrDefault(i => i.PoliticianKey()
                                                                                         .IsEqIgnoreCase(row.PoliticianKey())) != null))
                                                       .ToList();
            var defaultPoliticians = winners.Select(row => row.PoliticianKey())
                                     .Union(
                incumbentsInElectionNotMarkedWinners.Select(row => row.PoliticianKey()))
                                     .ToList();

            // Creating a dropdown for each Election position
            var dropdownContents = Enumerable.Range(0, officeInfo.ElectionPositions())
                                   .Select(n => new
            {
                DefaultPolitician = n < defaultPoliticians.Count ? defaultPoliticians[n] : string.Empty,
                List = new List <DataRow>(candidates)
            })
                                   .ToList();

            // Now create the node
            // Format the office description
            var text = useLine2Only
        ? officeInfo.OfficeLine2()
        : Offices.FormatOfficeName(officeInfo);

            var addClass = "office-name";

            if (!canUpdateIncumbents)
            {
                addClass += " no-checkbox";
            }
            if (!string.IsNullOrWhiteSpace(className))
            {
                addClass += " " + className;
            }
            var data = "key:'" + officeInfo.OfficeKey();

            if (canUpdateIncumbents)
            {
                data += "',addClass:'" + addClass + "',select:true";
            }
            else
            {
                data +=
                    "',addClass:'" + addClass + "',hideCheckbox:true,unselectable:true";
            }
            var officeNode = new HtmlLi().AddTo(parent);

            officeNode.Attributes.Add("data", data);
            new HtmlDiv {
                InnerHtml = text
            }.AddTo(officeNode, "label")
            .Attributes.Add("Title", text);
            var dropdownDiv = new HtmlDiv().AddTo(officeNode,
                                                  "dropdowns idwinners-" + officeInfo.OfficeKey());

            // if there is a possible runoff, create checkbox and runoff list
            var runoffPositions = officeInfo.GeneralRunoffPositions();

            if (runoffPositions != 0)
            {
                var minCandidates = runoffPositions == -1
          ? officeInfo.ElectionPositions() + 1
          : runoffPositions + 1;
                if (candidates.Count >= minCandidates)
                {
                    // if any candidates are marked as AdvanceToRunoff, we default it as a runoff
                    isRunoff = candidates.Any(row => row.AdvanceToRunoff());

                    var runnoffId = "runoff-" + officeInfo.OfficeKey();
                    var runoffDiv = new HtmlDiv().AddTo(dropdownDiv);
                    var runoffCheckbox = new HtmlInputCheckBox {
                        Checked = isRunoff
                    }.AddTo(runoffDiv,
                            "runoff-checkbox");
                    if (runoffPositions > 0)
                    {
                        runoffCheckbox.Attributes.Add("rel",
                                                      runoffPositions.ToString(CultureInfo.InvariantCulture));
                    }
                    new HtmlLabel
                    {
                        ID        = runnoffId,
                        InnerText = "Runoff is required"
                    }.AddTo(runoffDiv)
                    .Attributes["for"] = runnoffId;
                    var runoffsDiv = new HtmlDiv().AddTo(runoffDiv, "runoff-dropdown");
                    if (!isRunoff)
                    {
                        runoffsDiv.AddCssClasses("hidden");
                    }
                    else
                    {
                        runoffsDiv.RemoveCssClass("hidden");
                    }
                    new HtmlP
                    {
                        InnerText = "Select " + (runoffPositions == -1
              ? string.Empty
              : runoffPositions.ToString(CultureInfo.InvariantCulture)) + " candidates to advance"
                    }.AddTo(runoffsDiv);

                    var runoffList =
                        new HtmlSelect
                    {
                        EnableViewState = false,
                        Size            = candidates.Count,
                        Multiple        = true
                    }.AddTo(runoffsDiv);

                    foreach (var politician in candidates)
                    {
                        var name = Politicians.FormatName(politician);
                        if (!string.IsNullOrWhiteSpace(politician.PartyCode()))
                        {
                            name += " (" + politician.PartyCode() + ")";
                        }
                        var indicators = string.Empty;

                        // Add winner indicator
                        if (politician.AdvanceToRunoff())
                        {
                            indicators += "◄";
                        }

                        if (indicators != string.Empty)
                        {
                            name += " " + indicators;
                        }

                        runoffList.AddItem(name, politician.PoliticianKey(), politician.AdvanceToRunoff());
                    }
                }
            }

            var winnersDiv = new HtmlDiv().AddTo(dropdownDiv, "winners-dropdowns");

            if (isRunoff)
            {
                winnersDiv.AddCssClasses("hidden");
            }
            else
            {
                winnersDiv.RemoveCssClass("hidden");
            }

            // Create the dropdowns
            var inx = 0;

            foreach (var dropdownContent in dropdownContents)
            {
                var dropdownList =
                    new HtmlSelect {
                    EnableViewState = false
                }.AddTo(winnersDiv);

                if (inx >= winners.Count)
                {
                    dropdownList.AddCssClasses("bold");
                }

                // The first option in each dropdown is a disabled header
                var dropDownMessage = dropdownContent.List.Count > 0
          ? "Select winner or Vacant"
          : "No candidates";
                var option = dropdownList.AddItem(dropDownMessage, string.Empty,
                                                  dropdownContent.DefaultPolitician == string.Empty);
                option.Attributes.Add("disabled", "disabled");

                // Add an option for each politician
                foreach (
                    var politician in dropdownContent.List.OrderBy(row => row.LastName())
                    .ThenBy(row => row.FirstName()))
                {
                    var name = Politicians.FormatName(politician);
                    if (!string.IsNullOrWhiteSpace(politician.PartyCode()))
                    {
                        name += " (" + politician.PartyCode() + ")";
                    }
                    var indicators = string.Empty;

                    // Add winner indicator
                    if (winners.FirstOrDefault(winner => winner.PoliticianKey()
                                               .IsEqIgnoreCase(politician.PoliticianKey())) != null)
                    {
                        indicators += "◄";
                    }

                    if (indicators != string.Empty)
                    {
                        name += " " + indicators;
                    }

                    dropdownList.AddItem(name, politician.PoliticianKey(),
                                         dropdownContent.DefaultPolitician == politician.PoliticianKey());
                }

                // Add a "Vacant" option
                dropdownList.AddItem("Vacant", "vacant");
                inx++;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var stateCode = Request.QueryString["state"];

            if (IsNullOrWhiteSpace(stateCode))
            {
                throw new VoteException("State code is missing.");
            }
            if (!StateCache.IsValidStateCode(stateCode))
            {
                throw new VoteException("State code is invalid.");
            }
            var includeMissing = GetQueryString("m") == "1";
            var includeWith    = GetQueryString("w") == "1";
            var fileDesc       = includeMissing
        ? includeWith ? ".all" : ".missing-incumbents"
        : ".with-incumbents";

            // get the data
            var table = Counties.GetOfficesForCsv(stateCode);

            // create the csv
            string csv;

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

                // write headers
                csvWriter.AddField("State Code");
                csvWriter.AddField("County Name");
                csvWriter.AddField("County Code");
                csvWriter.AddField("Office Name");
                csvWriter.AddField("Office Key");
                csvWriter.AddField("Incumbent Name");
                csvWriter.AddField("Politician Key");
                csvWriter.AddField("Election Key");
                csvWriter.Write(streamWriter);

                foreach (var row in table.Rows.OfType <DataRow>()
                         .Where(r => !IsNullOrWhiteSpace(r.ElectionKey()) &&
                                (includeMissing && IsNullOrWhiteSpace(r.PoliticianKey()) ||
                                 includeWith && !IsNullOrWhiteSpace(r.PoliticianKey()))))
                {
                    csvWriter.AddField(row.StateCode());
                    csvWriter.AddField(row.County());
                    csvWriter.AddField(row.CountyCode());
                    csvWriter.AddField(Offices.FormatOfficeName(row));
                    csvWriter.AddField(row.OfficeKey() ?? Empty);
                    csvWriter.AddField(Politicians.FormatName(row));
                    csvWriter.AddField(row.PoliticianKey() ?? Empty);
                    csvWriter.AddField(row.ElectionKey() ?? Empty);
                    csvWriter.AddField(
                        row.ElectionKey() == null ?
                        Empty
              : $"=HYPERLINK(\"{UrlManager.GetAdminUri(GetAdminFolderPageUrl("election", "election", row.ElectionKey()))}\",\"Election Report\")");
                    csvWriter.AddField(
                        row.ElectionKey() == null || row.OfficeKey() == null ?
                        Empty
              : $"=HYPERLINK(\"{UrlManager.GetAdminUri(GetOfficeWinnerPageUrl(row.ElectionKey(), row.OfficeKey()))}\",\"Identify Winners\")");

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

            // download
            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition",
                               $"attachment;filename=\"county-offices-{stateCode}{fileDesc}.csv\"");
            Response.Write("\xfeff"); // BOM
            Response.Write(csv);
            Response.End();
        }
Пример #30
0
        protected void ButtonAddNewCandidate_OnClick(object sender, EventArgs e)
        {
            bool validateDuplicates;

            bool.TryParse(AddCandidateValidateDuplicates.GetValue(),
                          out validateDuplicates);

            AddCandidateDuplicatesHtml.Controls.Clear();
            _AddNewCandidateSubTabInfo.ClearValidationErrors();
            AddCandidateNewId.SetValue(string.Empty);

            // No actual updating here, just validation and reformatting
            _AddNewCandidateSubTabInfo.Update(FeedbackAddNewCandidate, false);
            if (FeedbackAddNewCandidate.ValidationErrorCount > 0)
            {
                return;
            }

            var stateCode  = ControlAddNewCandidateStateCode.GetValue();
            var firstName  = ControlAddNewCandidateFName.GetValue();
            var middleName = ControlAddNewCandidateMName.GetValue();
            var nickname   = ControlAddNewCandidateNickname.GetValue();
            var lastName   = ControlAddNewCandidateLName.GetValue();
            var suffix     = ControlAddNewCandidateSuffix.GetValue();

            var formattedName = Politicians.FormatName(firstName, middleName, nickname,
                                                       lastName, suffix);

            if (validateDuplicates)
            {
                var duplicatesHtml = Politicians.GetCandidateList(lastName, null, stateCode,
                                                                  null, true);
                AddCandidateDuplicatesHtml.Controls.Add(duplicatesHtml);
                if (duplicatesHtml.Controls.Count > 0)
                {
                    // Set up the duplicates dialog
                    AddCandidateFormattedName.SetValue(formattedName);
                    AddCandidateStateName.SetValue(StateCache.GetStateName(stateCode));
                    FeedbackAddNewCandidate.PostValidationError(ControlAddNewCandidateLName,
                                                                "Potential duplicate politician");
                    return;
                }
            }

            var newPoliticianKey = Politicians.GetUniqueKey(stateCode, lastName,
                                                            firstName, middleName, suffix);

            AddCandidateNewId.SetValue(newPoliticianKey);

            // If it's a primary, get the party key from the election
            //var partyKey = "X";
            var partyKey    = string.Empty; // mantis 508
            var electionKey = SafeGetElectionKey();

            if (Elections.IsPrimaryElection(electionKey))
            {
                partyKey = stateCode + Elections.GetNationalPartyCodeFromKey(electionKey);
            }

            Politicians.AddPolitician(newPoliticianKey, firstName, middleName, nickname,
                                      lastName, suffix, SafeGetOfficeKey(), partyKey, SecurePage.CreateUniquePassword());

            LogDataChange.LogInsert(Politicians.TableName, VotePage.UserName, SecurePage.UserSecurityClass,
                                    DateTime.UtcNow, newPoliticianKey);

            ClearAddNewCandidate();

            FeedbackAddNewCandidate.AddInfo("Politician " + formattedName + " was added.");
            if (Mode == DataMode.AddPoliticians)
            {
                FeedbackAddNewCandidate.AddInfo(new HtmlAnchor
                {
                    InnerText = "Intro Page",
                    HRef      = UrlManager.GetIntroPageUri(newPoliticianKey).ToString(),
                    Target    = "Politician"
                }.RenderToString());
                FeedbackAddNewCandidate.AddInfo(new HtmlAnchor
                {
                    InnerText = "Politician Admin Page",
                    HRef      = SecureAdminPage.GetPoliticianPageUrl(newPoliticianKey),
                    Target    = "Politician"
                }.RenderToString());
            }
        }