Пример #1
0
        public IEnumerable <Establishment> FindEstablishments(EstablishmentFilter filter = null)
        {
            int pages;

            filter      = filter ?? new EstablishmentFilter();
            filter.Page = 0;
            PreRequest?.Invoke(filter);
            var response = _client.FindEstablishments(filter, out pages);

            PostRequest?.Invoke(filter, response);

            foreach (var establishment in response)
            {
                yield return(establishment);
            }

            for (var i = 1; i < pages; i++)
            {
                filter.Page = i;

                PreRequest?.Invoke(filter);
                response = _client.FindEstablishments(filter, out pages);
                PostRequest?.Invoke(filter, response);

                foreach (var establishment in response)
                {
                    yield return(establishment);
                }
            }
        }
Пример #2
0
        private async Task <FindEstablishmentsResponse> RequestEstablishments(EstablishmentFilter filter)
        {
            PreRequest?.Invoke(filter);
            var response = await _client.FindEstablishmentsAsync(new FindEstablishmentsRequest(filter));

            PostRequestAsync?.Invoke(filter, response);
            return(response);
        }
Пример #3
0
        /// <summary>
        /// Fetches a string from a resource
        /// </summary>
        /// <param name="uri">URI</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="PocketException"></exception>
        protected async Task <string> RequestAsString(string uri, CancellationToken cancellationToken)
        {
            // every single Pocket API endpoint requires HTTP POST data
            HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, uri);
            HttpResponseMessage response = null;
            string responseString        = null;

            // call pre request action
            PreRequest?.Invoke(uri);

            // make async request
            try
            {
                response = await httpClient.GetAsync(uri, cancellationToken);

                // validate HTTP response
                ValidateResponse(response);

                // cache headers
                if (cacheHTTPResponseData)
                {
                    lastHeaders = response.Headers;
                }

                // read response
                responseString = await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException exc)
            {
                throw new PocketException(exc.Message, exc);
            }
            catch (PocketException exc)
            {
                throw exc;
            }
            finally
            {
                request.Dispose();

                if (response != null)
                {
                    response.Dispose();
                }
            }

            // call after request action
            AfterRequest?.Invoke(responseString);

            // cache response
            if (cacheHTTPResponseData)
            {
                lastResponseData = responseString;
            }

            return(responseString);
        }
Пример #4
0
        private IEnumerable <Provider> GetProviderQueryResponse(SelectionCriteriaStructure criteria, string queryId, int batchSize, IDictionary <string, string> warnings)
        {
            var noOfUkprnsProcessed = 0;

            var providerUkprns = criteria.UnitedKingdomProviderReferenceNumberList.ToList();
            var ukprnsListSize = providerUkprns.Count;

            do
            {
                var numberOfUkprnsUnprocessed = ukprnsListSize - noOfUkprnsProcessed;
                var numberOfUkprnsToSend      = numberOfUkprnsUnprocessed > batchSize
                    ? batchSize
                    : numberOfUkprnsUnprocessed;

                criteria.UnitedKingdomProviderReferenceNumberList =
                    providerUkprns.Skip(noOfUkprnsProcessed).Take(numberOfUkprnsToSend).ToArray();

                var providerQueryStructure = new ProviderQueryStructure
                {
                    QueryId           = queryId,
                    SchemaVersion     = "?",
                    SelectionCriteria = criteria
                };

                ProviderQueryResponse response = null;
                try
                {
                    PreRequest?.Invoke(criteria);
                    response = _client.retrieveAllProviders(providerQueryStructure);
                    PostRequest?.Invoke(criteria, response);
                }
                catch (Exception ex)
                {
                    throw new ProviderQueryException(ex.Message, criteria, ex);
                }

                var providers = response?.MatchingProviderRecords?.Select(MapFromUkrlpProviderRecord).ToList() ??
                                new List <Provider>();
                foreach (
                    var missing in
                    criteria.UnitedKingdomProviderReferenceNumberList.Where(
                        x => providers.All(y => x != y.UnitedKingdomProviderReferenceNumber)))
                {
                    warnings.Add(missing, MissingMessage);
                }

                foreach (var provider in providers)
                {
                    yield return(provider);
                }
                noOfUkprnsProcessed += numberOfUkprnsToSend;
            } while (noOfUkprnsProcessed < ukprnsListSize);
        }
Пример #5
0
        private async Task <T> GetResponseAsync <T>(object request, Uri requestUri)
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri);

            httpRequestMessage.Headers.Accept.Clear();
            httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonContentType));
            httpRequestMessage.Headers.Add("Client", $"Autoaddress2.0SDK {AssemblyVersion}");

            EnsureHttpClient();

            var completionOption  = HttpCompletionOption.ResponseContentRead;
            var cancellationToken = CancellationToken.None;

            PreRequest?.Invoke(this, new PreRequestEventArgs(request, httpRequestMessage));

            HttpResponseMessage response = await _httpClient.SendAsync(httpRequestMessage, completionOption, cancellationToken).ConfigureAwait(false);

            string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            PostRequest?.Invoke(this, new PostRequestEventArgs(response, content));

            if (!response.IsSuccessStatusCode)
            {
                if ((int)response.StatusCode == 429)
                {
                    throw new TooManyRequestsException(response.ReasonPhrase);
                }

                AutoaddressException autoaddressException = GetAutoaddressException(response.StatusCode, httpRequestMessage.RequestUri, content);

                if (autoaddressException != null)
                {
                    throw autoaddressException;
                }

                // guard
                response.EnsureSuccessStatusCode();

                throw new InvalidOperationException();
            }

            string result = ParseJson(content);

            return(JsonConvert.DeserializeObject <T>(result));
        }
