Search code examples
c#workflow-foundation-4workflow-foundation

Windows Workflow: Output from CodeActivity to input on next CodeActivity


I'm trying to figure out how I can pass data from one custom CodeActivity as a result, into the next CodeActivity in the sequence as an input.

Here is the code I have so far:

  private static void DemoWorkflow()
    {

        var s = new Sequence()
        {
            DisplayName = "Sequence1",
            Variables =
            {
                new Variable<string>
                {
                    Name = "TestParam",
                    Default = "Hello"
                }
            },
            Activities =
            {
                new Method1() { Text = "Test1234"},
                new Method2() 
            }
        };

        var settings = new TextExpressionCompilerSettings
        {
            AlwaysGenerateSource = true,
            ActivityName = "Sequence",
            ActivityNamespace = "System.Activities.Statements",
            ForImplementation = false,
            Activity = s,
            Language = "C#",
            RootNamespace = null,
            GenerateAsPartialClass = false
        };

        var results = new TextExpressionCompiler(settings).Compile();
        if (results.HasErrors)
        {
            throw new Exception("Compilation failed.");
        }

        var compiledExpressionRoot = Activator.CreateInstance(results.ResultType,
            new object[] {s}) as ICompiledExpressionRoot;

        CompiledExpressionInvoker.SetCompiledExpressionRoot(s, compiledExpressionRoot);
        WorkflowInvoker.Invoke(s);
    }
}

public class Method1 : CodeActivity<string>
{
    [RequiredArgument]
    public InArgument<string> Text { get; set; }

    protected override string Execute(CodeActivityContext context)
    {
        var inText = this.Text.Get(context);
        Console.WriteLine(inText);
        return "Text from Method1: " + inText;
    }
}

public class Method2 : CodeActivity
{
    public InArgument<string> Text { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        var inText = this.Text.Get(context);
        Console.WriteLine(inText);
    }
}

I feel Method2 should print "Text from Method 1: Test1234" but it currently does not.


Solution

  • You're not binding the variable to Method1::Result OutArgument<string> or the Method2::Text InArgument<string>. Try this setup instead:

    var v = new Variable<string>
    {
        Name = "TestParam",
        Default = "Hello"
    };
    
    var s = new Sequence()
    {
        DisplayName = "Sequence1",
        Variables =
        {
           v
        },
        Activities =
        {
            new Method1() { Text = "Test1234", Result = new OutArgument<string>(v)},
            new Method2() { Text = new InArgument<string>(v) } 
        }
    };