public DynamicControllerManager(HttpRequestBase request, ControllerManager controllerManager, IDynamicRepository dynamicRepository, UrlHelper urlHelper)
 {
     RequestManager = new RequestManager(request);
     DynamicEntitySearcher = new DynamicEntitySearcher(RequestManager);
     RequestManager.QueryStringDictionary = RequestManager.QueryStringDictionary.RouteValueDictionaryTypeCorrection(DynamicEntitySearcher.DynamicEntityMetadata);
     ControllerManager = controllerManager;
     DynamicRepository = dynamicRepository;
     UrlManager = new UrlManager(urlHelper);
     ReturnUrlCalculator = new ReturnUrlCalculator(UrlManager);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.IncludeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js");
            Page.IncludeJs(
                "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js");
            Page.IncludeJs("~/js/jq/jquery.cookie.js");
            Page.IncludeJs("~/js/jq/jquery.scrollintoview.js");
            Page.IncludeJs("~/js/vote.js");
            Page.IncludeJs("~/js/AddressEntry.js");
            Page.IncludeJs("~/js/json2.js");
            Page.IncludeCss("~/js/jq/jquery-ui.css");
            Page.IncludeCss("~/css/AddressEntry.css");

            var stateCode = DomainData.FromQueryStringOrDomain;

            MiniLogo.Src = DomainDesign.GetImageUri("smbanner.png")
                           .ToString();
            MiniLogo.Alt = UrlManager.GetDomainDesignCodeHostName(stateCode);

            //MiniLogo.Alt = "Vote-USA.org";

            StateCache.Populate(AddressEntryStatesDropDownList, "", "");
        }
Beispiel #3
0
        /// <summary>
        /// Main state machine for the application.
        ///
        /// Allow user to submit URL to be shortened or
        /// redirect user to long form URL if found.
        /// </summary>
        /// <param name="linkId">shortened URL code</param>
        /// <param name="longUrl">original URL submitted by user</param>
        public ActionResult Index(string linkId, string longUrl)
        {
            if (!string.IsNullOrEmpty(longUrl))
            {
                if (IsValidUrl(longUrl))
                {
                    return(SubmitUrl(longUrl));
                }
                else
                {
                    ViewBag.ErrorInvalidUrl = "Invalid URL! Please submit a different one.";
                    return(View());
                }
            }

            if (string.IsNullOrEmpty(linkId))
            {
                return(View());
            }
            else
            {
                string foundOrigUrl = UrlManager.GetUrlByEncodedId(linkId);

                if (string.IsNullOrEmpty(foundOrigUrl))
                {
                    ViewBag.ErrorInvalidShortCode = "Shortened URL not found. Please shorten another!";
                    return(View());
                }

                if (!foundOrigUrl.StartsWith("http://") && !foundOrigUrl.StartsWith("https://"))
                {
                    foundOrigUrl = "http://" + foundOrigUrl;
                }

                return(new RedirectResult(foundOrigUrl));
            }
        }
Beispiel #4
0
    private void SetCatagoryLink()
    {
        IList <string> categoryListID = CurrentBlog.BlogCategoryIDs;

        foreach (string id in categoryListID)
        {
            BlogCategory blogCategory = DataAccessContext.BlogCategoryRepository.GetOne(StoreContext.Culture, id);
            HyperLink    categoryLink = new HyperLink();
            categoryLink.ID          = "uxCategoryLink" + blogCategory.BlogCategoryID;
            categoryLink.CssClass    = "BlogDetailsDefaultTagsLink";
            categoryLink.Text        = blogCategory.Name;
            categoryLink.NavigateUrl = UrlManager.GetBlogCategoryUrl(blogCategory.UrlName);
            uxCategoryLinkPanel.Controls.Add(categoryLink);

            if (categoryListID[categoryListID.Count - 1] != id)
            {
                Label uxSeparater = new Label();
                uxSeparater.ID   = "uxSeparater";
                uxSeparater.Text = " , ";
                uxCategoryLinkPanel.Controls.Add(uxSeparater);
            }
        }
        uxCategoryPanel.Visible = true;
    }
Beispiel #5
0
    private void GetCatagoryList()
    {
        string[] categoryIDList = uxCategoryIDsHidden.Value.Split(',');

        foreach (string id in categoryIDList)
        {
            BlogCategory blogCategory = DataAccessContext.BlogCategoryRepository.GetOne(StoreContext.Culture, id);
            HyperLink    categoryLink = new HyperLink();
            categoryLink.ID          = "uxCategoryLink" + blogCategory.BlogCategoryID;
            categoryLink.CssClass    = "BlogDetailsDefaultTagsLink";
            categoryLink.Text        = blogCategory.Name;
            categoryLink.NavigateUrl = UrlManager.GetBlogCategoryUrl(blogCategory.UrlName);
            uxCategoryLinkPanel.Controls.Add(categoryLink);

            if (categoryIDList[categoryIDList.Length - 1] != id)
            {
                Label uxSeparater = new Label();
                uxSeparater.ID   = "uxCategorySeparater" + blogCategory.BlogCategoryID;
                uxSeparater.Text = " , ";
                uxCategoryLinkPanel.Controls.Add(uxSeparater);
            }
        }
        uxCategoryListPanel.Visible = true;
    }
