private ValCurs ParseXmlToValCurs(string xml)
        {
            ValCurs   result  = new ValCurs();
            XDocument srcTree = XDocument.Parse(xml);

            result.Date    = (string)srcTree.Element("ValCurs").Attribute("Date").Value;
            result.Name    = (string)srcTree.Element("ValCurs").Attribute("name").Value;
            result.Valutes = new List <Valute>();

            foreach (var item in srcTree.Descendants("Valute"))
            {
                Valute valute = new Valute();

                valute.ID       = (string)item.Attribute("ID").Value;
                valute.NumCode  = int.Parse(item.Element("NumCode").Value);
                valute.CharCode = (string)item.Element("CharCode").Value;
                valute.Nominal  = int.Parse(item.Element("Nominal").Value);
                valute.Name     = (string)item.Element("Name").Value;
                valute.Value    = (float)Convert.ToDouble(item.Element("Value").Value);

                result.Valutes.Add(valute);
            }

            return(result);
        }
Example #2
0
        public async Task <IActionResult> Index()
        {
            try
            {
                string URL = "https://www.cbr-xml-daily.ru/daily_eng.xml";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    string responseString;
                    using (Stream stream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        responseString = reader.ReadToEnd();
                        XmlSerializer serializer = new XmlSerializer(typeof(ValCurs));
                        curs = (ValCurs)serializer.Deserialize(new StringReader(responseString));
                    }
                }
                return(View(curs.Valute));
            }
            catch (WebException ex)
            {
                ViewData["Exception"] = "На сервере возникла ошибка!";
                return(View());
            }
            catch (Exception ex)
            {
                ViewData["Exception"] = "На сервере возникла ошибка!";
                return(View());
            }
        }
Example #3
0
 public ValCurs LoadCursFromCbrByDate(DateTime dateTime, string valutaCode)
 {
     try
     {
         var       xml    = client.DownloadString("http://www.cbr.ru/scripts/XML_daily.asp?date_req=" + dateTime.ToString("dd.MM.yyyy"));
         XDocument xdoc   = XDocument.Parse(xml);
         var       el     = xdoc.Element("ValCurs").Elements("Valute").Where(x => x.Attribute("ID").Value == valutaCode);
         Valuta    valuta = GetValuteByCode(valutaCode);
         if (valuta != null)
         {
             ValCurs valCurs = new ValCurs
             {
                 CursDate = dateTime,
                 Value    = Convert.ToDecimal(el.Elements("Value").FirstOrDefault().Value),
                 ValutaId = valuta.Id
             };
             context.Entry(valCurs).State = EntityState.Added;
             context.SaveChanges();
             return(valCurs);
         }
         return(null);
     }
     catch
     {
         return(null);
     }
 }
Example #4
0
        public async Task <ActionResult <List <Chart> > > Post([FromBody] SamplingParameters query)
        {
            Dictionary <string, string> currencies = new Dictionary <string, string>
            {
                { "Доллар США", "R01235" },
                { "Евро", "R01239" }
            };

            Task[]  tasks    = new Task[2];
            ValCurs valCurs1 = null;
            ValCurs valCurs2 = null;

            tasks[0]           = Task.Factory.StartNew(
                () => valCurs1 = _requestToCbr
                                 .GetCurs(query.DateBegin, query.DateEnd, currencies["Доллар США"]));
            tasks[1]           = Task.Factory.StartNew(
                () => valCurs2 = _requestToCbr
                                 .GetCurs(query.DateBegin, query.DateEnd, currencies["Евро"]));
            List <Chart> charts = new List <Chart>();
            await Task.Factory.ContinueWhenAll(tasks, completedTasks =>
            {
                var minVal = valCurs1.Record == null || valCurs2.Record == null
                    ? "50"
                    : valCurs1.Record.Concat(valCurs2.Record).Select(valCursRecord => valCursRecord.Value).Min();
                charts.Add(_chartFactory.GetChart(valCurs1, minVal, currencies.ElementAt(0).Key));
                charts.Add(_chartFactory.GetChart(valCurs2, minVal, currencies.ElementAt(1).Key));
            });

            return(new ObjectResult(charts));
        }
Example #5
0
 private void LogCurs(ValCurs curs)
 {
     _logger.LogInformation($"Response has:{Environment.NewLine}" +
                            $"date - [{curs.Date}]{Environment.NewLine}" +
                            $"name - [{curs.Name}]{Environment.NewLine}" +
                            $"row count - [{curs?.Valute?.Count() ?? -1}]");
 }
        public void UpdateCurrency(ValCurs Currency)
        {
            foreach (var item in Currency.ValType[1].Valute)
            {
                switch (item.Code)
                {
                case "USD":
                    bo.SetCurrencyRate("USD", DateTime.Now, Convert.ToDouble(item.Value), true);
                    break;

                case "DKK":
                    bo.SetCurrencyRate("DKK", DateTime.Now, Convert.ToDouble(item.Value), true);
                    break;

                case "EUR":
                    bo.SetCurrencyRate("EUR", DateTime.Now, Convert.ToDouble(item.Value), true);
                    break;

                case "GPB":
                    bo.SetCurrencyRate("GPB", DateTime.Now, Convert.ToDouble(item.Value), true);
                    break;

                case "SEK":
                    bo.SetCurrencyRate("SEK", DateTime.Now, Convert.ToDouble(item.Value), true);
                    break;
                }
            }
        }
