Reputation: 305
In Windows workflow foundation, is it possible to load the workflow from an external file? The aim is to make a generic workflow controller which takes the state machine workflow from a file and loads it. If I go and use the designer available in VS, the workflow diagram becomes fixed and can be used only for a particular use case but, whereas, I need to make a generic one.
Upvotes: 0
Views: 214
Reputation: 4672
Yes, you can save and load a XAML workflow to / from a file using the XamlActivityServices
and ActivityBuilder
types. You can build out your workflow dynamically in code, then use that service to serialize it down to XML to be used later.
If you want to allow your users to create and edit workflows, you can re-host the designer directly in your application too if you wish.
Saving a workflow to a file
Here's a very quick sample of saving a workflow to a file:
var activityBuilder = new ActivityBuilder();
activityBuilder.Name = "HelloWorldApp";
activityBuilder.Properties.Add(new DynamicActivityProperty { Name = "UserName", Type = typeof(InArgument<string>) });
activityBuilder.Implementation = new Sequence
{
Activities =
{
new WriteLine
{
Text = new CSharpValue<string>("\"Hello, \" + UserName + \", how are you?\"")
}
}
};
using (var streamWriter = File.CreateText(@"C:\Temp\MyWorkflow.xaml"))
{
using (var xamlWriter = new XamlXmlWriter(streamWriter, new XamlSchemaContext()))
{
using (var builderWriter = ActivityXamlServices.CreateBuilderWriter(xamlWriter))
{
XamlServices.Save(builderWriter, activityBuilder);
}
}
}
The above should produce an XML file like the following:
<?xml version="1.0" encoding="utf-8"?>
<Activity x:Class="HelloWorld"
xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities"
xmlns:mca="clr-namespace:Microsoft.CSharp.Activities;assembly=System.Activities"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="UserName" Type="InArgument(x:String)" />
</x:Members>
<Sequence>
<WriteLine>
<InArgument x:TypeArguments="x:String">
<mca:CSharpValue x:TypeArguments="x:String">
"Hello, " + UserName + ", how are you?"
</mca:CSharpValue>
</InArgument>
</WriteLine>
</Sequence>
</Activity>
Loading A XAML Workflow From A File
The following snippets show loading a workflow from a file, and then running the hydrated workflow.
var activityXamlServicesSettings = new ActivityXamlServicesSettings
{
CompileExpressions = true
};
var dynamicActivity = ActivityXamlServices.Load(File.OpenRead(@"C:\Temp\MyWorkflow.xaml"), activityXamlServicesSettings) as DynamicActivity;
var workflowInputs = new Dictionary<string, object>
{
{ "UserName", "Me" }
};
var workflowInvoker = new WorkflowInvoker(dynamicActivity);
workflowInvoker.Invoke(workflowInputs);
Upvotes: 1