public class IntelliSenseAddIn : IExcelAddIn
{
public void AutoOpen()
{
ExcelRegistration.GetExcelFunctions()
.ProcessParameterConversions(GetPostAsyncReturnConversionConfig())
.ProcessAsyncRegistrations(nativeAsyncIfAvailable: false)
.RegisterFunctions();
IntelliSenseServer.Install();
}
public void AutoClose()
{
IntelliSenseServer.Uninstall();
}
static ParameterConversionConfiguration GetPostAsyncReturnConversionConfig()
{
var rval = ExcelError.ExcelErrorGettingData;
return new ParameterConversionConfiguration()
.AddReturnConversion((type, customAttributes) => type != typeof(object) ? null : ((Expression<Func<object, object>>)
((object returnValue) => returnValue.Equals(ExcelError.ExcelErrorNA) ? rval : returnValue)));
}
}
public static class MyFunctions
{
private static Dictionary<string, object> cache = new Dictionary<string, object>();
public static void ClearCache()
{
cache.Clear();
}
[ExcelFunction(Description = "Download data")]
public static object BULLIT(
[ExcelArgument(Name = "Ticker", Description = "ID of the asset")]
// ... Some other ExcelArguments
)
{
string cacheKey = $"{ticker}-{data_request}-{period_start}-{period_end}-{transparency}-{order}-{direction}-{titles}";
if (cache.ContainsKey(cacheKey))
{
return cache[cacheKey];
}
var functionName = nameof(BULLIT);
var parameters = new object[] { ticker, data_request, period_start, period_end, transparency, order, direction, titles };
return ExcelAsyncUtil.RunTask(functionName, parameters, async () =>
{
var username = "xxx";
var password = "xxx";
var PostData = new Dictionary<string, string>
{
{"username", username},
{"password", password},
// ... Some other PostData
};
HttpClient myHttpClient = new();
HttpContent content = new FormUrlEncodedContent(PostData);
HttpResponseMessage response = await myHttpClient.PostAsync(url, content).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
string jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Json json = JsonSerializer.Deserialize<Json>(jsonString);
if (json != null && json.Error == "No error" && json.Data != null)
{
int rows = json.Data.Count;
int columns = json.Data[0].Value.Count;
object[,] result = new object[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (json.Data[i].Type[j] == "DOUBLE")
{
if (double.TryParse(json.Data[i].Value[j], NumberStyles.Any, CultureInfo.InvariantCulture, out double numericValue))
{
result[i, j] = numericValue;
}
else
{
result[i, j] = json.Data[i].Value[j];
}
}
else
{
result[i, j] = json.Data[i].Value[j];
}
}
}
cache[cacheKey] = result;
return result;
}
else
{
object[,] result = new object[1, 1];
if (json != null && json.Error != null)
{
cache[cacheKey] = result;
result[0, 0] = json.Error;
}
else
{
result[0, 0] = "#API_ERROR";
}
return result;
}
}
else
{
object[,] result = new object[1, 1];
result[0, 0] = "#API_UNAVAILABLE";
return result;
}
});
}
}