-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExchangeRatesUpdateJob.cs
82 lines (71 loc) · 3.12 KB
/
ExchangeRatesUpdateJob.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
[ScheduledPlugIn(
DisplayName = "Exchange Rates update job",
Description = "This job update exchange rates.")]
public class ExchangeRatesUpdateJob : ScheduledJobBase
{
[NonSerialized]
private static readonly ILogger _log = LogManager.GetLogger(typeof(ExchangeRatesUpdateJob));
public override string Execute()
{
string message = string.Empty;
int records = UpdateExchangeRate(out message);
return $"{records.ToString()} currencies were updated. {message}. Exchange Rate update Job was finished.";
}
private static int UpdateExchangeRate(out string message)
{
message = string.Empty;
_log.Information("Starting to update exchange rate job.");
var processedCurrency = 0;
var dto = CurrencyManager.GetCurrencyDto();
var currencyCodeIdMapping = dto.Currency.ToDictionary(c => c.CurrencyCode, c => c.CurrencyId);
try
{
foreach (var code in currencyCodeIdMapping.Keys)
{
int fromCurrencyId;
currencyCodeIdMapping.TryGetValue(code, out fromCurrencyId);
try
{
var uri = $"http://api.fixer.io/latest?base={code}";
using (var client = new WebClient())
{
var json = client.DownloadString(uri);
dynamic d = JObject.Parse(json);
DateTime exchangeDate = d.date;
foreach (var rate in d.rates)
{
string toCurrencyCode = rate.Name;
int toCurrencyId;
if (currencyCodeIdMapping.TryGetValue(toCurrencyCode, out toCurrencyId))
{
var currencyRate = dto.CurrencyRate.NewCurrencyRateRow();
currencyRate.FromCurrencyId = fromCurrencyId;
currencyRate.ToCurrencyId = toCurrencyId;
currencyRate.EndOfDayRate = currencyRate.AverageRate = rate.Value;
currencyRate.CurrencyRateDate = exchangeDate;
currencyRate.ModifiedDate = DateTime.Now;
dto.CurrencyRate.AddCurrencyRateRow(currencyRate);
currencyRate.AcceptChanges();
}
}
dto.CurrencyRate.AcceptChanges();
}
}
catch (Exception ex)
{
message += "Cannot update currency {code}. ";
_log.Error("Cannot update currency {code}.", ex);
continue;
}
dto.AcceptChanges();
processedCurrency++;
_log.Information($"{code} rates were updated");
}
}
catch (Exception ex)
{
_log.Error("The job could not be completed. ", ex);
}
return processedCurrency;
}
}