How can I dynamically set the values of variables from the parent scope in a Windows Workflow Foundation activity under .NET 4?
An attempt that failed (drop on a Sequence activity on a workflow where the Sequence has an int variable named Test):
public sealed class CodeActivity1 : NativeActivity
{
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
_locationReferences =
metadata.Environment.GetLocationReferences().ToList();
base.CacheMetadata(metadata);
}
protected override void Execute(NativeActivityContext context)
{
LocationReference locationReference =
_locationReferences.Find(
x => x.Name == "Test" && x.Type == typeof (int));
if (locationReference != null)
{
Console.WriteLine(
locationReference.Name + " " + locationReference.Type);
// Blows up here.
Location location = locationReference.GetLocation(context);
location.Value = 5;
}
}
private List<LocationReference> _locationReferences;
}
This results in:
System.InvalidOperationException was
unhandled by user code
Message=Activity ‘1.2: CodeActivity1’
cannot access this variable because it
is declared at the scope of activity
‘1.1: Sequence’. An activity can only
access its own implementation
variables.
It does find the variable; it just can’t get or set its value.
The variable name (“Test” in the above example) would not be known until runtime.
The normal way of handling this is to define an OutArgument and in the workflow designer bind the OutArgument to your variable. In the activity you only work with the argument. Using a NativeActivity gives you an OutArgument named Result but just adding a property of OUtArgument will do just fine.
Another benefit is you don’t need to know “magic” variable names to store results in.
Update because the code in the comment below is unreadable.
Try adding the following just before the line it blows up:
Totally not supported so use with care 🙂