一、XOML使用工作流的好处
通过Xoml方式使用工作流的好处在于,它能够不重新启动程序的情况下,仅仅通过配置xoml就能够实现改变工作流,非常灵活。
创建一个WinForm程序如下:
代码如下:
namespace WinForm { public partial class Form1 : Form { //定义工作流运行时Runtime容器 WorkflowRuntime workflowRuntime = new WorkflowRuntime(); public Form1() { InitializeComponent(); workflowRuntime.StartRuntime(); } private void button1_Click(object sender, EventArgs e) { //新建一个工作流 SequenceActivity workflow = new SequenceActivity(); workflow.Activities.Add(new MyActivity() { Message = "我已经执行啦!" }); WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); //将工作流保存在Xml文件里面 using(XmlWriter xr = XmlWriter.Create("MyWorkflow.xoml", new XmlWriterSettings() { CloseOutput = true })){ serializer.Serialize(xr, workflow); } MessageBox.Show("工作流创建成功!"); } private void button2_Click(object sender, EventArgs e) { //从Xml文件上执行工作流,如果你愿意,你可以将Xml数据保存在任何地方,甚至是保存在数据库里面 //然后从数据库里面读出工作流,然后执行 WorkflowInstance winstance = workflowRuntime.CreateWorkflow(XmlReader.Create("MyWorkflow.xoml")); winstance.Start(); } } public partial class MyActivity : Activity { public string Message { get; set; } protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { MessageBox.Show(Message); return base.Execute(executionContext); } } }
效果如下:
基于这种方式,可以实现制作出一套易操作的UI界面,让用户去配置流程,然后将生成的流程保存在Xml、字符串、数据库中。然后实现读取出流程,然后执行的目的。
结合XmlReader的重载,可以实现,只有一个字符串,就能够启动流程:
var xmlStr = "<?xml version="1.0" encoding="utf-8"?><SequenceActivity x:Name="SequenceActivity" xmlns:ns0="clr-namespace:WinForm;Assembly=WinForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"><ns0:MyActivity Message="我已经执行啦!" x:Name="myActivity1" /></SequenceActivity>"; WorkflowInstance winstance = workflowRuntime.CreateWorkflow(XmlReader.Create(new StringReader(xmlStr))); winstance.Start();