Exemple #1
0
        private async Task <bool> DeleteCoreAsync <T>(string href, CancellationToken cancellationToken)
            where T : IResource
        {
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException(nameof(href));
            }

            var uri = new CanonicalUri(this.uriQualifier.EnsureFullyQualified(href));

            this.logger.Trace($"Asynchronously deleting resource {uri.ToString()}", "DefaultDataStore.DeleteCoreAsync");

            IAsynchronousFilterChain chain = new DefaultAsynchronousFilterChain(this.defaultAsyncFilters as DefaultAsynchronousFilterChain)
                                             .Add(new DefaultAsynchronousFilter(async(req, next, logger, ct) =>
            {
                var httpRequest = new DefaultHttpRequest(HttpMethod.Delete, req.Uri);
                var response    = await this.ExecuteAsync(httpRequest, ct).ConfigureAwait(false);

                return(new DefaultResourceDataResult(req.Action, typeof(T), req.Uri, response.StatusCode, body: null));
            }));

            var request = new DefaultResourceDataRequest(ResourceAction.Delete, typeof(T), uri, false);
            var result  = await chain.FilterAsync(request, this.logger, cancellationToken).ConfigureAwait(false);

            bool successfullyDeleted = result.HttpStatus == 204;

            return(successfullyDeleted);
        }
 public void Throws_when_URI_is_empty()
 {
     Should.Throw <ArgumentNullException>(() =>
     {
         var bad = new CanonicalUri(string.Empty);
     });
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.IncludeJs("~/js/ballot.js");

            _ElectionDescription = PageCache.Elections.GetElectionDesc(_ElectionKey);
            Title = Format(TitleTag, GetMetaTitle(), PublicMasterPage.SiteName);

            OgUrl.Attributes.Add("content", CanonicalUri.ToString());
            OgTitle.Attributes.Add("content", $"My choices for {_ElectionDescription}");
            OgDescription.Attributes.Add("content", "View the candidates I plan to vote for.");

            OgImage.Attributes.Add("content",
                                   UrlManager.GetSiteUri("/images/designs/Vote-USA/fbbanner2.png").ToString());
            OgImageWidth.Attributes.Add("content", "250");
            OgImageHeight.Attributes.Add("content", "250");

            try
            {
                var metaContent = GetMetaTitle();
                MetaDescription = metaContent;
                MetaKeywords    = metaContent;

                BallotReportResponsive.GetReport(QueryElection, QueryCongress, QueryStateSenate,
                                                 QueryStateHouse, QueryCounty, QueryDistrict, QueryPlace, QueryElementary,
                                                 QuerySecondary, QueryUnified, QueryCityCouncil, QueryCountySupervisors,
                                                 QuerySchoolDistrictDistrict, out var officeContests).AddTo(ReportPlaceHolder);
                var ballotMeasures = BallotReferendumReportResponsive.GetReport(QueryElection, QueryCounty,
                                                                                QueryDistrict, QueryPlace, QueryElementary, QuerySecondary, QueryUnified,
                                                                                QueryCityCouncil, QueryCountySupervisors, QuerySchoolDistrictDistrict)
                                     .AddTo(ReferendumReportPlaceHolder);
                ballotMeasures.AddTo(ReferendumReportPlaceHolder);
                CreateHeading(officeContests.Count, ballotMeasures.Controls.Count > 0);

                // tag body with key for persistent selections
                var body             = Master.FindControl("Body") as HtmlGenericControl;
                var stateElectionKey = Elections.GetStateElectionKeyFromKey(QueryElection)
                                       .ToUpperInvariant();
                // ReSharper disable once PossibleNullReferenceException
                body.Attributes.Add("data-election", stateElectionKey);
                var electionDate = DateTime.ParseExact(Elections.GetElectionDateStringFromKey(stateElectionKey), "yyyyMMdd",
                                                       CultureInfo.InvariantCulture);
                //var showAd = electionDate.AddDays(1) > DateTime.Today;
                var showAd = true;
                body.Attributes.Add("data-ad", showAd ? "Y" : "N");

                // for a single contest election we add a special class and also include the candidate comparison info
                if (officeContests.Count == 1 && ballotMeasures.Controls.Count == 0)
                {
                    body.AddCssClasses("single-contest");
                    body.Attributes.Add("data-adelection", QueryElection);
                    body.Attributes.Add("data-adoffice", officeContests[0]);
                    CompareCandidatesReportResponsive.GetReport(_ElectionKey, officeContests[0], true)
                    .AddTo(ReportPlaceHolder);
                }
            }
            catch (Exception /*ex*/)
            {
                // ignored
            }
        }
