Exemple #1
0
        public IReadOnlyCollection <PurchaseInformation> FirstUpload(out int maxNumberPage)
        {
            string url          = mUrlBuilder.Build(mParameters);
            var    result       = mClient.GetResult(url);
            var    parsedResult = mMarketPlaceParser.Parse(result);

            try
            {
                maxNumberPage = mMaxNumberPageParser.Parse(result);
            }
            catch (System.NullReferenceException)
            {
                maxNumberPage = 1;
            }
            return(parsedResult);
        }
Exemple #2
0
        public async Task <string> BuildUrlAsync(string schme, string apiPath)
        {
            var serviceEndPoints = await GetEndpoints(serviceName);

            //负载均衡
            var _roundRobinLoadBlancer = new Ocelot.LoadBalancer.LoadBalancers.RoundRobin(() => Task.FromResult(serviceEndPoints));

            //服务主机名和端口
            var _servicehostAndPort = await _roundRobinLoadBlancer.Lease();

            if (!_servicehostAndPort.IsError)
            {
                var downStreamUrl = urlBuilder.Build(apiPath, schme, _servicehostAndPort.Data);

                if (!downStreamUrl.IsError)
                {
                    return(downStreamUrl.Data.Value);
                }
                else
                {
                    throw new System.Net.Http.HttpRequestException("");
                }
            }
            else
            {
                throw new System.Net.Http.HttpRequestException("LoadBalancer");
            }
        }
        public async Task <string> GenerateAsync()
        {
            var url    = _urlBuilder.Build();
            var uri    = new Uri(url);
            var result = await _clientFactory.Factory().GetResultAsync(uri).ConfigureAwait(false);

            var name = _parser.Parse(result);

            return(name);
        }
Exemple #4
0
        public async Task <List <Lib.Build> > GetWithStatus(BuildStatus statusFilter, BuildProviderSettings buildProviderSettings)
        {
            try
            {
                var excludedBuildDefinitionIds = buildProviderSettings.ExcludedBuildDefinitionIds ?? new List <long>();
                var urls      = _urlBuilder.Build(buildProviderSettings.Instance, buildProviderSettings.Collection, buildProviderSettings.TeamProjects);
                var responses = new List <BuildDefinitionsResponse>();

                foreach (var tfsUrl in urls)
                {
                    var request = tfsUrl
                                  .WithBasicAuth(buildProviderSettings.AccessToken, string.Empty)
                                  .AppendPathSegment("build")
                                  .AppendPathSegment("builds")
                                  .SetQueryParam("statusFilter", statusFilter.ToString())
                                  .SetQueryParam("maxBuildsPerDefinition", 1)
                                  .SetQueryParam("queryOrder", "finishTimeDescending");

                    _logger.Information($"Getting build definitions from url {request.Url}");

                    var res = await request.GetAsync();

                    var response = await request.GetJsonAsync <BuildDefinitionsResponse>();

                    responses.Add(response);
                }

                return(responses
                       .SelectMany(response => response
                                   .Builds
                                   .Where(bd => !excludedBuildDefinitionIds.Contains(bd.Id))
                                   .Select(_mapper.Map <Build, Lib.Build>))
                       .ToList());
            }
            catch (FlurlHttpTimeoutException)
            {
                // FlurlHttpTimeoutException derives from FlurlHttpException; catch here only
                // if you want to handle timeouts as a special case
                _logger.Error("Request timed out.");
            }
            catch (FlurlHttpException ex)
            {
                // ex.Message contains rich details, inclulding the URL, verb, response status,
                // and request and response bodies (if available)
                _logger.Error($"Calling {ex.Call.FlurlRequest.Url} returned the following error:");
                _logger.Error(ex.Message);
                _logger.Error($"Status code: {ex.Call.HttpStatus.ToString()}");
                _logger.Error($"Request Body: {ex.Call.RequestBody}");
                _logger.Error($"Response Body: {await ex.GetResponseStringAsync()}");
            }

            return(new List <Lib.Build>());
        }
Exemple #5
0
        public async Task <Models.Customer> GetUserAsync(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new AppException("User email required");
            }
            var parameters = new Dictionary <string, string>();

            parameters.Add("email", email);
            var response = await _client.GetAsync(_urlBuilder.Build("GetUserDetails", parameters));

            if (!response.IsSuccessStatusCode)
            {
                throw new AppException($"Invalid email {email}");
            }
            return(JsonConvert.DeserializeObject <Models.Customer>(await response.Content.ReadAsStringAsync()));
        }
Exemple #6
0
        public async Task Invoke(HttpContext context)
        {
            _logger.LogDebug("started calling downstream url creator middleware");

            var dsPath = _replacer
                         .Replace(DownstreamRoute.ReRoute.DownstreamPathTemplate, DownstreamRoute.TemplatePlaceholderNameAndValues);

            if (dsPath.IsError)
            {
                _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error");

                SetPipelineError(dsPath.Errors);
                return;
            }

            var dsScheme = DownstreamRoute.ReRoute.DownstreamScheme;

            var dsHostAndPort = HostAndPort;

            var dsUrl = _urlBuilder.Build(dsPath.Data.Value, dsScheme, dsHostAndPort);

            if (dsUrl.IsError)
            {
                _logger.LogDebug("IUrlBuilder returned an error, setting pipeline error");

                SetPipelineError(dsUrl.Errors);
                return;
            }

            _logger.LogDebug("downstream url is {downstreamUrl.Data.Value}", dsUrl.Data.Value);

            SetDownstreamUrlForThisRequest(dsUrl.Data.Value);

            _logger.LogDebug("calling next middleware");

            await _next.Invoke(context);

            _logger.LogDebug("succesfully called next middleware");
        }