Beispiel #6
0
        public BaseController(IUnitOfWorkAsync unitOfWorkAsync)
        {
            _unitOfWorkAsync = unitOfWorkAsync;

            _projectManager = new ProjectManager(unitOfWorkAsync);
            _fileManager    = new FileManager(unitOfWorkAsync);
            //_jobManager = new JobManager(unitOfWorkAsync);
            _wordManager = new WordManager(unitOfWorkAsync);
            //_workManager = new WorkManager(unitOfWorkAsync);
            //_imageManager = new ImageManager(unitOfWorkAsync);
            _answerManager   = new AnswerManager(unitOfWorkAsync);
            _urlManager      = new UrlManager(unitOfWorkAsync);
            _questionManager = new QuestionManager(unitOfWorkAsync);
            //_issueManager = new IssueManager(unitOfWorkAsync);
            _articleCategoryManager = new ArticleCategoryManager(unitOfWorkAsync);

            _commentService = new CommentService(unitOfWorkAsync.RepositoryAsync <CommentModel>());
            _commentManager = new CommentManager(_commentService, unitOfWorkAsync);

            //_articleService = new ArticleService(unitOfWorkAsync.RepositoryAsync<ArticleModel>());
            _articleManager = new ArticleManager(unitOfWorkAsync);

            _mapper = new Mappers.Mappers(_unitOfWorkAsync);
        }
