/// <summary> /// converts currencies from one type to another /// </summary> /// <param name="fromCurrency">code of source currency</param> /// <param name="toCurrency">code of destination currency</param> /// <returns>returns the ratio SRC/DST </returns> public async Task <double> ConvertAsync(string fromCurrency, string toCurrency) { HistoricalCurrencyEntity currentInfo = (await new Dal().GetTimeSpanCurrency(1)).FirstOrDefault(); //Gilad - was get by day double from = 1 / currentInfo.GetValue(fromCurrency); // 1/(USD/from) = from/USD double to = currentInfo.GetValue(toCurrency); //USD/to return(from * to); // from/USD * USD/to = from/to }
/// <summary> /// another async layer to make sure nothing gets stuck <see cref="UpdateDataBaseAsync"/> /// </summary> private async Task _updateDataBaseAsync(DateTime start, DateTime finish, bool force) { using (var ctx = new CurrencyContext()) { DateTime checkStart = start.Date; //make sure requested date is not later than the latest downloaded because //it is assumed that everything is updated until the latest date available if (!force) //if we should only update what is necessary { checkStart = DateTime.Parse((from hc in ctx.HistoricalCurrency select hc.date).ToList().LastOrDefault()).AddDays(1); //latest update to the database } if (start < checkStart) { start = checkStart; //make sure everything is updated until latest available } Task <string>[] taskList = new Task <string> [(finish - start).Days + 1]; for (int i = 0; start <= finish; i++, start = start.AddDays(1)) //each day in date range { string parsedDate = ParseDate(start); taskList[i] = Task <string> .Factory.StartNew(() => {//real concurrency! string jsonData = ""; using (var wc = new WebClient()) { for (int j = 0; j < 4; j++) //try 4 times { try { //we calculate url here so we get a new key each time string url = @"http://apilayer.net/api/historical?access_key=" + GetKey() + "&date=" + parsedDate + @"¤cies=EUR,GBP,ILS,BTC,JMD&format=1"; jsonData = wc.DownloadString(url); if (jsonData.Contains("success\":true"))//CurrencyClayer's way of saying good { break; } } catch (Exception e) { Console.WriteLine(e.Message); } } } return(jsonData); }); } Task.WaitAll(taskList);//wait for all of the threads to finish foreach (var item in taskList) { if (item.Result == "") { continue; //something went wrong } HistoricalCurrencyEntity entity = JsonConvert.DeserializeObject <HistoricalCurrencyEntity>(item.Result); if (!ctx.HistoricalCurrency.Any(e => e.date == entity.date)) //only add if it's not saved already { ctx.HistoricalCurrency.Add(entity); } } await ctx.SaveChangesAsync(); } }