Exemplo n.º 1
0
        //Funcion para insertar un nuevo registro
        public String InsertPrice(PriceRequest priceRequest)
        {
            try
            {
                PriceResponse priceResponse = GetPriceByVehicleType(priceRequest.idVehicleType);
                if (priceResponse == null)
                {
                    Price price = new Price();
                    price.idVehicleType = priceRequest.idVehicleType;
                    price.valueMinute   = priceRequest.valueMinute;
                    price.valueMonth    = priceRequest.valueMonth;
                    db.Price.Add(price);
                    db.SaveChanges();
                    mensaje = "OK";
                }
                else
                {
                    mensaje = "PRICE_EXIST_FOR_THIS_VEHICLE_TYPE";
                }
            }
            catch (DbEntityValidationException e)
            {
                mensaje = "Error al crear un precio" + e;
            }

            return(mensaje);
        }
        public PriceResponse ToPriceResponse()
        {
            var response = new PriceResponse();

            response.Ok      = Ok;
            response.Message = Message;
            response.License = License;
            response.Data    = Data;
            response.Status  = Status;

            response.Prices = new Dictionary <GasStationId, Result <PriceRequestError, Models.Prices> >();

            foreach (var barePrices in Prices)
            {
                switch (barePrices.Value.Status)
                {
                case "open":
                    response.Prices.Add(barePrices.Key, Result <PriceRequestError, Models.Prices> .Ok(barePrices.Value.ToPrices()));
                    break;

                case "no prices":
                    response.Prices.Add(barePrices.Key, Result <PriceRequestError, Models.Prices> .Error(PriceRequestError.NoPrices));
                    break;

                case "closed":
                    response.Prices.Add(barePrices.Key, Result <PriceRequestError, Models.Prices> .Error(PriceRequestError.Closed));
                    break;

                default:
                    throw new Exception();     // TODO: Fehlerbehandlung
                }
            }

            return(response);
        }
Exemplo n.º 3
0
        public static Prices GetPrices()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.ethPrice);

            request.ContentType = "application/json; charset=utf-8";
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string          data     = "";

            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                data = reader.ReadToEnd();
            }

            PriceResponse r      = JsonConvert.DeserializeObject <PriceResponse>(data);
            Prices        prices = null;

            if (r.status != false)
            {
                prices = r.data;
            }
            else
            {
                return(null);
            }

            return(prices);
        }
Exemplo n.º 4
0
        public static void PriceEvent(object sender, PriceResponse response)
        {
            if (response.Event == EventType.Subscribed)
            {
                Console.WriteLine("*You succesfully subscribed to price updates for pair: " + response.Symbol);
            }
            else if (response.Event == EventType.Updated)
            {
                Console.WriteLine("*** Update on pair '" + response.Symbol + "': \n" +
                                  "Timestamp: " + response.price[0] + "\n" +
                                  "open: " + response.price[1] + "\n" +
                                  "high: " + response.price[2] + "\n" +
                                  "low: " + response.price[3] + "\n" +
                                  "close: " + response.price[4] + "\n" +
                                  "volume: " + response.price[5] + "\n" +
                                  "*** End of update. \n");
            }
            else if (response.Event == EventType.Rejected)
            {
                Console.WriteLine("*Your attempt to subscribe to price update was rejected: " + response.Message);
            }

            else if (response.Event == EventType.Unsubscribed)
            {
                Console.WriteLine("*You succesfully unsubscribed from price updates of pair: " + response.Symbol);
            }
        }
Exemplo n.º 5
0
        public async System.Threading.Tasks.Task GetPrice_GBP_Books_Cost_Match()
        {
            var bookList = new PriceRequest()
            {
                BookList = new BookList
                {
                    Book1 = 2,
                    Book2 = 2,
                    Book3 = 2,
                    Book4 = 1,
                    Book5 = 1
                }
            };

            var priceResponse = new PriceResponse
            {
                GBP  = 51.20m,
                Euro = 56.32m
            };

            var request           = new GetPrice(bookList);
            var cancellationToken = new CancellationToken();

            var expected = new GetPriceResponse(priceResponse).PriceResponse.GBP;
            var actual   = await _getPriceHandler.Handle(request, cancellationToken).ConfigureAwait(false);

            Assert.AreEqual(actual.PriceResponse.GBP, expected);
        }