Beispiel #7
0
 public UrlController(UrlManager urlManager)
 {
     this._urlManager = urlManager;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            SimpleCsvWriter csvWriter;
            StreamWriter    streamWriter;

            void FillDataRows(IList <int> candidates, IList <int> offices, int ballotMeasures,
                              string description = null)
            {
                if (_HasElections)
                {
                    csvWriter.AddField(description.SafeString());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.President].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.President].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.USSenate].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.USSenate].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.USHouse].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.USHouse].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.Governor].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.Governor].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.StateExecutive].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.StateExecutive].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.StateSenate].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.StateSenate].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.StateHouse].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.StateHouse].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.County].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.County].BlankIfZero());
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(offices[(int)OfficeHeading.Local].BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(candidates[(int)OfficeHeading.Local].BlankIfZero());
                }

                if (_HasBallotMeasures)
                {
                    csvWriter.AddField(ballotMeasures.BlankIfZero());
                }

                var allOffices    = 0;
                var allCandidates = 0;

                for (var o = OfficeHeading.President; o < OfficeHeading.Count; o++)
                {
                    allOffices    += offices[(int)o];
                    allCandidates += candidates[(int)o];
                }

                if (_HasOffices)
                {
                    csvWriter.AddField(allOffices.BlankIfZero());
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField(allCandidates.BlankIfZero());
                }

                csvWriter.Write(streamWriter);
            }

            bool IsBallotMeasure(DataRow r)
            {
                return(r.ReferendumKey() != null);
            }

            if (!DateTime.TryParse(Request.QueryString["from"], out var fromDate))
            {
                fromDate = DateTime.MinValue;
            }
            if (!DateTime.TryParse(Request.QueryString["to"], out var toDate))
            {
                toDate = DateTime.MaxValue;
            }
            var reportType = Request.QueryString["type"].SafeString();

            _HasCandidates     = reportType.Contains("C");
            _HasOffices        = reportType.Contains("O");
            _HasBallotMeasures = reportType.Contains("B");
            _HasElections      = Request.QueryString["detail"] == "E";

            for (var i = 0; i < (int)OfficeHeading.Count; i++)
            {
                _ElectionOffices[i] = new List <string>();
            }

            // get data table from database
            var table = ElectionsPoliticians.GetOfficesAndCandidatesReportData(fromDate, toDate, 0)
                        .Rows.OfType <DataRow>().ToList();

            // create dummy entries so months with no elections will show
            var lowDate = fromDate == DateTime.MinValue
        ? table.Min(r => r.ElectionDate())
        : fromDate;
            var highDate = toDate == DateTime.MaxValue
        ? table.Max(r => r.ElectionDate())
        : toDate;
            var monthList = new List <DateTime>();

            while (lowDate <= highDate)
            {
                monthList.Add(lowDate);
                lowDate = lowDate.AddMonths(1);
            }

            var dummies = monthList.Select(m => new
            {
                row           = (DataRow)null,
                MonthYear     = m.ToString("yyyyMM"),
                MonthYearDesc = m.ToString("MMM yyyy"),
                Year          = m.ToString("yyyy"),
                OfficeHeading = OfficeHeading.Other
            }).ToList();

            var data = table
                       .Select(r => new
            {
                row           = r,
                MonthYear     = r.ElectionDate().ToString("yyyyMM"),
                MonthYearDesc = r.ElectionDate().ToString("MMM yyyy"),
                Year          = r.ElectionDate().ToString("yyyy"),
                OfficeHeading = GetOfficeHeading(r.OfficeClass(), r.AlternateOfficeClass())
            })
                       .Union(dummies)
                       .GroupBy(r => r.row == null ? r.MonthYear : r.row.ElectionKeyState())
                       .GroupBy(el => el.First().MonthYear)
                       .OrderBy(g => g.Key)
                       .GroupBy(m => m.First().First().Year)
                       .ToList();

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

                // write CSV headings
                csvWriter.AddField("Date");
                if (_HasElections)
                {
                    csvWriter.AddField("Election Title");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("President Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("President Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("US Senate Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("US Senate Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("US House Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("US House Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("Governor Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("Governor Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("State Executive Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("State Executive Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("State Senate Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("State Senate Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("State House Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("State House Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("Countywide Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("Countywide Candidates");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("Local Offices");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("Local Candidates");
                }
                if (_HasBallotMeasures)
                {
                    csvWriter.AddField("Ballot Measures");
                }
                if (_HasOffices)
                {
                    csvWriter.AddField("TOTAL OFFICES");
                }
                if (_HasCandidates)
                {
                    csvWriter.AddField("TOTAL CANDIDATES");
                }
                csvWriter.Write(streamWriter);

                foreach (var year in data)
                {
                    foreach (var monthYear in year)
                    {
                        foreach (var election in monthYear)
                        {
                            for (var i = 0; i < _ElectionOfficeCount.Length; i++)
                            {
                                _ElectionOffices[i].Clear();
                            }
                            foreach (var candidate in election)
                            {
                                if (candidate.row != null)
                                {
                                    if (IsBallotMeasure(candidate.row))
                                    {
                                        _ElectionBallotMeasures++;
                                    }
                                    else
                                    {
                                        _ElectionCandidates[(int)candidate.OfficeHeading]++;
                                        _ElectionOffices[(int)candidate.OfficeHeading].Add(candidate.row.OfficeKey());
                                    }
                                }
                            }
                            for (var i = 0; i < _ElectionOfficeCount.Length; i++)
                            {
                                _ElectionOfficeCount[i] = _ElectionOffices[i].Distinct().Count();
                            }
                            if (_HasElections)
                            {
                                var row = election.First().row;
                                if (row != null)
                                {
                                    csvWriter.AddField(row.ElectionDate().ToString("M/d/yyyy"));
                                    var desc =
                                        $"=HYPERLINK(\"{UrlManager.GetAdminUri(GetAdminFolderPageUrl("election", "election", row.ElectionKeyState(), "complete", "1"))}\",\"{row.ElectionDescription()}\")";
                                    FillDataRows(_ElectionCandidates, _ElectionOfficeCount, _ElectionBallotMeasures,
                                                 desc);
                                }
                            }
                            RollCounters(_ElectionCandidates, _MonthCandidates);
                            RollCounters(_ElectionOfficeCount, _MonthOfficeCount);
                            RollBallotMeasures(ref _ElectionBallotMeasures, ref _MonthBallotMeasures);
                        }
                        csvWriter.AddField($"Total {monthYear.First().First().MonthYearDesc}");
                        FillDataRows(_MonthCandidates, _MonthOfficeCount, _MonthBallotMeasures);
                        RollCounters(_MonthCandidates, _YearCandidates);
                        RollCounters(_MonthOfficeCount, _YearOfficeCount);
                        RollBallotMeasures(ref _MonthBallotMeasures, ref _YearBallotMeasures);
                    }
                    csvWriter.Write(streamWriter);
                    csvWriter.AddField($"TOTAL YEAR {year.First().First().First().Year}");
                    FillDataRows(_YearCandidates, _YearOfficeCount, _YearBallotMeasures);
                    RollCounters(_YearCandidates, _ReportCandidates);
                    RollCounters(_YearOfficeCount, _ReportOfficeCount);
                    RollBallotMeasures(ref _YearBallotMeasures, ref _ReportBallotMeasures);
                    csvWriter.Write(streamWriter);
                }
                csvWriter.AddField("REPORT TOTAL");
                FillDataRows(_ReportCandidates, _ReportOfficeCount, _ReportBallotMeasures);

                streamWriter.Flush();
                ms.Position = 0;
                var csv = new StreamReader(ms).ReadToEnd();

                var reportDesc = String.Empty;
                if (_HasOffices)
                {
                    if (_HasCandidates)
                    {
                        reportDesc += "Offices & Candidates";
                    }
                    else
                    {
                        reportDesc += "Offices";
                    }
                }
                else if (_HasCandidates)
                {
                    reportDesc += "Candidates";
                }
                else if (_HasBallotMeasures)
                {
                    reportDesc += "Ballot Measures";
                }
                reportDesc += " in Elections";
                if (fromDate != DateTime.MinValue)
                {
                    if (toDate != DateTime.MaxValue)
                    {
                        reportDesc += $" {fromDate:M-d-yyyy} to {toDate:M-d-yyyy}";
                    }
                    else
                    {
                        reportDesc += $" after {fromDate:M-d-yyyy}";
                    }
                }
                else if (toDate != DateTime.MaxValue)
                {
                    reportDesc += $" before {toDate:M-d-yyyy}";
                }
                if (_HasElections)
                {
                    reportDesc += " with election detail";
                }

                // download
                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition",
                                   $"attachment;filename=\"{reportDesc}.csv\"");
                Response.Write("\xfeff"); // BOM
                Response.Write(csv);
                Response.End();
            }
        }
        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();
        }
Beispiel #10
0
 public static void Start()
 {
     UrlManager <AppUrls> .Initialize();
 }
Beispiel #11
0
 private void Page_Load(object sender, System.EventArgs e)
 {
     Response.RedirectPermanent(
         UrlManager.GetForResearchPageUri(
             DomainData.FromQueryStringOrDomain).ToString(), true);
 }
Beispiel #12
0
 public MainActivity()
 {
     _fetch = new FetchManager();
     _url   = new UrlManager();
 }
Beispiel #13
0
 protected string GetBlogUrl(object blogID, object urlName)
 {
     return(UrlManager.GetBlogUrl(blogID, urlName));
 }
    protected string GetURL(object dataItem)
    {
        Category category = (Category)dataItem;

        return(UrlManager.GetCategoryUrl(category.CategoryID, category.UrlName));
    }
Beispiel #15
0
        public static ISpecificHandler getHandler(WebContext context)
        {
            if (context.httprequest.Path.ToLower().StartsWith("/do/"))
            {
                string action = context.httprequest.Path.ToLower().Substring(4).Trim('/');
                if (action.StartsWith("markthreadasread"))
                {
                    return(new handlers.request.MarkThreadAsReadHandler());
                }
                switch (action)
                {
                case "login":
                    return(new handlers.request.LoginHandler());

                case "logout":
                    return(new handlers.request.LogoutHandler());

                case "migrateaccount":
                    return(new handlers.request.MigrateAccountHandler());

                case "register":
                    return(new handlers.request.RegisterHandler());

                case "registerbyinvite":
                    return(new handlers.request.RegisterByInviteHandler());

                case "edit":
                    return(new handlers.request.EditHandler());

                case "punish":
                    return(new handlers.request.PunishHandler());

                case "reply":
                    return(new handlers.request.ReplyHandler());

                case "newthread":
                    return(new handlers.request.CreateThreadHandler());

                case "settings":
                    return(new handlers.request.SettingsHandler());

                case "userdata":
                    return(new handlers.request.UserDataHandler());

                case "sendpm":
                    return(new handlers.request.SendPMHandler());

                case "upload":
                    return(new handlers.request.UploadHandler());

                case "newpoll":
                    return(new handlers.request.CreatePollHandler());

                case "vote":
                    return(new handlers.request.VoteHandler());

                case "avatars/add":
                    return(new handlers.request.avatars.AddHandler());

                case "avatars/remove":
                    return(new handlers.request.avatars.RemoveHandler());

                case "avatars/setasdefault":
                    return(new handlers.request.avatars.SetAsDefaultHandler());

                case "maintenance/cleancache":
                    return(new handlers.request.maintenance.CleanCacheHandler());

                default:
                    return(new handlers.WrongUrlHandler());
                }
            }

            AbstractUrl url = UrlManager.Parse(context.httprequest.Path, context.httprequest.QueryString, context.account != null);

            if (url == null)
            {
                return(new handlers.WrongUrlHandler());
            }

            if (!context.httprequest.Path.StartsWith(url.canonical))
            {
                //throw new ApplicationException("Going to redirect to: '" + url.canonicalFull + "' (canonical='" + url.canonicalFull + "')");
                throw new RedirectException(url.canonicalFull);
            }

            return(handlersDictionary[url.GetType()](url));
        }
 public ActionResult GoBack()
 {
     UrlManager.IsReturning = true;
     return(Redirect(UrlManager.PopUrl()));
 }
Beispiel #17
0
 protected string GetNewsUrl(object newsID, object urlName)
 {
     return(UrlManager.GetNewsUrl(newsID, urlName));
 }
 protected void uxTellFriendLinkButton_Click(object sender, EventArgs e)
 {
     Response.Redirect(UrlManager.GetTellFriendMobileUrl(CurrentProduct.ProductID, CurrentProduct.UrlName));
 }
Beispiel #19
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());
            }
        }
Beispiel #20
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();
        }