Пример #6
0
        public IHttpActionResult AddNewPreRequest(PreRequestViewModel pPreRequest)
        {
            try
            {
                this.objPreClientController = new PreClientController();
                ResponseViewModel rta = new ResponseViewModel();

                using (BDRAEntities db = new BDRAEntities())
                {
                    /*
                     *              Validamos si el PreCliente de la solicitud ya existe en la base de datos.
                     */

                    PreClient PreClientBD = new PreClient();

                    PreClientBD = objPreClientController.GetPreClientBD(pPreRequest.preClient);

                    if (PreClientBD == null)
                    {
                        PreClientBD = objPreClientController.SetDataToPreClient(pPreRequest.preClient, pPreRequest.user);
                        var preClientCreated = objPreClientController.CreatePreClientInBD(PreClientBD);
                        if (preClientCreated)
                        {
                            PreClientBD = objPreClientController.GetPreClientBD(pPreRequest.preClient);
                        }
                    }


                    PreRequest oPreRequest = new PreRequest();
                    oPreRequest.preReq_registrationDate = DateTime.Now;
                    oPreRequest.preCli_id    = PreClientBD.preCli_id;
                    oPreRequest.preReq_state = true;
                    oPreRequest.usu_document = pPreRequest.user.id;

                    if (pPreRequest.vehicleModel.id != null && pPreRequest.vehicleModel.id != 0)
                    {
                        oPreRequest.vehMdl_id = pPreRequest.vehicleModel.id;
                    }
                    else
                    {
                        var vechicleModel  = VehicleModelController.SetDataToVehicleModel(pPreRequest.vehicleModel);
                        var vehicleModelDB = VehicleModelController.CreateVehicleModelInDB(vechicleModel);
                        oPreRequest.vehMdl_id = vehicleModelDB.id;
                    }
                    if (pPreRequest.stateRequest != null)
                    {
                        oPreRequest.sta_id = pPreRequest.stateRequest.id;
                    }
                    if (pPreRequest.firstCanal != null)
                    {
                        oPreRequest.firstCanal_id = pPreRequest.firstCanal.id;
                    }
                    if (pPreRequest.secondCanal != null)
                    {
                        oPreRequest.secondCanal_id = pPreRequest.secondCanal.id;
                    }


                    db.PreRequest.Add(oPreRequest);
                    db.SaveChanges();

                    var lastRequest = GetTheLastPreRequestByPreClient(PreClientBD);

                    if (pPreRequest.lsObservation[0].observation != "")
                    {
                        PreRequest_Observation observation = this.SetDataToObservation(lastRequest.preReq_id, pPreRequest.lsObservation[0].observation, pPreRequest.user.id);
                        this.InsertObservationInDB(observation);
                    }


                    rta.response = true;
                    rta.message  = "Se ha creado la pre solicitud: " + lastRequest.preReq_id + " de cliente de persona natural";

                    return(Ok(rta));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Пример #7
0
        /// <summary>
        /// Fetches a typed resource
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method">Requested method (path after /v3/)</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="parameters">Additional POST parameters</param>
        /// <param name="requireAuth">if set to <c>true</c> [require auth].</param>
        /// <returns></returns>
        /// <exception cref="PocketException">No access token available. Use authentification first.</exception>
        protected async Task <T> Request <T>(
            string method,
            CancellationToken cancellationToken,
            Dictionary <string, string> parameters = null,
            bool requireAuth     = true,
            bool isReaderRequest = false) where T : class, new()
        {
            if (requireAuth && AccessCode == null)
            {
                throw new PocketException("SDK error: No access token available. Use authentication first.");
            }

            string httpBase = isReaderRequest ? parserUri : baseUri;

            if (isReaderRequest && String.IsNullOrEmpty(parserUri))
            {
                throw new PocketException("Please pass a valid parserUri in the PocketClient ctor.");
            }

            // every single Pocket API endpoint requires HTTP POST data
            HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Post, httpBase + method);
            HttpResponseMessage response = null;
            string responseString        = null;

            if (parameters == null)
            {
                parameters = new Dictionary <string, string>();
            }

            // add consumer key to each request
            parameters.Add("consumer_key", ConsumerKey);

            // add access token (necessary for all requests except authentification)
            if (AccessCode != null && requireAuth)
            {
                parameters.Add("access_token", AccessCode);
            }

            // content of the request
            request.Content = new FormUrlEncodedContent(parameters);

            // call pre request action
            PreRequest?.Invoke(method);

            // make async request
            try
            {
                response = await httpClient.SendAsync(request, cancellationToken);

                // validate HTTP response
                ValidateResponse(response);

                // cache headers
                if (cacheHTTPResponseData)
                {
                    lastHeaders = response.Headers;
                }

                // read response
                responseString = await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException exc)
            {
                throw new PocketException(exc.Message, exc);
            }
            catch (PocketException exc)
            {
                throw exc;
            }
            finally
            {
                request.Dispose();

                if (response != null)
                {
                    response.Dispose();
                }
            }

            // call after request action
            AfterRequest?.Invoke(responseString);

            // cache response
            if (cacheHTTPResponseData)
            {
                lastResponseData = responseString;
            }

            return(DeserializeJson <T>(responseString));
        }
Пример #8
0
        /// <summary>
        /// 获取相应对象
        /// </summary>
        /// <returns></returns>
        public async Task <HttpResponseMessage> GetResponse()
        {
            var  timer        = Stopwatch.StartNew();
            long pre          = 0,
                 setheader    = 0,
                 setbody      = 0,
                 res          = 0,
                 acceptcookie = 0,
                 acceptheader = 0,
                 error        = 0,
                 end          = 0;

            if (Encoding == null)
            {
                Encoding = Encoding.UTF8;
            }
            if (PreRequest != null)
            {
                await PreRequest.ConfigureAwait(false);

                PreRequest = null;
                pre        = timer.ElapsedMilliseconds;
                timer.Restart();
            }
            ResponseCode = 0;
            Exception    = null;
            Uri uri = GetFullUrl();

            Trace.WriteLine(uri.ToString(), "HttpRequest.Url");

            var cancel = new CancellationTokenSource(Timeout);

            try
            {
                _Abort = cancel.Cancel;
                var message = new HttpRequestMessage(GetHttpMethod(), uri);

                if (Cookie?.Count > 0)
                {
                    message.Headers.Add("Cookie", Cookie.GetCookieHeader(uri));
                }
                if (KeepAlive)
                {
                    message.Headers.Connection.Add("keep-alive");
                }

                if (_FormBody != null)
                {
                    var formdata = FormBody.GetBytes(Encoding);
                    message.Content = new ByteArrayContent(formdata);

                    message.Content.Headers.Add("Content-Type", FormBody.ContentType);
                    message.Content.Headers.ContentType.CharSet = Encoding.WebName;
                    //message.Headers.TryAddWithoutValidation("Content-Type", "charset=" + Encoding.WebName);

                    setbody = timer.ElapsedMilliseconds;
                    timer.Restart();
                }

                if (_Headers?.Count > 0)
                {
                    foreach (var item in _Headers)
                    {
                        var arr = item.Value as IEnumerable <string>;
                        if (arr != null)
                        {
                            if (!message.Headers.TryAddWithoutValidation(item.Key, arr) &&
                                message.Content != null)
                            {
                                message.Content.Headers.TryAddWithoutValidation(item.Key, arr);
                            }
                        }
                        else
                        {
                            var str = item.Value as string ?? item.Value + "";
                            if (!message.Headers.TryAddWithoutValidation(item.Key, str) &&
                                message.Content != null)
                            {
                                message.Content.Headers.TryAddWithoutValidation(item.Key, str);
                            }
                        }
                    }
                    setheader = timer.ElapsedMilliseconds;
                    timer.Restart();
                }


                var response = await HttpClient.SendAsync(message, cancel.Token);

                _Abort = null;
                res    = timer.ElapsedMilliseconds;
                timer.Restart();
                if (AcceptCookie && response.Headers.Contains("Set-Cookie"))
                {
                    var setcookies = response.Headers.GetValues("Set-Cookie");
                    foreach (var cookie in setcookies)
                    {
                        Cookie.SetCookies(uri, cookie);
                    }
                    acceptcookie = timer.ElapsedMilliseconds;
                    timer.Restart();
                }
                if (AcceptHeader)
                {
                    Headers.Clear();
                    foreach (var head in response.Headers)
                    {
                        Headers.Add(head.Key, head.Value);
                    }
                    foreach (var head in response.Content.Headers)
                    {
                        Headers.Add(head.Key, head.Value);
                    }
                    acceptheader = timer.ElapsedMilliseconds;
                    timer.Restart();
                }
                ResponseCode = response.StatusCode;
                return(response);
            }
            catch (Exception ex)
            {
                error = timer.ElapsedMilliseconds;
                timer.Restart();
                if (ex is TaskCanceledException && _Abort != null)
                {
                    ex = new TimeoutException("请求已超时");
                }
                Trace.WriteLine(ex.Message, "HttpRequest.Error");
                Exception    = ex;
                ResponseCode = 0;
                return(null);
            }
            finally
            {
                cancel?.Dispose();
                _Abort  = null;
                setbody = timer.ElapsedMilliseconds;
                timer.Stop();
                Trace.WriteLine(ResponseCode, "HttpRequest.StatusCode");
                Trace.WriteLine(
                    $"pre={pre}; setheader={setheader}; setbody={setbody}; response={res}; acceptcookie={acceptcookie}; acceptheader={acceptheader}; error={error}; end={end}",
                    "HttpRequest.Timing");
            }
        }