Exemplo n.º 6
0
        public async System.Threading.Tasks.Task GetPrice_Euro_Match()
        {
            var bookList = new PriceRequest()
            {
                BookList = new BookList
                {
                    Book1 = 0,
                    Book2 = 0,
                    Book3 = 0,
                    Book4 = 0,
                    Book5 = 0
                }
            };

            var priceResponse = new PriceResponse
            {
                GBP  = 0m,
                Euro = 0m
            };

            var request           = new GetPrice(bookList);
            var cancellationToken = new CancellationToken();

            var expected = new GetPriceResponse(priceResponse).PriceResponse.Euro;
            var actual   = await _getPriceHandler.Handle(request, cancellationToken).ConfigureAwait(false);

            Assert.AreEqual(actual.PriceResponse.Euro, expected);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Price Request/Response
        /// </summary>
        /// <param name="priceWmRequest"></param>
        /// <returns></returns>
        public PriceResponse GetPrice(PriceRequest priceWmRequest)
        {
            var priceResponse = new PriceResponse();
            var request       = priceWmRequest.ToWmPriceRequest();
            var backup        = new BackupLogEntry(request, "PriceRequest");

            LogRequest(request, "PriceRequest");
            var wmPriceResponse = _soapStoreFrontWebService.PriceWebServiceAsync(request).Result;

            backup.AddResponse(wmPriceResponse);
            _repository.InsertOne(backup);
            LogResponse(wmPriceResponse);

            var failedProducts = new List <FailedProduct>();

            while (wmPriceResponse.ErrorReturn != null)
            {
                var productId = GetProductFromMaterialErrorMessage(wmPriceResponse.ErrorReturn.Error);
                if (productId == Empty)
                {
                    priceResponse.ErrorMessage = wmPriceResponse.ErrorReturn.Error;
                    return(priceResponse);
                }

                Log($"{ErrorMessages.ERRORS_CONTAINED_IN_RESPONSE} for product {productId}");

                var failedProduct = new FailedProduct {
                    ErrorMessage = wmPriceResponse.ErrorReturn.Error, PartNumber = productId
                };
                failedProducts.Add(failedProduct);

                var newProductLists = request.PricingRequest.ProductList.Where(val => val.ProductID != productId).ToArray();
                //I don't see why or how this will be needed (if no edge case is reported by 1/1/2020, remove this line altogether)
                //if (newProductLists.Length == request.PricingRequest.ProductList.Length) break;

                request.PricingRequest.ProductList = newProductLists;
                if (newProductLists.Length == 0)
                {
                    break;
                }

                Log(InfoMessages.SEND_DATA_CORRECTED_INPUT_REQUEST);
                var backup2 = new BackupLogEntry(request, "PriceRequest");
                LogRequest(request, "Additional PriceRequests (to handle failed products)");
                wmPriceResponse = _soapStoreFrontWebService.PriceWebServiceAsync(request).Result;
                backup2.AddResponse(wmPriceResponse);
                _repository.InsertOne(backup2);
                LogResponse(wmPriceResponse);
            }

            priceResponse = wmPriceResponse.ToPriceResponse();

            if (failedProducts.Count == 0)
            {
                return(priceResponse);
            }
            priceResponse.FailedProducts = failedProducts;
            priceResponse.ErrorMessage   = "We were not able to obtain prices for all requested products.  Please see list of failed products.";
            return(priceResponse);
        }
Exemplo n.º 8
0
        //pass request with risk data with details of a gadget, return the best price retrieved from 3 external quotation engines
        public PriceResponse GetPrice(PriceRequest request, out string errorMessage)
        {
            errorMessage = string.Empty;

            var result = new PriceResponse();

            this.ValidateRequest(request, ref errorMessage);
            if (errorMessage.Length > 0)
            {
                return(result);
            }

            //now call 3 external system and get the best price
            foreach (var quoteSys in this.GetQuotationSystems(request))
            {
                var systemResponse = quoteSys.GetPrice(request);
                if (this.IsResponseValid(systemResponse) && systemResponse.Price < result.Price)
                {
                    result.Price       = Math.Min(systemResponse.Price, result.Price);
                    result.InsurerName = systemResponse.Name;
                    result.Tax         = systemResponse.Tax;
                }
            }

            return(result);
        }
        // Arrange
        // Act

        public async Task ShouldbeAThing()
        {
            PriceResponse priceResponse = await Mediator.Send(new PriceRequest());

            Console.WriteLine(priceResponse);
            Console.WriteLine($"Price Response Close Rate: {priceResponse.C}");
            priceResponse.ShouldNotBeNull();
            priceResponse.C.ShouldBeGreaterThan(0);
            //priceResponse.Ts.AddMinutes(1).ShouldBeGreaterThan(DateTime.Now);
        }
Exemplo n.º 10
0
        public async Task PriceAndCurrencySubmitted_CreatesPriceResponse_ReturnsPriceResponse()
        {
            //arrange
            var convertedPriceService = new ConvertedPriceService(_currencyConverterMock.Object);

            //act
            PriceResponse priceResponse = await convertedPriceService.ConvertedPriceResponse((decimal)1.12, "sourceCurrency", "targetCurrency");

            //assert
            Assert.IsInstanceOf <PriceResponse>(priceResponse);
        }
        public IHttpActionResult GetPrice(int id)
        {
            PriceResponse price = priceModel.GetPriceByVehicleType(id);

            if (price == null)
            {
                return(NotFound());
            }

            return(Ok(price));
        }
Exemplo n.º 12
0
        public IActionResult GetPricesForBooks([FromBody] PriceRequest priceRequest)
        {
            if ((priceRequest?.BookIds?.Length ?? 0) == 0)
            {
                return(BadRequest("A valid PriceRequest must contain BookIds"));
            }

            var response = new PriceResponse
            {
                Prices = priceRequest.BookIds.Select(bookId => _priceEngine.GetPriceForBook(bookId)).ToList()
            };

            return(Ok(response));
        }
Exemplo n.º 13
0
        public async Task PriceAndCurrencySubmitted_CreatesPriceResponseWithTargetCurrency_ReturnPriceResponse()
        {
            //arrange
            var price                 = (decimal)1.12;
            var sourceCurrency        = "USD";
            var targetCurrency        = "GBP";
            var convertedPriceService = new ConvertedPriceService(_currencyConverterMock.Object);

            //act
            PriceResponse priceResponse = await convertedPriceService.ConvertedPriceResponse(price, sourceCurrency, targetCurrency);

            //assert
            Assert.AreEqual(targetCurrency, priceResponse.Currency);
        }
Exemplo n.º 14
0
        private BookCatalog BuildBookCatalogVm(IEnumerable <Book> books, PriceResponse prices, RatingResponse ratings)
        {
            var priceMap  = prices.Prices.ToDictionary(p => p.BookId);
            var ratingMap = ratings.Ratings.ToDictionary(p => p.BookId);

            var catalogItems = books.Select(b =>
                                            new BookCatalogItem
            {
                Id          = b.Id,
                Isbn        = b.Isbn,
                Title       = b.Title,
                ReleaseDate = b.ReleaseDate,
                Price       = priceMap.TryGetValue(b.Id, out Price price) ? price.Amount : 0m,
                Rating      = ratingMap.TryGetValue(b.Id, out BookRating rating) ? rating.AvgRating : 0
            }).ToArray();
Exemplo n.º 15
0
    private IEnumerator OnReceiveCoinUpdate(WWW req)
    {
        yield return(req);

        // Gotta fix the response text
        string fixedReq = string.Format("{0}{1}{2}", "{\"Prices\":", req.text, "}");

        PriceResponse obj = PriceResponse.FromJson(fixedReq);

        foreach (CoinPrice cp in obj.prices.Values)
        {
            Debug.Log("\nUSD:" + cp.USD +
                      "\nBTC:" + cp.BTC +
                      "\nETH:" + cp.ETH);
        }
    }
Exemplo n.º 16
0
        public void ShouldReturnResponseWithoutError(RiskData data, PriceResponse expectedResponse, string expectedMessage)
        {
            var request = new PriceRequest()
            {
                RiskData = data
            };

            var error  = string.Empty;
            var result = priceEngine.GetPrice(request, out error);

            Assert.AreEqual(expectedMessage, error);

            Assert.AreEqual(expectedResponse.Price, result.Price);
            Assert.AreEqual(expectedResponse.Tax, result.Tax);
            Assert.AreEqual(expectedResponse.InsurerName, result.InsurerName);
        }
Exemplo n.º 17
0
        //funcion para obtener el precio segun el tipo de vehiculo
        public PriceResponse GetPriceByVehicleType(int IdVehicleType)
        {
            Price         myPrice       = db.Price.SingleOrDefault(Price => Price.idVehicleType == IdVehicleType);
            PriceResponse priceResponse = new PriceResponse();

            if (myPrice != null)
            {
                priceResponse.id            = myPrice.id;
                priceResponse.idVehicleType = myPrice.idVehicleType;
                priceResponse.valueMinute   = myPrice.valueMinute;
                priceResponse.valueMonth    = myPrice.valueMonth;

                return(priceResponse);
            }
            return(null);
        }
Exemplo n.º 18
0
        public IActionResult GetPrices(
            [FromRoute][MinLength(3)] string symbol,
            [FromQuery][Required] string range,
            [FromQuery] string interval,
            [FromQuery] DateTime?endTime)
        {
            if (string.IsNullOrEmpty(range) || !_intervals.ContainsKey(range))
            {
                throw new ValidationException("Invalid range specified.");
            }

            if (interval != null)
            {
                if (_intervals.Values.All(value => value != interval))
                {
                    throw new ValidationException("Invalid interval specified.");
                }
            }
            else
            {
                interval = _intervals[range];
            }

            var prices = _sharePriceHistoryProvider.GetPriceHistory(symbol, endTime ?? DateTime.UtcNow, range, interval);

            if (prices == null)
            {
                return(NotFound());
            }

            var response = new PriceResponse
            {
                Range    = range,
                Interval = interval,
                Prices   = prices.Select(p => new Price
                {
                    Timestamp = p.Timestamp,
                    Open      = p.Open,
                    High      = p.High,
                    Low       = p.Low,
                    Close     = p.Close,
                    Volume    = p.Volume
                })
            };

            return(Ok(response));
        }
Exemplo n.º 19
0
        private async Task <GetPriceResponse> HandleInternalAsync(GetPrice request, CancellationToken cancellationToken)
        {
            int[] booksArray   = HandleGetBooksLength(request);
            int[] updatedArray = HandleUpdateArray(booksArray);

            int booksLength = updatedArray.Length;

            if (booksLength == 0)
            {
                PriceResponse singleBookTypePrice = new PriceResponse
                {
                    GBP  = 0m,
                    Euro = 0m,
                };

                return(new GetPriceResponse(singleBookTypePrice));
            }

            int bookValue = updatedArray[0];

            if (booksLength == 1)
            {
                PriceResponse singleBookTypePrice = new PriceResponse
                {
                    GBP  = bookValue * bookPrice,
                    Euro = bookValue * bookPrice * currencyConversionGBPToEuro,
                };

                return(new GetPriceResponse(singleBookTypePrice));
            }
            ;

            List <List <int> > combinations = CalculateCombinations(updatedArray);

            List <decimal> costings = CalculateCostings(combinations);

            decimal lowestPrice = costings.Min();

            PriceResponse prices = new PriceResponse
            {
                GBP  = lowestPrice,
                Euro = lowestPrice * currencyConversionGBPToEuro,
            };

            return(new GetPriceResponse(prices));
        }
        public async Task <CoinPriceResponse> FetchCoinPriceAsync()
        {
            // Fetch preferred coin from in-memory cache
            CoinType preferredCoin = _userRepository.FetchPreferredCoin();

            // Fetch price data from coin
            PriceResponse response = await _coinPriceGateway.FetchCoinPriceAsync(preferredCoin).ConfigureAwait(false);

            // Map and return response
            return(new CoinPriceResponse
            {
                CoinType = preferredCoin,
                Rate = response.Rate,
                Bid = response.Bid,
                Ask = response.Ask
            });
        }
        public async Task <ConversionResponse> Handle(ConversionRequest aConversionRequest, CancellationToken aCancellationToken)
        {
            // TODO when FluentValidation release new version for dotnet core 3 it will support integration into the MVC pipeline.
            // Thus we won't need to manually do this.
            // Or we could add Validation to the Mediator Piple (See ThaiTools)
            ValidationResult validationResult = ConversionRequestValidator.Validate(aConversionRequest);

            if (!validationResult.IsValid)
            {
                throw new ValidationException(validationResult.Errors);
            }

            if (aConversionRequest.FromCurrency == CurrencyCodes.AgldCurrencyCode | aConversionRequest.FromCurrency == CurrencyCodes.AhldCurrencyCode)
            {
                PriceResponse priceResponse = await Mediator.Send(new PriceRequest());

                return(new ConversionResponse
                {
                    Rate = priceResponse.C
                });
            }

            else
            {
                var singleSymbolPriceRequest = new SingleSymbolPriceRequest {
                    fsym = CurrencyCodes.EthCurrencyCode, tsyms = CurrencyCodes.UsdCurrencyCode
                };

                SingleSymbolPriceResponse singleSymbolPriceResponse = await Mediator.Send(singleSymbolPriceRequest);

                decimal value = 0;
                System.Collections.Generic.Dictionary <string, decimal> .ValueCollection values = singleSymbolPriceResponse.Prices.Values;

                foreach (decimal v in values)
                {
                    value = v;
                }
                return(new ConversionResponse
                {
                    Rate = value
                });
            }
        }
Exemplo n.º 22
0
    private IEnumerator OnReceiveCoinUpdate(WWW req, List <string> c)
    {
        yield return(req);

        // Gotta fix the response text
        string fixedReq = string.Format("{0}{1}{2}", "{\"Prices\":", req.text, "}");

        Debug.Log(fixedReq);
        PriceResponse obj = PriceResponse.FromJson(fixedReq);

        int i = 0;

        foreach (CoinPrice cp in obj.prices.Values)
        {
            allCoins.Find(x => x.Symbol == c[i]).Price = cp;
            i++;
        }

        CoinListUpdate();
    }
Exemplo n.º 23
0
        public static PriceResponse ToPriceResponse(this PriceWebServiceResponse1 response)
        {
            var result = new PriceResponse();

            result = new PriceResponse {
                Products = new List <Product>()
            };
            foreach (var product in response.ProductList)
            {
                var p = new Product
                {
                    PartNumber = product.ProductID,
                    Price      = Convert.ToDecimal(product.Price, CultureInfo.InvariantCulture),
                    Currency   = product.Currency
                };
                result.Products.Add(p);
            }

            return(result);
        }
        public override async Task Subscribe(
            PriceRequest request,
            IServerStreamWriter <PriceResponse> responseStream,
            ServerCallContext context
            )
        {
            var i = 0;

            while (true)
            {
                // At every second, keep sending a fake response
                await Task.Delay(TimeSpan.FromSeconds(1));

                var quote = $"Quote#{++i} for {request.Uic}-{request.AssetType}";
                Console.WriteLine($"Sent: {quote}");
                var response = new PriceResponse {
                    Quote = quote
                };
                await responseStream.WriteAsync(response);
            }
        }
Exemplo n.º 25
0
        public ReturnResult SimulationMTGetDeal(string url, PriceRequestBody body)
        {
            ReturnResult result = new ReturnResult
            {
                IsSuccess = false,
            };

            try
            {
                PriceRequest requestData = new PriceRequest
                {
                    partnerId = agentinfo.mt_partnerId,
                    body      = body
                };

                var responseStr = new MeiTuanInter(agentinfo.mt_partnerId, agentinfo.mt_secret, agentinfo.mt_client).DoRequest(url, JsonConvert.SerializeObject(requestData));
                if (string.IsNullOrEmpty(responseStr))
                {
                    result.Message = "返回数据为空";
                }
                else
                {
                    PriceResponse responseBody = (PriceResponse)JsonConvert.DeserializeObject(responseStr, typeof(PriceResponse));
                    if (responseBody.code == 200)
                    {
                        result.IsSuccess = true;
                        result.Message   = JsonConvert.SerializeObject(responseBody);
                    }
                    else
                    {
                        result.Message = responseBody.describe;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "异常" + ex.Message;
            }
            return(result);
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Price([FromHeader] string authorization, [FromBody] PriceRequest request)
        {
            //Get the customerId, stored as a claim in the token
            var customerId = User.Claims.FirstOrDefault(x => x.Type == Constants.UserIdClaim)?.Value;

            //should never happen
            if (string.IsNullOrEmpty(customerId))
            {
                throw new UserIdInvalidException(
                          $"The supplied JSON Web Token does not contain a valid value in the '{ Constants.UserIdClaim }' claim.");
            }

            var calculatedPrice = await
                                  _rideService.CalculatePriceAsync(request.StartAddress, request.EndAddress, request.RideType);

            var response = new PriceResponse
            {
                Price = calculatedPrice
            };

            return(Ok(response));
        }
        public async Task FetchCoinPriceAsync_Success()
        {
            // Arrange
            var fixture            = new Fixture();
            var inputCoinType      = CoinType.ETH;
            var expectedResponse   = fixture.Build <PriceResponse>().Create();
            var mockCointreeClient = new Mock <ICointreeClient>();

            mockCointreeClient.Setup(client => client.GetPriceAsync(inputCoinType)).ReturnsAsync(expectedResponse);

            fixture.Register(() => mockCointreeClient.Object);

            var target = fixture.Create <CoinPriceGateway>();

            // Act
            PriceResponse actual = await target.FetchCoinPriceAsync(inputCoinType);

            // Assert
            Assert.Equal(expectedResponse, actual); // expect same instance to return

            mockCointreeClient.Verify(client => client.GetPriceAsync(inputCoinType), Times.Once);
            mockCointreeClient.VerifyNoOtherCalls();
        }
Exemplo n.º 28
0
        private async void CalculatePriceCommandExecuteAsync()
        {
            CalculatePriceRequest request = new CalculatePriceRequest(Request);

            IsBusy = true;
            PriceResponse response = await _backendApiService.SubmitCalculatePriceRequest(request);

            IsBusy = false;


            if (response == null)
            {
                await DialogService.DisplayAlertAsync("Forbindelse",
                                                      "Pris kunne ikke beregnes - ingen internetforbindelse", "OK");
            }
            else if (response.WasUnsuccessfull())
            {
                await DialogService.DisplayAlertAsync("Ukendt fejl", "Prisen for turen kunne ikke beregnes", "OK");
            }
            else if (response.WasSuccessfull())
            {
                Price = response.Body.Price;
            }
        }
        private void handleResponseEvent(Event eventObj, IList <PriceResponse> prices)
        {
            Debug.WriteLine("EventType = " + eventObj.Type);
            foreach (Message message in eventObj.GetMessages())
            {
                Debug.WriteLine("correlationID= " + message.CorrelationID);
                Debug.WriteLine("messageType = " + message.MessageType);

                Element elmSecurityData = message["securityData"];

                Element elmSecurity = elmSecurityData["security"];
                string  security    = elmSecurity.GetValueAsString();
                Debug.WriteLine(security);

                if (elmSecurityData.HasElement("securityError", true))
                {
                    Element elmSecError  = elmSecurityData["securityError"];
                    string  source       = elmSecError.GetElementAsString("source");
                    int     code         = elmSecError.GetElementAsInt32("code");
                    string  category     = elmSecError.GetElementAsString("category");
                    string  errorMessage = elmSecError.GetElementAsString("message");
                    string  subCategory  = elmSecError.GetElementAsString("subcategory");
                }
                else
                {
                    bool hasFieldErrors = elmSecurityData.HasElement("fieldExceptions", true);
                    if (hasFieldErrors)
                    {
                        Element elmFieldErrors = elmSecurityData["fieldExceptions"];
                        for (int errorIndex = 0; errorIndex < elmFieldErrors.NumValues; errorIndex++)
                        {
                            Element fieldError = elmFieldErrors.GetValueAsElement(errorIndex);
                            string  fieldId    = fieldError.GetElementAsString("fieldId");

                            Element errorInfo   = fieldError["errorInfo"];
                            string  source      = errorInfo.GetElementAsString("source");
                            int     code        = errorInfo.GetElementAsInt32("code");
                            string  category    = errorInfo.GetElementAsString("category");
                            string  strMessage  = errorInfo.GetElementAsString("message");
                            string  subCategory = errorInfo.GetElementAsString("subcategory");
                        }
                    }

                    Element elmFieldData = elmSecurityData["fieldData"];
                    for (int valueIndex = 0; valueIndex < elmFieldData.NumValues; valueIndex++)
                    {
                        Element  elmValues = elmFieldData.GetValueAsElement(valueIndex);
                        DateTime date      = elmValues.GetElementAsDate("date").ToSystemDateTime();

                        //You can use either a Name or a string to get elements.
                        double bid = elmValues.GetElementAsFloat64("BID");
                        double ask = elmValues.GetElementAsFloat64("ASK");

                        var price = new PriceResponse(security, ask, bid, date);

                        Debug.WriteLine($"{date:yyyy-MM-dd}: BID = {bid}, ASK = {ask}");

                        prices.Add(price);
                    }
                }
            }
        }
        public void SetUp()
        {
            _fakeBackendApiService = Substitute.For <IBackendApiService>();
            _fakeNavigationService = Substitute.For <INavigationService>();
            _fakePageDialogService = Substitute.For <IPageDialogService>();
            _uut = new CreateRideViewModel(_fakeNavigationService, _fakePageDialogService, _fakeBackendApiService);


            _priceResponseOk = new PriceResponse(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(new
                {
                    price = 100.00,
                }), Encoding.UTF8, "application/json"),
            });

            _priceResponseBadRequest = new PriceResponse(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content    = new StringContent(JsonConvert.SerializeObject(new
                {
                    errors = new Dictionary <string, IList <string> >()
                    {
                        { "error", new List <string> {
                              "The address is not valid"
                          } }
                    },
                }), Encoding.UTF8, "application/json"),
            });

            _rideResponseOk = new CreateRideResponse(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(new
                {
                    id = 1,
                    startDestination     = new { cityName = "Test", postalCode = 1234, streetName = "Tester", streetNumber = 1 },
                    endDestination       = new { cityName = "Tester", postalCode = 4321, streetName = "Test", streetNumber = 2 },
                    departureTime        = DateTime.Now.Add(new TimeSpan(0, 0, 30)),
                    confirmationDeadline = DateTime.Now.Subtract(new TimeSpan(0, 2, 0)),
                    passengerCount       = 1,
                    createdOn            = DateTime.Now,
                    price  = 100,
                    status = 0,
                }), Encoding.UTF8, "application/json"),
            });

            _rideResponseBadRequest = new CreateRideResponse(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content    = new StringContent(JsonConvert.SerializeObject(new
                {
                    errors = new Dictionary <string, IList <string> >()
                    {
                        { "error", new List <string> {
                              "Not enough money"
                          } }
                    },
                }), Encoding.UTF8, "application/json"),
            });
        }