Beispiel #21
0
 public string GetUrl(object id, object url)
 {
     return(Page.ResolveUrl(UrlManager.GetProductUrl(id.ToString(), url.ToString())));
 }
Beispiel #22
0
    protected string GetURL(object cartItem)
    {
        Product product = ((ICartItem)cartItem).Product;

        return(UrlManager.GetMobileProductUrl(product.ProductID, product.Locales[StoreContext.Culture].UrlName));
    }
    public void Show(Product product, int quantity, decimal customPrice, CartItemGiftDetails giftDetails, OptionItemValueCollection selectedOptions, ProductKitItemValueCollection productKitItemCollection)
    {
        ProductImage image = product.GetPrimaryProductImage();

        uxProductImage.ImageUrl       = "~/" + image.RegularImage;
        uxProductNameLink.NavigateUrl = UrlManager.GetProductUrl(product.ProductID, product.Locales[StoreContext.Culture].UrlName);
        uxProductNameLink.Text        = "<div class='ProductName'>" + product.Name + "</div>";
        uxQuantityLabel.Text          = quantity.ToString();
        decimal productPrice = product.GetDisplayedPrice(StoreContext.WholesaleStatus);


        if (product.IsCustomPrice)
        {
            productPrice = customPrice;
        }

        if (product.IsGiftCertificate && !product.IsFixedPrice)
        {
            productPrice = giftDetails.GiftValue;
        }

        if (productKitItemCollection.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            foreach (OptionItemValue optionItemValue in selectedOptions)
            {
                sb.Append("<div class='OptionName'>");
                sb.Append(optionItemValue.GetDisplayedName(StoreContext.Culture, StoreContext.Currency));
                sb.Append("</div>");
            }

            if ((!productKitItemCollection.IsNull) && (productKitItemCollection.Count > 0))
            {
                sb.Append("<div class='OptionName'>");
                sb.Append("Items:");
                sb.Append("</div>");
            }

            foreach (ProductKitItemValue value in productKitItemCollection)
            {
                sb.Append("<div class='OptionName'>");
                sb.Append("- " + value.GetGroupName(StoreContext.Culture, StoreContext.CurrentStore.StoreID) + ":" + value.GetDisplayedName(StoreContext.Culture, StoreContext.CurrentStore.StoreID));
                sb.Append("</div>");
            }

            uxProductNameLink.Text = uxProductNameLink.Text + sb.ToString();
        }
        else
        {
            if (selectedOptions.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (OptionItemValue optionItemValue in selectedOptions)
                {
                    sb.Append("<div class='OptionName'>");
                    sb.Append(optionItemValue.GetDisplayedName(StoreContext.Culture, StoreContext.Currency));
                    sb.Append("</div>");

                    productPrice += optionItemValue.OptionItem.PriceToAdd;
                }

                uxProductNameLink.Text = uxProductNameLink.Text + sb.ToString();
            }
        }

        uxPriceLabel.Text = StoreContext.Currency.FormatPrice(productPrice);
        uxMessage.Text    = product.Name + "[$AddSuccess]";
        uxAddToCartPopup.Show();
    }
