Example #1
0
        public async Task UpdateBYNVoid()
        {
            Currency baseCurrency = await _context.Currency.Where(x => x.Code == Constants.BYNCode).SingleOrDefaultAsync();

            var    currencyList = _context.Currency.Where(x => x.Code != Constants.BYNCode && x.Active);
            string jsonCurList  = await ServicesCommonFunctions.SendGetRequestAsync(new Uri(Constants.BYN_CURRENCY_LIST_URL));

            DataContractJsonSerializer jsonFormatterNBRBCurAr = new DataContractJsonSerializer(typeof(NbrbCur[]));
            DataContractJsonSerializer jsonFormatterNBRBRate  = new DataContractJsonSerializer(typeof(NbrbRate));

            NbrbCur[] curArray   = (NbrbCur[])jsonFormatterNBRBCurAr.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(jsonCurList)));
            var       addedRates = new List <CurrencyRates>();

            foreach (var currency in currencyList)
            {
                for (var currencyDate = Constants.baseDate; currencyDate <= DateTime.Today; currencyDate = currencyDate.AddDays(1))
                {
                    if (await _context.CurrencyRates.Where(x => x.DateRate == currencyDate && x.Currency.Code == currency.Code).SingleOrDefaultAsync() != null)
                    {
                        continue;
                    }

                    var curNBRB = curArray.SingleOrDefault(x => x.Cur_Abbreviation == currency.Code &&
                                                           DateTime.Parse(x.Cur_DateStart) <= currencyDate &&
                                                           DateTime.Parse(x.Cur_DateEnd) >= currencyDate
                                                           );

                    if (curNBRB == null)
                    {
                        continue;
                    }

                    string urlRate  = Constants.BYN_CURRENCY_RATE_URL + curNBRB.Cur_ID + Constants.BYN_ATTR_DATE + currencyDate;
                    string jsonRate = await ServicesCommonFunctions.SendGetRequestAsync(new Uri(urlRate));

                    NbrbRate      curRate      = jsonFormatterNBRBRate.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(jsonRate))) as NbrbRate;
                    CurrencyRates currencyRate = new CurrencyRates
                    {
                        BaseCurrencyId = baseCurrency.Id,
                        CurrencyId     = currency.Id,
                        DateRate       = currencyDate,
                        CurrecyScale   = curRate.Cur_Scale,
                        CurrencyRate   = (decimal)curRate.Cur_OfficialRate
                    };
                    addedRates.Add(currencyRate);
                }
            }
            if (addedRates.Count > 0)
            {
                await _context.AddRangeAsync(addedRates);

                await _context.SaveChangesAsync();
            }
        }