Example #7
0
     public Chart GetChart(ValCurs valCurs, string minVal, string title)
     {
         if (valCurs?.Record != null)
         {
             return new Chart
                    {
                        YValues = JsonConvert.SerializeObject(
                            valCurs.Record.Select(valCursRecord => valCursRecord.Value).ToList()
                            ),
                        XLabels = JsonConvert.SerializeObject(
                            valCurs.Record.Select(valCursRecord => valCursRecord.Date).ToList()
                            ),
                        MinYValues = minVal,
                        Title      = title
                    }
         }
         ;
         return(new Chart
         {
             YValues = "[\"0,0\"]",
             XLabels = "[]",
             MinYValues = minVal,
             Title = title
         });
     }
 }
Example #8
0
        private static Task <List <Currency> > Parse(ValCurs toparse)
        {
            var result = toparse.Valute.Select(currency => new Currency
            {
                Name = currency.CharCode, Rate = decimal.Parse(currency.Value) / currency.Nominal
            }).ToList();

            return(Task.FromResult(result));
        }
Example #9
0
        public async Task <ValCurs> RequestCursAsync(CancellationToken cancellationToken)
        {
            ValCurs curs = null;

            foreach (int i in Enumerable.Range(0, _configuration.GetRetryRequestCount()))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(null);
                }

                await using Stream responseStream
                                = await _web.RequestNewCurrencyAsync(DateTime.Now).ConfigureAwait(false);

                if (responseStream is null)
                {
                    try
                    {
                        _logger.LogInformation("Wait request timeout");
                        await Task.Delay(_configuration.GetRetryRequestWaitTime(),
                                         cancellationToken);

                        _logger.LogInformation("Request timeout end");

                        continue;
                    }
                    catch (TaskCanceledException)
                    {
                        return(null);
                    }
                }

                curs = await _parser.ParseCursAsync(responseStream).ConfigureAwait(false);

                if (curs is null)
                {
                    try
                    {
                        _logger.LogInformation("Wait parse timeout");
                        await Task.Delay(_configuration.GetRetryRequestWaitTime(),
                                         cancellationToken);

                        _logger.LogInformation("Parse timeout end");

                        continue;
                    }
                    catch (TaskCanceledException)
                    {
                        return(null);
                    }
                }

                break;
            }

            return(curs);
        }
Example #10
0
        private async Task Worker(CancellationToken cancellationToken)
        {
            try
            {
                _workSignal.Wait(cancellationToken);

                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        ValCurs curs = await RequestCursAsync(cancellationToken).ConfigureAwait(false);

                        if (curs is null)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                break;
                            }

                            _logger.LogError($"Service cant get exchange rates");
                            throw new ExchangeRateRequestException("Service cant get exchange rates");
                        }

                        bool dBWriteState = await SaveCursAsync(curs, cancellationToken);

                        if (!dBWriteState)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                break;
                            }

                            _logger.LogError($"Service cant store exchange rates");
                            throw new ExchangeRateRequestException("Service cant store exchange rates");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"Loading fail. Skip. {ex}");
                    }
                    finally
                    {
                        _workSignal.Reset();
                        _workSignal.Wait(cancellationToken);
                    }
                }

                _logger.LogInformation("Work thread stopped");
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something wrong in service work thread: {ex}");
            }
        }
Example #11
0
        public decimal GetValCursByDate(DateTime dateTime, string valutaCode)
        {
            ValCurs valCurs = context.ValCurs.Where(v => v.CursDate == dateTime).Where(v => v.Valuta.Code == valutaCode).FirstOrDefault();

            if (valCurs == null)
            {
                valCurs = LoadCursFromCbrByDate(dateTime, valutaCode);
            }
            if (valCurs != null)
            {
                return(valCurs.Value);
            }
            return(0);
        }
Example #12
0
        public async Task ParseResponse_Bad_Test()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            ILogger <ResponseParser> logger = SU.GetLogger <ResponseParser>();

            ResponseParser parser = new ResponseParser(logger);

            await using FileStream testResponse = SU.GetFileStream(@".\TestData\ResponseBad.xml");

            ValCurs curs = await parser.ParseCursAsync(testResponse);

            Assert.Null(curs);
        }
