Compare commits

..

No commits in common. "213592b9e2e589b36b5fbd2a26d1ca28530d58ff" and "8b125e475e4f6970d1948e77fdf832c5e77f2cec" have entirely different histories.

3 changed files with 50 additions and 46 deletions

View File

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

View File

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

View File

@ -1,4 +1,5 @@
using System.Net; using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq; using System.Xml.Linq;
@ -8,25 +9,28 @@ namespace RhSolutions.Services;
public class CurrencyClient : ICurrencyClient public class CurrencyClient : ICurrencyClient
{ {
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req="; 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 HttpStatusCode StatusCode { get; private set; }
public CurrencyClient(HttpClient httpClient) public CurrencyClient(HttpClient httpClient, IMemoryCache memoryCache)
{ {
_httpClient = httpClient; _httpClient = httpClient;
_memoryCache = memoryCache;
} }
public async Task<decimal?> GetCurrencyCourse(DateTime date) public async Task<decimal?> GetCurrencyCourse(DateTime date)
{ {
string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}"; if (!_memoryCache.TryGetValue(date, out decimal? exchangeRate))
{
string request = $"{requestAddress}{date.Date:dd/MM/yyyy}";
HttpResponseMessage response = await _httpClient.GetAsync(request); HttpResponseMessage response = await _httpClient.GetAsync(request);
try try
{ {
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
string xml = await response.Content.ReadAsStringAsync(); string xml = await response.Content.ReadAsStringAsync();
XElement valCourses = XElement.Parse(xml); XElement valCourses = XElement.Parse(xml);
exchangeRate = decimal.Parse(valCourses.Elements("Valute")
decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
.Where(e => e.Element("Name").Value == "Евро") .Where(e => e.Element("Name").Value == "Евро")
.FirstOrDefault() .FirstOrDefault()
.Element("Value").Value); .Element("Value").Value);
@ -35,7 +39,13 @@ public class CurrencyClient : ICurrencyClient
catch catch
{ {
StatusCode = response.StatusCode; StatusCode = response.StatusCode;
return null; exchangeRate = null;
} }
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(date, exchangeRate, cacheEntryOptions);
}
return exchangeRate;
} }
} }