Beispiel #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.NoHeading        = true;
            MainBannerHomeLink.HRef = UrlManager.GetSiteUri().ToString();
            Title = "Vote-USA - Manage Issue Responses";

            if (UserSecurityClass != PoliticianSecurityClass)
            {
                var mainContent = Master.MainContentControl;
                mainContent.Controls.Clear();
                new HtmlP
                {
                    InnerText = "This page is only available to signed-in candidates"
                }.AddTo(mainContent, "user-error");
                return;
            }

            PoliticianName.InnerText = base.PoliticianName;
            var issuesAndTopics = Questions2.GetIssuesAndTopics();

            // prune to match the politician
            var liveOfficeKey  = Politicians.GetLiveOfficeKey(PoliticianKey, Empty);
            var electoralClass = Offices.GetElectoralClass(Offices.GetOfficeClass(liveOfficeKey));
            var stateCode      = Offices.GetStateCodeFromKey(liveOfficeKey);
            var issueLevel     = Empty;
            var countyOrLocal  = Empty;

            switch (electoralClass)
            {
            case ElectoralClass.USPresident:
            case ElectoralClass.USSenate:
            case ElectoralClass.USHouse:
                issueLevel = "B";
                break;

            case ElectoralClass.USGovernors:
            case ElectoralClass.State:
                issueLevel = "C";
                break;

            case ElectoralClass.County:
                issueLevel    = "D";
                countyOrLocal = Offices.GetCountyCodeFromKey(liveOfficeKey);
                break;

            case ElectoralClass.Local:
                issueLevel    = "E";
                countyOrLocal = Offices.GetLocalKeyFromKey(liveOfficeKey);
                break;
            }

            foreach (var issue in issuesAndTopics)
            {
                foreach (var topic in issue.Questions)
                {
                    if (topic.Jurisdictions.Any(j => j.IssueLevel == "A"))
                    {
                        topic.Pruned = false;
                    }
                    else
                    {
                        switch (issueLevel)
                        {
                        case "B":
                            topic.Pruned = topic.Jurisdictions.All(j => j.IssueLevel != "B");
                            break;

                        case "C":
                            topic.Pruned = !topic.Jurisdictions.Any(j => j.IssueLevel == "C" &&
                                                                    (j.StateCode == Empty || j.StateCode == stateCode));
                            break;

                        case "D":
                            topic.Pruned = !topic.Jurisdictions.Any(j => j.IssueLevel == "D" &&
                                                                    (j.StateCode == Empty || j.StateCode == stateCode &&
                                                                     (j.CountyOrLocal == Empty || j.CountyOrLocal == countyOrLocal)));
                            break;

                        case "E":
                            topic.Pruned = !topic.Jurisdictions.Any(j => j.IssueLevel == "E" &&
                                                                    (j.StateCode == Empty || j.StateCode == stateCode &&
                                                                     (j.CountyOrLocal == Empty || j.CountyOrLocal == countyOrLocal)));
                            break;

                        default:
                            topic.Pruned = true;
                            break;
                        }
                    }
                }

                issue.Pruned = issue.Questions.All(q => q.Pruned);
            }

            var prunedIssuesAndTopics = issuesAndTopics.Where(i => !i.Pruned)
                                        .Select(i => new IssuesAndTopicsPrunedIssue
            {
                I     = i.IssueId,
                Issue = i.Issue,
                Q     = i.Questions.Where(q => !q.Pruned).Select(q => new IssuesAndTopicsPrunedQuestion
                {
                    I = q.QuestionId,
                    Q = q.Question
                }).ToList()
            }).ToList();


            // load the topics
            var options = prunedIssuesAndTopics.Select(i =>
                                                       $"<option value=\"{i.I}\">{i.Issue}</option>");

            IssuesSelectOptions.Text = "<option value=\"\">&lt; select an issue &gt;</option>" +
                                       Join(Empty, options);

            // second pruning to reduce bandwidth
            var rePrunedIssuesAndTopics = prunedIssuesAndTopics
                                          .Select(i => new IssuesAndTopicsRePrunedIssue
            {
                I = i.I,
                Q = i.Q
            }).ToList();

            // make data available client side
            var body = Master.FindControl("body") as HtmlGenericControl;
            var json = new JavaScriptSerializer();

            // ReSharper disable once PossibleNullReferenceException
            body.Attributes.Add("data-issues-and-topics", json.Serialize(rePrunedIssuesAndTopics));
            body.Attributes.Add("data-politician-key", PoliticianKey);
        }
        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();
        }
    protected void uxAddToCartImageButton_Command(object sender, CommandEventArgs e)
    {
        string productID = e.CommandArgument.ToString();
        string urlName   = e.CommandName.ToString();

        Product product = DataAccessContext.ProductRepository.GetOne(
            StoreContext.Culture,
            productID, new StoreRetriever().GetCurrentStoreID());

        ProductSubscription subscriptionItem = new ProductSubscription(product.ProductID);

        if (subscriptionItem.IsSubscriptionProduct())
        {
            if (StoreContext.Customer.IsNull)
            {
                string returnUrl = "AddtoCart.aspx?ProductID=" + product.ProductID;
                Response.Redirect("~/UserLogin.aspx?ReturnUrl=" + returnUrl);
            }
        }

        if (!StoreContext.ShoppingCart.CheckCanAddItemToCart(product))
        {
            Response.Redirect("AddShoppingCartNotComplete.aspx?ProductID=" + product.ProductID);
        }

        if (StoreContext.CheckoutDetails.ContainsGiftRegistry())
        {
            Response.Redirect("AddShoppingCartNotComplete.aspx");
        }
        else
        {
            if ((DataAccessContext.OptionGroupRepository.ProductIsOptionGroup(StoreContext.Culture, productID)) || (product.IsProductKit))
            {
                Response.Redirect(UrlManager.GetProductUrl(productID, urlName));
            }
            else
            {
                if ((IsPhysicalGiftCertificate(product) || !product.IsFixedPrice || product.RequiresUserInput() || product.IsCustomPrice))
                {
                    Response.Redirect(UrlManager.GetProductUrl(productID, urlName));
                }
                else
                {
                    StoreContext.ShoppingCart.AddItem(product, product.MinQuantity);

                    bool enableNotification = ConvertUtilities.ToBoolean(DataAccessContext.Configurations.GetValue("EnableAddToCartNotification", StoreContext.CurrentStore));
                    if (UrlManager.IsMobileClient())
                    {
                        enableNotification = false;
                    }
                    if (enableNotification)
                    {
                        uxAddToCartNotification.Show(product, product.MinQuantity);
                    }
                    else
                    {
                        Response.Redirect("ShoppingCart.aspx");
                    }
                }
            }
        }
    }
