RhSolutions-AddIn/RhSolutions.AddIn/Services/CurrencyClient.cs

50 lines
1.8 KiB
C#
Raw Permalink Normal View History

2024-01-18 23:16:27 +03:00
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
{
2023-05-16 07:43:57 +03:00
private readonly HttpClient _httpClient;
2024-01-18 23:16:27 +03:00
private readonly IMemoryCache _memoryCache;
private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req=";
public HttpStatusCode StatusCode { get; private set; }
2024-01-18 23:16:27 +03:00
public CurrencyClient(HttpClient httpClient, IMemoryCache memoryCache)
{
2023-05-16 07:43:57 +03:00
_httpClient = httpClient;
2024-01-18 23:16:27 +03:00
_memoryCache = memoryCache;
}
2023-06-09 14:49:20 +03:00
public async Task<decimal?> GetExchangeRate(DateTime date)
{
2024-01-18 23:16:27 +03:00
if (!_memoryCache.TryGetValue(date, out decimal exchangeRate))
{
2024-01-18 23:16:27 +03:00
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;
}
2023-05-16 07:43:57 +03:00
}
2024-01-18 23:16:27 +03:00
return exchangeRate;
}
}