Example #13
0
        private static decimal ConvertToRub(decimal value, string currency, ValCurs data)
        {
            if (currency == DefaultValues.APICurrency)
            {
                return(value);
            }

            // asked currency info
            var instance = data.Valute.First(v => v.CharCode == currency);

            // how many rubles one value of this currency contains (e.g one dollar - 20 rubles, oneInRub = 20)
            var oneInRub = Decimal.Parse(instance.Value, DecimalFormatInfo) / instance.Nominal;

            // 5 dollars, oneDollarInRub = 20, return 20 * 5 = 100 rubs
            return(oneInRub * value);
        }
Example #14
0
        private ValCurs GetVAlCur(string date)
        {
            string url = $"https://www.cbar.az/currencies/{date}.xml";

            HttpClient clicent = new HttpClient();

            ValCurs myVAlCurs  = new ValCurs();
            Stream  fileStream = clicent.GetAsync(url).GetAwaiter().GetResult().Content.ReadAsStreamAsync().GetAwaiter().GetResult();

            using (fileStream)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ValCurs));
                myVAlCurs = (ValCurs)serializer.Deserialize(fileStream);
            }
            return(myVAlCurs);
        }
Example #15
0
        public async Task <ActionResult> GetCurrencyRate(string id)
        {
            try
            {
                var currencyRate    = new CurrencyRate();
                var valCurs         = new ValCurs();
                var currencyRateXml = new XmlDocument();

                var dateReq1 = DateTime.Now.AddYears(-1).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
                var dateReq2 = DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

                var response = await httpClient.GetAsync("XML_dynamic.asp?date_req1=" + dateReq1 + "&date_req2=" + dateReq2 + "&VAL_NM_RQ=" + id);

                if (response.StatusCode.GetHashCode() == 200)
                {
                    currencyRateXml.LoadXml(await response.Content.ReadAsStringAsync());
                    valCurs = xmlHelper.DeSerializeXmlToObject <ValCurs>(currencyRateXml);
                }

                if (valCurs.Record.Count == 0)
                {
                    return(Json(new { success = false, responseText = "Для выбранной валюты нет данных!" }, JsonRequestBehavior.AllowGet));
                }

                currencyRate.FaceValue = valCurs.Record[0].Nominal;
                currencyRate.Rate      = new double[valCurs.Record.Count, 2];

                for (int i = 0; i < valCurs.Record.Count; i++)
                {
                    var myDate = DateTime.Parse(valCurs.Record[i].Date);
                    var epoch  = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    var data   = (myDate - epoch).TotalMilliseconds;

                    currencyRate.Rate[i, 0] = data;
                    currencyRate.Rate[i, 1] = double.Parse(valCurs.Record[i].Value);
                }

                return(Json(new { success = true, CurrencyRate = JsonConvert.SerializeObject(currencyRate) }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Logger.SetLog(-1, ex.StackTrace);
                return(Json(new { success = false, responseText = "При получении данных произошла ошибка!" }, JsonRequestBehavior.AllowGet));
            }
        }
Example #16
0
        public string Get(string id)
        {
            string  retStr = "1 RUB-";
            var     ser    = new Serialize();
            ValCurs quiz   = ser.DeSerialize <ValCurs>(SendRequest("http://www.cbr.ru/scripts/XML_daily.asp"));

            if (quiz.Valute.Any(x => x.CharCode == id.ToUpper()))
            {
                var item = Convert.ToDouble(quiz.Valute.FirstOrDefault(x => x.CharCode == id.ToUpper()).Value);
                var rate = Math.Round(1 / item, 4);
                retStr += rate.ToString() + " " +
                          id;
                return(retStr);
            }
            else
            {
                return("Валюта " + id.ToUpper() + " с таким кодом не найден в");
            }
        }
        public void GetCurrency()
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.cbar.az/currencies/03.12.2020.xml");

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(ValCurs));
                        using (TextReader reader1 = new StringReader(reader.ReadToEnd()))
                        {
                            Currency = (ValCurs)serializer.Deserialize(reader1);
                            UpdateDb.UpdateCurrency(Currency);
                        }
                    }
                }
        }
Example #18
0
        /// <summary>
        /// Сохраняет курсы валют в базу данных
        /// </summary>
        /// <param name="curs">Курсы валют который неободимо сохранить в базу</param>
        /// <returns></returns>
        public async Task <bool> StoreCurrencyAsync(ValCurs curs)
        {
            try
            {
                _logger.LogInformation($"{nameof(DbWorker)} start");

                if (curs is null)
                {
                    throw  new NullReferenceException($"{nameof(curs)} is null");
                }

                if (_dbContext.ExchangeRates.Where(valute => valute.ExchangeRateDate == curs.Date).Any())
                {
                    throw new ExchangeRatesSaveException($"Valute already save today. We dont know how to save new value");
                }

                curs.Valute.ForEach(valute
                                    => _dbContext.ExchangeRates.AddAsync(new ExchangeRates()
                {
                    ExchangeRateDate = curs.Date,
                    Name             = valute.Name,
                    CharCode         = valute.CharCode,
                    Nominal          = valute.Nominal,
                    Value            = valute.Value
                }));

                await _dbContext.SaveChangesAsync();

                _logger.LogInformation($"{nameof(DbWorker)} done");
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Cant store in db: {ex}");
                return(false);
            }
        }