Beispiel #27
0
    protected void uxAddToCartButton_Click(object sender, EventArgs e)
    {
        PromotionSelected promotion = new PromotionSelected(StoreContext.Culture, new StoreRetriever().GetCurrentStoreID());

        promotion.SetPromotionGroupID = PromotionGroupID;
        bool isSuccess = true;

        foreach (DataListItem item in uxList.Items)
        {
            if (item.FindControl("uxGroup") != null)
            {
                Components_PromotionProductGroup group = (Components_PromotionProductGroup)item.FindControl("uxGroup");
                if (group.IsSelectedProduct)
                {
                    string   productGroup = group.GetSelectedOption;
                    string[] groupInfo    = productGroup.Split(':');

                    IList <string> options = new List <string>();
                    foreach (string option in groupInfo[1].Split(','))
                    {
                        if (option.Trim() == "")
                        {
                            continue;
                        }
                        options.Add(option);
                    }
                    Product product = DataAccessContext.ProductRepository.GetOne(StoreContext.Culture, groupInfo[0], new StoreRetriever().GetCurrentStoreID());
                    promotion.AddSelectedPromotionItem(group.PromotionSubGroupID, product, options);
                }
                else
                {
                    isSuccess = false;
                }
            }
        }
        if (!isSuccess)
        {
            return;
        }

        // Check Inventory
        isSuccess = CheckOutOfStock(promotion.PromotionSelectedItems);
        if (!isSuccess)
        {
            Response.Redirect("AddShoppingCartNotComplete.aspx?ProductID=0&PromotionStock=1");
        }
        // Check Free Shipping
        isSuccess = CartItemPromotion.CheckCanAddItemToCart(StoreContext.ShoppingCart, promotion);
        if (isSuccess)
        {
            PromotionSelected.AddPromotionItem(StoreContext.ShoppingCart, promotion, 1);

            bool enableNotification = ConvertUtilities.ToBoolean(DataAccessContext.Configurations.GetValue("EnableAddToCartNotification", StoreContext.CurrentStore));
            if (UrlManager.IsMobileDevice(Request))
            {
                enableNotification = false;
            }
            if (enableNotification)
            {
                uxAddToCartNotification.Show(promotion, 1);
            }
            else
            {
                Response.Redirect("ShoppingCart.aspx");
            }
        }
        else
        {
            Response.Redirect("AddShoppingCartNotComplete.aspx?ProductID=0&FreeShiping=1");
        }
    }
        override protected IEnumerable <XElement> getSpecificData(WebContext context)
        {
            PageOuter             pageOuter = PageOuter.createUnlimited(context.userSettings.usersPerPage);
            IEnumerable <Session> sessions  =
                from stringId in Config.instance.mainConnection.LoadIdsByConditions(
                    Session.TableSpec.instance,
                    new ComplexCondition(
                        ConditionsJoinType.AND,
                        new ComparisonCondition(
                            Session.TableSpec.instance.getColumnSpec(Session.TableSpec.FIELD_LASTHUMANACTIVITY),
                            Web.Core.DB.conditions.ComparisonType.GREATEROREQUAL,
                            DateTime.Now.Subtract(Config.instance.ActivityThreshold).ToUTCString()
                            ),
                        new     ComparisonCondition(
                            Session.TableSpec.instance.getColumnSpec(Session.TableSpec.FIELD_ISDELETED),
                            Web.Core.DB.conditions.ComparisonType.EQUAL,
                            "0"
                            )
                        ),
                    pageOuter,
                    new JoinSpec[0],
                    new SortSpec[] {
                new SortSpec(
                    Session.TableSpec.instance.getColumnSpec(Session.TableSpec.FIELD_LASTHUMANACTIVITY),
                    false
                    ),
            }
                    ) select Session.LoadByKey(stringId);

            return(new XElement[] {
                new XElement("users",
                             from session in sessions
                             let account = session.account
                                           where !account.isStatusHidden
                                           select account.user.exportToXmlForViewing(
                                 context,
                                 new XElement("lastActivity", session.lastHumanActivity.ToXml()),
                                 !account.isDetailedStatusHidden ? new XElement("lastUrl", new XElement("url", session.lastUrl), new XElement("title", UrlManager.TryGetTitle(session.lastUrl))) : null
                                 )
                             )
            });
        }
