How to embed PowerFX in a .NET Application
PowerFX is a language from Microsoft aimed at power users. Writing PowerFX feels like Excel formulas, and one of the building blocks of PowerFX is actually “formulas” that are reactive to other formulas. Microsoft uses PowerFX mainly as the low code language for the PowerApps offering.
A few years ago, Microsoft open sourced PowerFX with the goal of letting others take advantage of the power and simplicity of the language. The main repo is located at https://github.com/microsoft/Power-Fx . The repo contains a link nice introductory video about the what, why and how of PowerFX (https://www.youtube-nocookie.com/embed/ik6k89WNjuk ).
If you are a .NET developer, you too can take advantage of the power and simplicity of PowerFX by embedding a .NET PowerFX Interpreter created by Microsoft. One use case for embedding PowerFX in a .NET app is to allow Business Users to define Business Rules in PowerFX and then integrate them into your app. This allows the Business users to maintain the rules while you maintain the hosting app.
To use the interpreter:
- Add the Microsoft.PowerFx.Interpreter NuGet to your project ( https://www.nuget.org/packages/Microsoft.PowerFx.Interpreter )
- Instantiate an object of type RecalcEngine.
- Add formulas by passing the formula as a string to the SetFormula method of RecalcEngine.
- Notice that adding Formulas does not execute them. To make the engine execute the formulas, call RecalcEngine’s Eval (or EvalAsync) method, passing a string representing the expression to execute. The expression can reference formulas added with SetFormula.
Here is the minimal C# example:
using Microsoft.PowerFx;
using Microsoft.PowerFx.Types;
var engine = new RecalcEngine();
// notice the escaped quotes as we are passing a PowerFX string literal. Our second parameter needs to be
// a valid PowerFX expression.
engine.SetFormula("MyName", "\"Juanito\"", OnFormulaUpdate);
engine.SetFormula("Greeting", "\"Hello, \" & MyName & \"!\"", OnFormulaUpdate);
var greetingResult = engine.Eval("Greeting");
Console.WriteLine(greetingResult.ToObject());
return;
void OnFormulaUpdate(string arg1, FormulaValue arg2)
{
// this method is called whenever the formula is evaluated by the engine
}
I have been working on a new app ( https://github.com/TheJuanitoLearnsShow/PuppyWorkbooks ) that allows users to maintain an executable workbook containing PowerFX formulas. The app and its tests provide examples of how to use the interpreter. The repo has examples of how to create your own PowerFX function to be used by PowerFX expressions, a future post will cover the steps on how to accomplish that.
Comments