Example #19
0
        public async Task <bool> SaveCursAsync(ValCurs curs, CancellationToken cancellationToken)
        {
            bool dBWriteState = false;

            foreach (int i in Enumerable.Range(0, _configuration.GetRetryStoreCurrencyCount()))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                dBWriteState = await _db.StoreCurrencyAsync(curs).ConfigureAwait(false);

                if (!dBWriteState)
                {
                    try
                    {
                        _logger.LogInformation("Wait db save timeout");
                        await Task.Delay(_configuration.GetRetryStoreCurrencyWaitTime(),
                                         cancellationToken);

                        _logger.LogInformation("DB timeout end");

                        continue;
                    }
                    catch (TaskCanceledException)
                    {
                        return(false);
                    }
                }

                break;
            }

            return(dBWriteState);
        }
Example #20
0
        /// <summary>
        /// Десериализует Stream с xml ответом
        /// </summary>
        /// <param name="responseData">Разбираемые даннные в XML формате</param>
        /// <returns></returns>
        public async Task <ValCurs> ParseCursAsync(Stream responseData)
        {
            if (responseData is null)
            {
                throw new NullReferenceException($"{nameof(responseData)} is null");
            }

            try
            {
                _logger.LogInformation($"{nameof(ResponseParser)} start");

                XmlSerializer formatter = new XmlSerializer(typeof(ValCurs));

                using StreamReader responseReader = new StreamReader(responseData, Encoding.GetEncoding(1251));
                string response = await responseReader.ReadToEndAsync().ConfigureAwait(false);

#if DEBUG
                _logger.LogInformation(response);
#endif

                // Можно сразу читать стрим, но тогда не выйдет логгировать ответ. Стрим не поддерживает Seek
                StringReader responseStringReader = new StringReader(response);
                ValCurs      curs = (ValCurs)formatter.Deserialize(responseStringReader);

                LogCurs(curs);

                _logger.LogInformation($"{nameof(ResponseParser)} done");

                return(curs);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Cant parse data - {ex}");
                return(null);
            }
        }
Example #21
0
        public async Task <IActionResult> GetQuotes(DateTime date)
        {
            ValCurs res = await dataService.GetValute(date);

            return(Ok(res));
        }
 public async Task Get()
 {
     _valCurs = await GetAsync(_address);
 }
Example #23
0
        public static async Task <IList <KeyValuePair <CurrencyEmoji, decimal> > > GetCurrenciesValuesAsync(decimal value, CurrencyEmoji valueCurrencyEmoji, ValCurs data, IEnumerable <CurrencyEmoji> neededCurrencies)
        {
            return(await Task.Run(() =>
            {
                var currency = valueCurrencyEmoji.Currency;

                var rub = ConvertToRub(value, currency, data); // whatever currency the value is, it is processed as rub

                var currencies = new List <KeyValuePair <ValCursValute, CurrencyEmoji> >(neededCurrencies.Count());

                foreach (var i in data.Valute)
                {
                    foreach (var j in neededCurrencies)
                    {
                        if (i.CharCode == j.Currency)
                        {
                            currencies.Add(new KeyValuePair <ValCursValute, CurrencyEmoji>(i, j));
                        }
                    }
                }

                var result = currencies.Select(
                    i =>
                {
                    var(valute, currencyEmoji) = i;

                    return new KeyValuePair <CurrencyEmoji, decimal>(
                        currencyEmoji,
                        rub / (decimal.Parse(valute.Value, DecimalFormatInfo) / valute.Nominal)
                        );
                }
                    ).ToList();

                var rubEmoji = neededCurrencies.FirstOrDefault(ce => ce.Currency == DefaultValues.APICurrency);

                if (rubEmoji != null)
                {
                    result
                    .Add(new KeyValuePair <CurrencyEmoji, decimal>(rubEmoji, rub));
                }

                if (!result.Any(el => el.Key.Emoji == valueCurrencyEmoji.Emoji))
                {
                    result.Add(new KeyValuePair <CurrencyEmoji, decimal>(valueCurrencyEmoji, value));
                }

                return result;
            }));
        }
Example #24
0
        private static async Task CacheTodayAsync()
        {
            Data = await CurrenciesProcessor.LoadValCursAsync();

            LastCachedDate = DateTimeZones.NowMoscow;
        }