aboutsummaryrefslogtreecommitdiff
path: root/RhSolutions.AddIn/Services/CurrencyClient.cs
blob: f71d55a06f1a4976061dff1c7167021d8d3ef335 (plain)
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
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace RhSolutions.Services;

public class CurrencyClient : ICurrencyClient
{
    private readonly HttpClient _httpClient;
    private readonly IMemoryCache _memoryCache;
    private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req=";
    public HttpStatusCode StatusCode { get; private set; }

    public CurrencyClient(HttpClient httpClient, IMemoryCache memoryCache)
    {
        _httpClient = httpClient;
        _memoryCache = memoryCache;
    }

    public async Task<decimal?> GetExchangeRate(DateTime date)
    {
        if (!_memoryCache.TryGetValue(date, out decimal exchangeRate))
        {
            string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
            HttpResponseMessage response = await _httpClient.GetAsync(request);
            try
            {
                response.EnsureSuccessStatusCode();
                string xml = await response.Content.ReadAsStringAsync();
                XElement valCourses = XElement.Parse(xml);
                exchangeRate = decimal.Parse(valCourses.Elements("Valute")
                    .Where(e => e.Element("Name").Value == "Евро")
                    .FirstOrDefault()
                    .Element("Value").Value);
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromHours(1));
                _memoryCache.Set(date, exchangeRate, cacheEntryOptions);
                return exchangeRate;
            }
            catch
            {
                StatusCode = response.StatusCode;
                return null;
            }
        }
        return exchangeRate;        
    }
}