Ejemplo n.º 1
0
        ////////////
        public HistoryConvert AddItemHistory(HistoryConvert model)
        {
            Currency  currentCurrency = _convertContext.currencies.Where(x => x.Id.Equals(model.FromCurrencyId)).FirstOrDefault();
            Currency  finishcurrency  = _convertContext.currencies.Where(x => x.Id.Equals(model.ToCurrencyId)).FirstOrDefault();
            string    jsonpathfrom    = "https://api.exchangeratesapi.io/latest?base=" + currentCurrency.CurrencyName;
            WebClient web             = new WebClient();
            Stream    stream          = web.OpenRead(jsonpathfrom);
            string    jsonconfiguration;

            using (var reader = new StreamReader(stream))
            {
                jsonconfiguration = reader.ReadToEnd();
            }

            decimal requiredCoefficient;
            Root    result = JsonConvert.DeserializeObject <Root>(jsonconfiguration);
            var     jo     = JObject.Parse(jsonconfiguration).SelectToken("rates").ToObject <Dictionary <string, decimal> >();

            foreach (KeyValuePair <string, decimal> item in jo)
            {
                if (item.Key == finishcurrency.CurrencyName)
                {
                    requiredCoefficient = item.Value;
                    model.ToAmount      = model.FromAmount * requiredCoefficient;
                    try
                    {
                        _convertContext.Add(model);
                        _convertContext.SaveChanges();
                    }
                    catch (System.Exception)
                    {
                        return(null);
                    }
                }
            }
            return(model);
        }