Beispiel #1
0
        public async Task <EstimateResult <IEstimate> > FindEstimatesAsync(EstimateQuery query)
        {
            string jsonResponse;
            var    requestUri = CreateRequestUri(query);

            using (var client = CreateClient())
            {
                try
                {
                    jsonResponse = await client.GetStringAsync(requestUri).ConfigureAwait(false);
                }
                catch (HttpRequestException rEx)
                {
                    // TODO: parse errors from here and create strongly typed error messages
                    // Could be object with Code, Description and HTML (full message received from Bring)
                    // Some errors are validation errors like - invalid postal code, invalid city etc., but some are exceptions.
                    // Wrap and return only validation errors, others throw further.
                    // Wrap configuration errors and throw them with details, but other errors throw as is.
                    // http://developer.bring.com/additionalresources/errorhandling.html?from=shipping
                    return(EstimateResult <IEstimate> .CreateFailure(rEx.Message));
                }
            }
            var response  = JsonConvert.DeserializeObject <ShippingResponse>(jsonResponse);
            var estimates = response.Product.Select(MapProduct).Cast <IEstimate>();

            return(EstimateResult <IEstimate> .CreateSuccess(estimates));
        }
Beispiel #2
0
        public async Task <EstimateResult <IEstimate> > FindEstimatesAsync(EstimateQuery query)
        {
            HttpResponseMessage responseMessage = null;
            string jsonResponse = null;

            var requestUri = CreateRequestUri(query);
            var cacheKey   = CreateCacheKey(requestUri);

            if (HttpRuntime.Cache.Get(cacheKey) is EstimateResult <IEstimate> cached)
            {
                return(await Task.FromResult(cached));
            }

            using (var client = CreateClient())
            {
                try
                {
                    responseMessage = await client.GetAsync(requestUri).ConfigureAwait(false);

                    jsonResponse = await responseMessage.Content.ReadAsStringAsync();

                    responseMessage.EnsureSuccessStatusCode();
                }
                catch (HttpRequestException)
                {
                    if (string.IsNullOrEmpty(jsonResponse))
                    {
                        var responseError = new ResponseError(responseMessage?.StatusCode ?? HttpStatusCode.InternalServerError);
                        return(EstimateResult <IEstimate> .CreateFailure(responseError));
                    }
                }
            }

            var response = JsonConvert.DeserializeObject <ShippingResponse>(jsonResponse, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var errors = response.GetAllErrors().ToArray();

            if (errors.Any())
            {
                return(EstimateResult <IEstimate> .CreateFailure(errors));
            }

            var products  = response.GetAllProducts();
            var estimates = products.Select(MapProduct).Cast <IEstimate>().ToList();
            var result    = EstimateResult <IEstimate> .CreateSuccess(estimates);

            HttpRuntime.Cache.Insert(cacheKey, result, null, DateTime.UtcNow.AddMinutes(2), Cache.NoSlidingExpiration);

            return(result);
        }
Beispiel #3
0
        public async Task it_returns_result()
        {
            var settings = new ShippingSettings(new Uri("http://test.localtest.me"));
            var sut      = new ShippingClient(settings);

            var query = new EstimateQuery(
                new ShipmentLeg("0484", "5600"),
                PackageSize.InGrams(2500));

            var actual = await sut.FindAsync <ShipmentEstimate>(query).ConfigureAwait(false);

            actual.Estimates.Should().NotBeEmpty();
        }
 public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
 {
     // All the values in "query" are null or zero
     // Do some stuff with query if there were anything to do
     if (query != null && query.username != null)
     {
         return(Ok(query.username));
     }
     else
     {
         return(Ok("Add a username!"));
     }
 }
Beispiel #5
0
        private Uri CreateRequestUri(EstimateQuery query)
        {
            var uri        = new Uri(Settings.EndpointUri, MethodName);
            var queryItems = HttpUtility.ParseQueryString(string.Empty); // This creates empty HttpValueCollection which creates query string on ToString

            queryItems.Add(query.Items);

            var ub = new UriBuilder(uri)
            {
                Query = queryItems.ToString()
            };

            return(ub.Uri);
        }
Beispiel #6
0
        public async Task it_returns_result()
        {
            var clientUri = new Uri("http://test.localtest.me");

            var settings = new ShippingSettings(clientUri, "*****@*****.**", "20b22ed6-2aa7-48c9-9561-b49fe85ce118");
            var sut      = new ShippingClient(settings);

            var query = new EstimateQuery(
                new ShipmentLeg("0484", "5600", "NO", "NO"),
                PackageSize.InGrams(2500),
                new Products(Product.Servicepakke));

            var actual = await sut.FindAsync <ShipmentEstimate>(query).ConfigureAwait(false);

            actual.Estimates.Should().NotBeEmpty();
        }
Beispiel #7
0
        public async Task it_returns_error_when_unauthenticated()
        {
            var clientUri = new Uri("http://test.localtest.me");

            var settings = new ShippingSettings(clientUri, (string)null, null);
            var sut      = new ShippingClient(settings);

            var query = new EstimateQuery(
                new ShipmentLeg("0484", "5600", "NO", "NO"),
                PackageSize.InGrams(2500));

            var actual = await sut.FindAsync <ShipmentEstimate>(query).ConfigureAwait(false);

            var responseErrors = actual.Errors.OfType <ResponseError>();

            Assert.Single(responseErrors);
        }
Beispiel #8
0
        public async Task it_returns_error_when_no_product_in_estimate_query()
        {
            var clientUri = new Uri("http://test.localtest.me");

            var settings = new ShippingSettings(clientUri, "*****@*****.**", "20b22ed6-2aa7-48c9-9561-b49fe85ce118");
            var sut      = new ShippingClient(settings);

            var query = new EstimateQuery(
                new ShipmentLeg("0484", "5600", "NO", "NO"),
                PackageSize.InGrams(2500));

            var actual = await sut.FindAsync <ShipmentEstimate>(query).ConfigureAwait(false);

            var fieldErrors = actual.Errors.OfType <FieldError>()
                              .Where(x => x.Code.Equals("INVALID_ARGUMENT"));

            Assert.Single(fieldErrors);
        }
Beispiel #9
0
        /// <summary>
        /// Finds Bring Shipping estimates based on estimate query.
        /// </summary>
        /// <typeparam name="T">Type of estimates <see cref="IEstimate"/>.</typeparam>
        /// <param name="query">Query parameters of type <see cref="EstimateQuery"/>.</param>
        /// <returns>Estimate find result of type <see cref="EstimateResult{T}"/>.</returns>
        public async Task <EstimateResult <T> > FindAsync <T>(EstimateQuery query)
            where T : IEstimate
        {
            foreach (var handler in Settings.QueryHandlers)
            {
                if (handler.CanHandle(typeof(T)))
                {
                    var estimate = await handler.FindEstimatesAsync(query).ConfigureAwait(false);

                    if (estimate.Success)
                    {
                        return(EstimateResult <T> .CreateSuccess(estimate.Estimates.Cast <T>()));
                    }
                    return(EstimateResult <T> .CreateFailure(estimate.ErrorMessages));
                }
            }

            throw new Exception(string.Format("No matching query handler found for estimate type {0}", typeof(T).Name));
        }
Beispiel #10
0
        private BringRatesSampleBlockView Search(BringRatesSampleBlockView formData)
        {
            var settings = new ShippingSettings(GetBaseUri());
            var client   = new ShippingClient(settings);

            var shipmentLeg          = ParameterMapper.GetShipmentLeg(formData);
            var packageSize          = ParameterMapper.GetPackageSize(formData);
            var additionalParameters = ParameterMapper.GetAdditionalParameters(formData);

            var query  = new EstimateQuery(shipmentLeg, packageSize, additionalParameters);
            var result = client.FindAsync <ShipmentEstimate>(query).Result;

            var estimateGroups = result.Estimates
                                 .GroupBy(x => x.GuiInformation.MainDisplayCategory)
                                 .Select(x => new BringRatesSampleBlockView.EstimateGroup(x.Key, x));

            var model = new BringRatesSampleBlockView(estimateGroups);

            return(model);
        }
 /// <summary>
 /// Gets the types required by the estimator in order to work:
 /// InterestRateMarketData is the only required type for this estimator.
 /// </summary>
 /// <param name="settings">The parameter is not used.</param>
 /// <param name="multivariateRequest">The parameter is not used.</param>
 /// <returns>An array containing the type InterestRateMarketData.</returns>
 public virtual EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return(new EstimateRequirement[] { new EstimateRequirement(typeof(InterestRateMarketData)) });
 }
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return(new EstimateRequirement[] { new EstimateRequirement(typeof(DVPLI.MarketDataTypes.Scalar[])) });
 }
 EstimateRequirement[] IEstimator.GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Gets the types required by the estimator in order to work:
 /// InterestRateMarketData is the only required type for this estimator.
 /// </summary>
 /// <param name="settings">The parameter is not used.</param>
 /// <param name="multivariateRequest">The parameter is not used.</param>
 /// <returns>An array containing the type InterestRateMarketData.</returns>
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return new EstimateRequirement[] { new EstimateRequirement(typeof(InterestRateMarketData)) };
 }
 /// <summary>
 /// Gets the types required by the estimator in order to work:
 /// InterestRateMarketData and CallPriceMarketData are
 /// the required type for this estimator.
 /// </summary>
 /// <param name="settings">The parameter is not used.</param>
 /// <param name="multivariateRequest">The parameter is not used.</param>
 /// <returns>
 /// An array containing the type InterestRateMarketData and CallPriceMarketData.
 /// </returns>
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return(new EstimateRequirement[] { new EstimateRequirement(typeof(DiscountingCurveMarketData), MarketRequirement.TickerMarket),
                                        new EstimateRequirement(typeof(CallPriceMarketData)),
                                        new EstimateRequirement(typeof(DVPLI.MarketDataTypes.Scalar)) });
 }