Exemple #4
0
        private IResourceDataResult GetResourceData <T>(string href, bool skipCache)
        {
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException(nameof(href));
            }

            var canonicalUri = new CanonicalUri(this.uriQualifier.EnsureFullyQualified(href));

            this.logger.Trace($"Synchronously getting resource type {typeof(T).Name} from: {canonicalUri.ToString()}", "DefaultDataStore.GetResource<T>");

            ISynchronousFilterChain chain = new DefaultSynchronousFilterChain(this.defaultSyncFilters as DefaultSynchronousFilterChain)
                                            .Add(new DefaultSynchronousFilter((req, next, logger) =>
            {
                var httpRequest = new DefaultHttpRequest(HttpMethod.Get, req.Uri);

                var response = this.Execute(httpRequest);
                var body     = this.GetBody <T>(response);

                return(new DefaultResourceDataResult(req.Action, typeof(T), req.Uri, response.StatusCode, body));
            }));

            var request = new DefaultResourceDataRequest(ResourceAction.Read, typeof(T), canonicalUri, skipCache);

            return(chain.Filter(request, this.logger));
        }
Exemple #5
0
        private Task <IResourceDataResult> GetResourceDataAsync <T>(string href, bool skipCache, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException(nameof(href));
            }

            var canonicalUri = new CanonicalUri(this.uriQualifier.EnsureFullyQualified(href));

            this.logger.Trace($"Asynchronously getting resource type {typeof(T).Name} from: {canonicalUri.ToString()}", "DefaultDataStore.GetResourceAsync<T>");

            IAsynchronousFilterChain chain = new DefaultAsynchronousFilterChain(this.defaultAsyncFilters as DefaultAsynchronousFilterChain)
                                             .Add(new DefaultAsynchronousFilter(async(req, next, logger, ct) =>
            {
                var httpRequest = new DefaultHttpRequest(HttpMethod.Get, req.Uri);

                var response = await this.ExecuteAsync(httpRequest, ct).ConfigureAwait(false);
                var body     = this.GetBody <T>(response);

                return(new DefaultResourceDataResult(req.Action, typeof(T), req.Uri, response.StatusCode, body));
            }));

            var request = new DefaultResourceDataRequest(ResourceAction.Read, typeof(T), canonicalUri, skipCache);

            return(chain.FilterAsync(request, this.logger, cancellationToken));
        }
Exemple #6
0
 // Copy constructor
 public DefaultHttpRequest(IHttpRequest existingRequest, Uri overrideUri = null)
 {
     this.body            = existingRequest.Body;
     this.bodyContentType = existingRequest.BodyContentType;
     this.headers         = new HttpHeaders(existingRequest.Headers);
     this.method          = existingRequest.Method.Clone();
     this.canonicalUri    = new CanonicalUri(existingRequest.CanonicalUri, overrideResourcePath: overrideUri);
 }
        public void Throws_when_URI_is_not_fully_qualified()
        {
            var notFullyQualified = "/path/to/resource";

            Should.Throw <ArgumentException>(() =>
            {
                var bad = new CanonicalUri(notFullyQualified);
            });

            Should.Throw <ArgumentException>(() =>
            {
                var bad = new CanonicalUri(notFullyQualified, new QueryString("foo=bar&baz=123"));
            });
        }
Exemple #8
0
        public DefaultHttpRequest(HttpMethod method, CanonicalUri canonicalUri, QueryString queryParams, HttpHeaders headers, string body, string bodyContentType)
        {
            this.method       = method;
            this.canonicalUri = canonicalUri;

            bool queryParamsWerePassed = queryParams?.Any() ?? false;

            if (queryParamsWerePassed)
            {
                var mergedQueryString = this.canonicalUri.QueryString.Merge(queryParams);
                this.canonicalUri = new CanonicalUri(this.canonicalUri.ResourcePath.ToString(), mergedQueryString);
            }

            this.headers = headers;
            if (headers == null)
            {
                this.headers = new HttpHeaders();
            }

            this.body            = body;
            this.bodyContentType = bodyContentType;
        }
