| | | 1 | | using System.Text; |
| | | 2 | | using Elsa.Expressions.Models; |
| | | 3 | | using Elsa.Extensions; |
| | | 4 | | using Elsa.Mediator.Contracts; |
| | | 5 | | using Elsa.Expressions.Python.Notifications; |
| | | 6 | | using JetBrains.Annotations; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Expressions.Python.Handlers; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Configures the C# evaluator with methods to access workflow variables. |
| | | 12 | | /// </summary> |
| | | 13 | | [UsedImplicitly] |
| | | 14 | | public class GenerateWorkflowVariableAccessors : INotificationHandler<EvaluatingPython> |
| | | 15 | | { |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public Task HandleAsync(EvaluatingPython notification, CancellationToken cancellationToken) |
| | | 18 | | { |
| | 0 | 19 | | var expressionExecutionContext = notification.Context; |
| | 0 | 20 | | var variables = expressionExecutionContext.GetVariablesInScope().ToList(); |
| | 0 | 21 | | var sb = new StringBuilder(); |
| | 0 | 22 | | sb.AppendLine("class WorkflowVariablesProxy:"); |
| | 0 | 23 | | sb.AppendLine(" def __init__(self, execution_context):"); |
| | 0 | 24 | | sb.AppendLine(" self.execution_context = execution_context"); |
| | 0 | 25 | | sb.AppendLine(); |
| | 0 | 26 | | sb.AppendLine(" def get(self, name):"); |
| | 0 | 27 | | sb.AppendLine(" return self.execution_context.GetVariable(name)"); |
| | 0 | 28 | | sb.AppendLine(); |
| | 0 | 29 | | sb.AppendLine(" def set(self, name, value):"); |
| | 0 | 30 | | sb.AppendLine(" self.execution_context.SetVariable(name, value)"); |
| | 0 | 31 | | sb.AppendLine(); |
| | | 32 | | |
| | 0 | 33 | | foreach (var variable in variables) |
| | | 34 | | { |
| | 0 | 35 | | var variableName = variable.Name; |
| | 0 | 36 | | var variableType = variable.GetVariableType(); |
| | 0 | 37 | | var friendlyTypeName = variableType.GetFriendlyTypeName(Brackets.Square); |
| | 0 | 38 | | sb.AppendLine($" @property"); |
| | 0 | 39 | | sb.AppendLine($" def {variableName}(self):"); |
| | 0 | 40 | | sb.AppendLine($" return self.execution_context.GetVariable[{friendlyTypeName}]('{variableName}')"); |
| | 0 | 41 | | sb.AppendLine($" @{variableName}.setter"); |
| | 0 | 42 | | sb.AppendLine($" def {variableName}(self, value):"); |
| | 0 | 43 | | sb.AppendLine($" self.execution_context.SetVariable('{variableName}', value)"); |
| | | 44 | | } |
| | | 45 | | |
| | 0 | 46 | | sb.AppendLine(); |
| | 0 | 47 | | sb.AppendLine("variables = WorkflowVariablesProxy(execution_context);"); |
| | | 48 | | |
| | 0 | 49 | | notification.AppendScript(sb.ToString()); |
| | | 50 | | |
| | 0 | 51 | | return Task.CompletedTask; |
| | | 52 | | } |
| | | 53 | | } |