summaryrefslogtreecommitdiff
path: root/Services/CurrencyClient.cs
blob: dd7fd2e4bfd8a88851ca3a63f18174ef453ccadb (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
using System.Diagnostics;
using System.Text;
using System.Xml.Linq;

namespace ExcelAddIn.Services;

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

	public CurrencyClient(HttpClient httpClient)
	{
		_httpClient = httpClient;
	}

	public async Task<decimal?> GetExchangeRate(DateTime date)
	{
		string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
		
		HttpResponseMessage response = await _httpClient.GetAsync(request);
		try
		{
			response.EnsureSuccessStatusCode();
			var bytes = await response.Content.ReadAsByteArrayAsync();
			var xml = Encoding.GetEncoding(1251).GetString(bytes);
			
			XElement valCourses = XElement.Parse(xml);

			decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
				.Where(e => e.Element("Name").Value == "Евро")
				.FirstOrDefault()
				.Element("Value").Value);
			return exchangeRate;
		}
		catch (Exception ex)
		{
			Debug.WriteLine(ex.Message);
			return null;
		}
	}
}