Exemple #9
0
        private TReturned SaveCore <T, TReturned>(T resource, string href, QueryString queryParams, HttpHeaders headers, bool create)
            where T : class
            where TReturned : class
        {
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException(nameof(href));
            }

            var canonicalUri = new CanonicalUri(this.uriQualifier.EnsureFullyQualified(href), queryParams);

            this.logger.Trace($"Synchronously saving resource of type {typeof(T).Name} to {canonicalUri.ToString()}", "DefaultDataStore.SaveCore");

            ISynchronousFilterChain chain = new DefaultSynchronousFilterChain(this.defaultSyncFilters as DefaultSynchronousFilterChain)
                                            .Add(new DefaultSynchronousFilter((req, next, logger) =>
            {
                bool contentTypeIsPresent = !string.IsNullOrEmpty(req.Headers?.ContentType);

                bool contentTypeIsFormUrlEncoded =
                    contentTypeIsPresent &&
                    string.Equals(req.Headers.ContentType, HttpHeaders.MediaTypeApplicationFormUrlEncoded, StringComparison.OrdinalIgnoreCase);

                string postBody = contentTypeIsFormUrlEncoded
                        ? new FormUrlEncoder(req.Properties).ToString()
                        : this.serializer.Serialize(req.Properties);

                var httpRequest = new DefaultHttpRequest(
                    HttpMethod.Post,
                    req.Uri,
                    queryParams: null,
                    headers: req.Headers,
                    body: postBody,
                    bodyContentType: contentTypeIsPresent ? req.Headers.ContentType : DefaultContentType);

                var response       = this.Execute(httpRequest);
                var responseBody   = this.GetBody <T>(response);
                var responseAction = this.GetPostAction(req, response);

                bool responseHasData      = responseBody.Any();
                bool responseIsProcessing = response.StatusCode == 202;
                bool responseOkay         = responseHasData || responseIsProcessing;

                if (!responseOkay)
                {
                    throw new ResourceException(DefaultError.WithMessage("Unable to obtain resource data from the API server."));
                }

                if (responseIsProcessing)
                {
                    this.logger.Warn($"Received a 202 response, returning empty result. Href: '{canonicalUri.ToString()}'", "DefaultDataStore.SaveCoreAsync");
                }

                return(new DefaultResourceDataResult(responseAction, typeof(TReturned), req.Uri, response.StatusCode, responseBody));
            }));

            Map propertiesMap = null;

            var abstractResource = resource as AbstractResource;

            if (abstractResource != null)
            {
                // Serialize properties
                propertiesMap = this.resourceConverter.ToMap(abstractResource);

                var  extendableInstanceResource = abstractResource as AbstractExtendableInstanceResource;
                bool includesCustomData         = extendableInstanceResource != null;
                if (includesCustomData)
                {
                    var customDataProxy = (extendableInstanceResource as IExtendableSync).CustomData as DefaultCustomDataProxy;

                    // Apply custom data deletes
                    if (customDataProxy.HasDeletedProperties())
                    {
                        if (customDataProxy.DeleteAll)
                        {
                            this.DeleteCore <ICustomData>(extendableInstanceResource.CustomData.Href);
                        }
                        else
                        {
                            customDataProxy.DeleteRemovedCustomDataProperties(extendableInstanceResource.CustomData.Href);
                        }
                    }

                    // Merge in custom data updates
                    if (customDataProxy.HasUpdatedCustomDataProperties())
                    {
                        propertiesMap["customData"] = customDataProxy.UpdatedCustomDataProperties;
                    }

                    // Remove custom data updates from proxy
                    extendableInstanceResource.ResetCustomData();
                }
            }

            // In some cases, all we need to save are custom data property deletions, which is taken care of above.
            // So, we should just refresh with the latest data from the server.
            // This doesn't apply to CREATEs, though, because sometimes we need to POST a null body.
            bool nothingToPost = propertiesMap.IsNullOrEmpty();

            if (!create && nothingToPost)
            {
                return(this.AsSyncInterface.GetResource <TReturned>(canonicalUri.ToString()));
            }

            var requestAction = create
                ? ResourceAction.Create
                : ResourceAction.Update;
            var request = new DefaultResourceDataRequest(requestAction, typeof(T), canonicalUri, headers, propertiesMap, false);

            var result = chain.Filter(request, this.logger);

            return(this.resourceFactory.Create <TReturned>(result.Body, resource as ILinkable));
        }
Exemple #10
0
 public DefaultHttpRequest(HttpMethod method, CanonicalUri canonicalUri)
     : this(method, canonicalUri, null, null, null, null)
 {
 }