RhSolutions-AddIn/src/AddIn/Functions.cs

84 lines
2.4 KiB
C#
Raw Normal View History

using ExcelDna.Integration;
2022-12-19 09:13:14 +03:00
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
2021-11-11 16:33:40 +03:00
2021-12-08 14:45:14 +03:00
namespace RehauSku
2021-11-11 16:33:40 +03:00
{
2021-11-29 15:50:24 +03:00
public class Functions
2021-11-11 16:33:40 +03:00
{
2022-07-04 09:08:02 +03:00
[ExcelFunction(Description = "Получение корректного артикула из строки")]
public static object GETRAUSKU([ExcelArgument(Name = "\"Строка\"", Description = "строка, содержащая актикул")] string line)
{
2022-07-04 09:21:44 +03:00
if (RauSku.TryParse(line, out RauSku rausku))
2022-07-04 09:08:02 +03:00
{
return rausku.ToString();
}
else return ExcelError.ExcelErrorNA;
}
2022-12-19 09:13:14 +03:00
[ExcelFunction(Description = "Запрос в удаленную базу данных")]
public static object RHSOLUTIONS([ExcelArgument(Name = "Запрос")] string line)
{
object result;
result = ExcelAsyncUtil.Run("Database request", line, delegate
{
return RhDatabaseClient.GetProduct(line).GetAwaiter().GetResult();
});
if (result == null)
{
return ExcelError.ExcelErrorNA;
}
if (result.Equals(ExcelError.ExcelErrorNA))
{
return "Загрузка...";
}
return result;
}
}
public static class RhDatabaseClient
{
private static HttpClient httpClient = AddIn.httpClient;
public static async Task<object> GetProduct(string line)
{
string request = @"https://rh.cebotari.ru/api/search?query=" + line;
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls;
string response = await httpClient.GetStringAsync(request);
var products = JsonConvert.DeserializeObject<IEnumerable<DbProduct>>(response);
var product = products.FirstOrDefault();
if (product == null)
{
return null;
}
else
{
return $"{product.productSku} {product.name}";
}
}
private class DbProduct
{
public string productSku { get; set; }
public string name { get; set; }
}
2021-11-11 16:33:40 +03:00
}
}