Beispiel #16
0
 /// <summary>
 /// List required market data inlcuding normal vol
 /// </summary>
 /// <param name="settings"></param>
 /// <param name="query"></param>
 /// <returns></returns>
 public override EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return(new EstimateRequirement[] {
         new EstimateRequirement(typeof(InterestRateMarketData)),
         new EstimateRequirement()
         {
             Field = "Vol-ATM-N", MarketDataType = typeof(MatrixMarketData), TickerReplacement = GetSwaptionVolatilityTicker(query.Market)
         }
     });
 }
 /// <summary>
 /// Gets the types required by the estimator in order to work:
 /// EquitySpotMarketData and CallPriceMarketData are
 /// the required type for this estimator.
 /// </summary>
 /// <param name="settings">The parameter is not used.</param>
 /// <param name="multivariateRequest">The parameter is not used.</param>
 /// <returns>
 /// An array containing the type EquitySpotMarketData and CallPriceMarketData.
 /// </returns>
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return new EstimateRequirement[] { new EstimateRequirement(typeof(EquitySpotMarketData)),
                                        new EstimateRequirement(typeof(CallPriceMarketData)),
                                        new EstimateRequirement(typeof(DiscountingCurveMarketData),MarketRequirement.TickerMarket) };
 }
Beispiel #18
0
 public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
 {
     // All the values in "query" are null or zero
     // Do some stuff with query if there were anything to do
 }
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return new EstimateRequirement[] { new EstimateRequirement(typeof(DVPLI.MarketDataTypes.Scalar[])) };
 }
 /// <summary>
 /// Gets the types required by the estimator in order to work:
 /// InterestRateMarketData and zero rate curve historical serie are required for this estimator.
 /// </summary>
 /// <param name="settings">The parameter is not used.</param>
 /// <param name="multivariateRequest">The parameter is not used.</param>
 /// <returns>An array containing the type InterestRateMarketData.</returns>
 public EstimateRequirement[] GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     return(new EstimateRequirement[] { new EstimateRequirement(typeof(InterestRateMarketData)),
                                        new EstimateRequirement(typeof(DiscountingCurveMarketData[])) });
 }
 EstimateRequirement[] IEstimator.GetRequirements(IEstimationSettings settings, EstimateQuery query)
 {
     throw new NotImplementedException();
 }