Compare commits

...

3 Commits

Author SHA1 Message Date
Sergey Chebotar
213592b9e2 Check cache for currency rate before run async util 2023-06-08 07:47:14 +03:00
Sergey Chebotar
1399d71f3c Switch Currency client from transient to singleton 2023-06-08 07:43:49 +03:00
Sergey Chebotar
bfab7eb02b Edit caller function names 2023-06-08 06:44:11 +03:00
3 changed files with 47 additions and 51 deletions

View File

@ -24,7 +24,7 @@ public sealed class RhSolutionsAddIn : IExcelAddIn
.AddSingleton((Application)ExcelDnaUtil.Application)
.AddSingleton<IAddInConfiguration, AddInConfiguration>()
.AddSingleton<IDatabaseClient, DatabaseClient>()
.AddTransient<ICurrencyClient, CurrencyClient>()
.AddSingleton<ICurrencyClient, CurrencyClient>()
.AddTransient<IFileDialog, FileDialog>();
Services.AddSingleton<WriterFactory>();

View File

@ -2,12 +2,14 @@
using System.Runtime.Versioning;
#endif
using Microsoft.Extensions.Caching.Memory;
namespace RhSolutions.AddIn;
#if !NET472
[SupportedOSPlatform("windows")]
#endif
public class RhSolutionsFunction
public class RhSolutionsFunctions
{
[ExcelFunction(Description = "Поиск артикула в базе данных")]
public static object RHSOLUTIONS([ExcelArgument(Name = "СТРОКА", Description = "Ячейка с артикулом РЕХАУ или поисковый запрос в свободной форме")] string line)
@ -16,7 +18,7 @@ public class RhSolutionsFunction
ProductSku.TryParse(line, out var skus);
if (ExcelAsyncUtil.Run("Database request", line, delegate
if (ExcelAsyncUtil.Run(nameof(RHSOLUTIONS), line, delegate
{
return databaseClient.GetProducts(line)
.GetAwaiter()
@ -80,7 +82,7 @@ public class RhSolutionsFunction
var article = skus.First().Id;
IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>();
if (ExcelAsyncUtil.Run("Database request", line, delegate
if (ExcelAsyncUtil.Run(nameof(РЕХАУИМЯ), line, delegate
{
return databaseClient.GetProducts(article)
.GetAwaiter()
@ -116,7 +118,7 @@ public class RhSolutionsFunction
var article = skus.First().Id;
IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>();
if (ExcelAsyncUtil.Run("Database request", line, delegate
if (ExcelAsyncUtil.Run(nameof(РЕХАУЦЕНА), line, delegate
{
return databaseClient.GetProducts(article)
.GetAwaiter()
@ -154,7 +156,7 @@ public class RhSolutionsFunction
IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService<IDatabaseClient>();
ICurrencyClient currencyClient = RhSolutionsAddIn.ServiceProvider.GetRequiredService<ICurrencyClient>();
if (ExcelAsyncUtil.Run("Database request", line, delegate
if (ExcelAsyncUtil.Run(nameof(РЕХАУЦЕНАРУБ), line, delegate
{
var product = databaseClient.GetProducts(article)
.GetAwaiter()
@ -190,29 +192,33 @@ public class RhSolutionsFunction
public static object КУРСЕВРО([ExcelArgument(Name = "ДАТА", Description = "Дата в формате Excel (необязательно)")] double dateField)
{
ICurrencyClient currencyClient = RhSolutionsAddIn.ServiceProvider.GetRequiredService<ICurrencyClient>();
if (ExcelAsyncUtil.Run("Database request", dateField, delegate
{
IMemoryCache memoryCache = RhSolutionsAddIn.ServiceProvider.GetRequiredService<IMemoryCache>();
DateTime date = dateField == 0 ? DateTime.Today : DateTime.FromOADate(dateField);
var exchangeRate = currencyClient.GetCurrencyCourse(date)
if (!memoryCache.TryGetValue(date, out decimal exchangeRate))
{
var result = ExcelAsyncUtil.Run(nameof(КУРСЕВРО), dateField, delegate
{
var requestResult = currencyClient.GetCurrencyCourse(date)
.GetAwaiter()
.GetResult();
return exchangeRate ?? -1m;
}) is not decimal requestResult)
return requestResult ?? -1m;
});
if (result is not decimal)
{
return "Загрузка...";
}
else
{
if (requestResult < 0)
{
return ExcelError.ExcelErrorNA;
}
else
{
return Math.Round(requestResult, 2);
exchangeRate = (decimal)result;
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
memoryCache.Set(date, exchangeRate, cacheEntryOptions);
}
}
return exchangeRate < 0 ? ExcelError.ExcelErrorNA : exchangeRate;
}
}

View File

@ -1,5 +1,4 @@
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
@ -9,28 +8,25 @@ 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=";
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)
public CurrencyClient(HttpClient httpClient)
{
_httpClient = httpClient;
_memoryCache = memoryCache;
}
public async Task<decimal?> GetCurrencyCourse(DateTime date)
{
if (!_memoryCache.TryGetValue(date, out decimal? exchangeRate))
{
string request = $"{requestAddress}{date.Date:dd/MM/yyyy}";
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")
decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
.Where(e => e.Element("Name").Value == "Евро")
.FirstOrDefault()
.Element("Value").Value);
@ -39,13 +35,7 @@ public class CurrencyClient : ICurrencyClient
catch
{
StatusCode = response.StatusCode;
exchangeRate = null;
return null;
}
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(date, exchangeRate, cacheEntryOptions);
}
return exchangeRate;
}
}