Beispiel #29
0
    private void GenerateBreadcrumb(DataListItem item)
    {
        Panel  panel               = (Panel)item.FindControl("uxBreadcrumbPanel");
        string name                = DataBinder.Eval(item.DataItem, "Name").ToString();
        string contentMenuItemID   = DataBinder.Eval(item.DataItem, "ContentMenuItemID").ToString();
        string urlName             = DataBinder.Eval(item.DataItem, "UrlName").ToString();
        string parentContentMenuID = DataBinder.Eval(item.DataItem, "ContentMenuID").ToString();

        HyperLink link = new HyperLink();

        if (contentMenuItemID != "0")
        {
            ContentMenuItem currntItem = DataAccessContext.ContentMenuItemRepository.GetOne(
                StoreContext.Culture, contentMenuItemID);
            IList <ContentMenuItem> parentList = new List <ContentMenuItem>();

            if (currntItem.MenuPosition == ContentMenuItem.MenuPositionType.Root)
            {
                parentList.Add(currntItem);
                link      = new HyperLink();
                link.Text = parentList[0].Name;
                //link.Text = "Information";
                link.CssClass = "SiteMapParent";
                panel.Controls.Add(link);

                if (!currntItem.LinksToContent())
                {
                    link.NavigateUrl = UrlManager.GetContentMenuUrl(contentMenuItemID, urlName);
                }
                else
                {
                    Vevo.Domain.Contents.Content content = DataAccessContext.ContentRepository.GetOne(
                        StoreContext.Culture, currntItem.ContentID.ToString());
                    link.NavigateUrl = UrlManager.GetContentUrl(content.ContentID, content.UrlName);
                }
            }
            else
            {
                parentList    = currntItem.GetParentMenuItemList(StoreContext.Culture);
                link          = new HyperLink();
                link.Text     = parentList[0].Name;
                link.CssClass = "SiteMapParent";


                if (!currntItem.LinksToContent())
                {
                    link.NavigateUrl = UrlManager.GetContentMenuUrl(contentMenuItemID, urlName);
                }
                else
                {
                    Vevo.Domain.Contents.Content content = DataAccessContext.ContentRepository.GetOne(
                        StoreContext.Culture, currntItem.ContentID.ToString());
                    link.NavigateUrl = UrlManager.GetContentUrl(content.ContentID, content.UrlName);
                }

                panel.Controls.Add(link);

                for (int i = 1; i < parentList.Count; i++)
                {
                    Label label = new Label();
                    label.Text     = " >> ";
                    label.CssClass = "SiteMapSeparate";
                    panel.Controls.Add(label);

                    link             = new HyperLink();
                    link.Text        = parentList[i].Name;
                    link.CssClass    = "SiteMapParent";
                    link.NavigateUrl = UrlManager.GetContentMenuUrl(
                        parentList[i].ContentMenuItemID, parentList[i].UrlName);

                    panel.Controls.Add(link);
                }
            }
        }
        else
        {
            link          = new HyperLink();
            link.Text     = name;
            link.CssClass = "SiteMapParent";
            panel.Controls.Add(link);
        }
        GenerateContent(item, contentMenuItemID);
    }
