This example demonstrates how to load an OpenAPI document, register it as an action connector in a PowerFxConfig, set up the required RuntimeConfig with a custom BaseRuntimeConnectorContext, and evaluate a formula using the RecalcEngine.
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.OpenApi.Readers;
using Microsoft.PowerFx;
using Microsoft.PowerFx.Connectors;
using Microsoft.PowerFx.Types;
public static class ActionConnectorSample
{
public static async Task RunAsync()
{
// 1. Load the swagger.
using var stream = File.OpenRead("MyConnector.swagger.json");
var openApiDoc = new OpenApiStreamReader().Read(stream, out _);
// 2. Create a PowerFxConfig and register the connector.
var config = new PowerFxConfig();
var settings = new ConnectorSettings("MyConnector")
{
IncludeInternalFunctions = false,
AllowUnsupportedFunctions = false,
};
// OpenApiParser.GetFunctions is called under the hood by AddActionConnector.
IReadOnlyList<ConnectorFunction> functions =
config.AddActionConnector(settings, openApiDoc, new ConsoleLogger());
// 3. Build an HttpMessageInvoker that will actually make the network call.
using var httpClient = new HttpClient();
// 4. Create a RuntimeConfig with the connector runtime context.
var runtimeCtx = new MyConnectorRuntimeContext("MyConnector", httpClient);
var runtimeConfig = new RuntimeConfig().AddRuntimeContext(runtimeCtx);
// 5. Evaluate a Power Fx expression that uses the generated function.
var engine = new RecalcEngine(config);
var result = await engine.EvalAsync(
@"MyConnector.SendEmail({ to: ""a@b.com"", subject: ""Hi"" })",
CancellationToken.None,
options: new ParserOptions { AllowsSideEffects = true },
runtimeConfig: runtimeConfig);
Console.WriteLine(result.ToObject());
}
private sealed class MyConnectorRuntimeContext : BaseRuntimeConnectorContext
{
private readonly string _ns;
private readonly HttpMessageInvoker _invoker;
public MyConnectorRuntimeContext(string ns, HttpMessageInvoker invoker) { _ns = ns; _invoker = invoker; }
public override HttpMessageInvoker GetInvoker(string @namespace) => _invoker;
public override TimeZoneInfo TimeZoneInfo => TimeZoneInfo.Utc;
}
}