Exemple #7
0
        /// <summary>
        /// Executes a REST request indirectly via a callback function <paramref name="executeCallback"/>,
        /// and using a user-defined callback function <paramref name="responseBuilderCallback"/> for
        /// constructing the resulting <see cref="Response"/> object.
        /// </summary>
        /// <remarks>
        /// The callback method <paramref name="executeCallback"/> is responsible for setting the body
        /// of the request, if any, before executing the request. The callback method returns a string
        /// representation of the body of the final request when available, otherwise returns a string
        /// indicating the body is no longer available (e.g. was sent as a stream, or is binary). The
        /// result is only required for passing as an argument to <see cref="IRequestLogger.Log"/>.
        ///
        /// <para>The Boolean argument to <paramref name="responseBuilderCallback"/> indicates whether
        /// or not an exception was thrown while executing the request. The value is <c>true</c>
        /// if an exception occurred, otherwise <c>false</c>.</para>
        /// </remarks>
        /// <param name="url">The base URI.</param>
        /// <param name="method">The HTTP method to use for the request.</param>
        /// <param name="responseBuilderCallback">A user-specified function used to construct the resulting <see cref="Response"/>
        /// object from the <see cref="HttpWebResponse"/> and a Boolean value specifying whether or not a <see cref="WebException"/>
        /// was thrown during the request. If this value is <c>null</c>, a default method is used to construct
        /// the resulting <see cref="Response"/> object.</param>
        /// <param name="headers">
        /// A collection of custom HTTP headers to include with the request. If the value is
        /// <c>null</c>, no custom headers are added to the HTTP request.
        /// </param>
        /// <param name="queryStringParameters">
        /// A collection of parameters to add to the query string portion of the request URI.
        /// If the value is <c>null</c>, no parameters are added to the query string.
        /// </param>
        /// <param name="settings">
        /// The settings to use for the request. If the value is <c>null</c>, the default settings returned
        /// by <see cref="DefaultRequestSettings"/> will be used for the request.
        /// </param>
        /// <param name="executeCallback"></param>
        /// <returns>Returns a <see cref="Response"/> object containing the HTTP status code, headers,
        /// and body from the REST response.</returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="url"/> is <c>null</c>.
        /// <para>-or-</para>
        /// <para>If <paramref name="executeCallback"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="NotSupportedException">If <paramref name="method"/> is not supported by the service.</exception>
        public virtual Response ExecuteRequest(Uri url, HttpMethod method, Func <HttpWebResponse, bool, Response> responseBuilderCallback, Dictionary <string, string> headers, Dictionary <string, string> queryStringParameters, RequestSettings settings, Func <HttpWebRequest, string> executeCallback)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
            if (executeCallback == null)
            {
                throw new ArgumentNullException("executeCallback");
            }

            url = _urlBuilder.Build(url, queryStringParameters);

            if (settings == null)
            {
                settings = DefaultRequestSettings;
            }

            return(_retryLogic.Execute(() =>
            {
                Response response;

                var startTime = DateTimeOffset.UtcNow;

                string requestBodyText = null;
                try
                {
                    var req = WebRequest.Create(url) as HttpWebRequest;
                    req.Method = method.ToString();
                    req.ContentType = settings.ContentType;
                    req.Accept = settings.Accept;
                    req.AllowAutoRedirect = settings.AllowAutoRedirect;
                    if (settings.ContentLength > 0 || settings.AllowZeroContentLength)
                    {
                        req.ContentLength = settings.ContentLength;
                    }

                    if (settings.ConnectionLimit != null)
                    {
                        req.ServicePoint.ConnectionLimit = settings.ConnectionLimit.Value;
                    }

                    req.Timeout = (int)settings.Timeout.TotalMilliseconds;

                    if (!string.IsNullOrEmpty(settings.UserAgent))
                    {
                        req.UserAgent = settings.UserAgent;
                    }

                    if (settings.Credentials != null)
                    {
                        req.Credentials = settings.Credentials;
                    }

                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            req.Headers.Add(header.Key, header.Value);
                        }
                    }

                    requestBodyText = executeCallback(req);

                    using (var resp = req.GetResponse() as HttpWebResponse)
                    {
                        if (responseBuilderCallback != null)
                        {
                            response = responseBuilderCallback(resp, false);
                        }
                        else
                        {
                            response = BuildWebResponse(resp);
                        }
                    }
                }
                catch (WebException ex)
                {
                    if (ex.Response == null)
                    {
                        throw;
                    }

                    using (var resp = ex.Response as HttpWebResponse)
                    {
                        if (responseBuilderCallback != null)
                        {
                            response = responseBuilderCallback(resp, true);
                        }
                        else
                        {
                            response = BuildWebResponse(resp);
                        }
                    }
                }
                var endTime = DateTimeOffset.UtcNow;

                // Log the request
                if (_logger != null)
                {
                    _logger.Log(method, url.OriginalString, headers, requestBodyText, response, startTime, endTime, settings.ExtendedLoggingData);
                }

                if (response != null && settings.ResponseActions != null && settings.ResponseActions.ContainsKey(response.StatusCode))
                {
                    var action = settings.ResponseActions[response.StatusCode];
                    if (action != null)
                    {
                        action(response);
                    }
                }

                return response;
            }, settings.Non200SuccessCodes, settings.RetryCount, settings.RetryDelay));
        }
Exemple #8
0
 private void WhenIBuildTheUrl()
 {
     _result = _urlBuilder.Build(_dsPath, _dsScheme, new HostAndPort(_dsHost, _dsPort));
 }
Exemple #9
0
        public GoogleSearchResponse Search(string query)
        {
            var url = _urlBuilder.Build(_config, query);

            return(GetResults(url));
        }