Beispiel #30
0
        public JsonResult NewsSave(Models.NewsSave model = null)
        {
            var answer = JsonAnswer <int>();

            try
            {
                if (ModelState.IsValid)
                {
                    using (var db = new DB.DataLayerContext())
                    {
                        DB.News data = null;
                        if (model.IdMaterial <= 0)
                        {
                            data = new DB.News()
                            {
                                date = DateTime.Now, user = AppCore.GetUserContextManager().GetCurrentUserContext().IdUser, status = true, Block = false
                            };
                            db.News.Add(data);
                        }
                        else
                        {
                            data = db.News.Where(x => x.id == model.IdMaterial).FirstOrDefault();
                            if (data == null)
                            {
                                throw new Exception("Указанная новость не найдена.");
                            }

                            if (data.Block)
                            {
                                if (AppCore.GetUserContextManager().GetCurrentUserContext().IsSuperuser)
                                {
                                    throw new Exception("Указанная новость удалена (сообщение для суперпользователя).");
                                }
                                else
                                {
                                    throw new Exception("Указанная новость не найдена.");
                                }
                            }
                        }

                        data.name       = model.NameMaterial;
                        data.text       = model.BodyFull;
                        data.short_text = model.BodyShort;

                        db.SaveChanges();

                        answer.Data = data.id;

                        var result = AppCore.Get <UrlManager>().Register(
                            Module,
                            data.id,
                            ItemTypeFactory.GetItemType(typeof(DB.News)).IdItemType,
                            nameof(ModuleController.ViewNews),
                            new List <ActionArgument>()
                        {
                            new ActionArgument()
                            {
                                ArgumentName = "IdNews", ArgumentValue = data.id
                            }
                        },
                            "news/" + UrlManager.Translate(data.name),
                            RoutingConstants.MAINKEY
                            );
                        if (!result.IsSuccess)
                        {
                            throw new Exception(result.Message);
                        }

                        answer.FromSuccess("Новость сохранена");
                    }
                }
            }
            catch (Exception ex)
            {
                answer.FromException(ex);
                Module.RegisterEvent(EventType.Error, "Ошибка сохранения новости", "Модель данных, переданная из формы:\r\n" + Newtonsoft.Json.JsonConvert.SerializeObject(model), null, ex);
            }

            return(ReturnJson(answer));
        }
Beispiel #31
0
 public static string GetUrlCommand(string page)
 {
     return(UrlManager.getURL(page));
 }