Workflow Foundation个人整理的一些使用工作流例子

316774722 贡献于2011-05-19

作者 MC SYSTEM  创建于2008-11-11 03:47:00   修改者ggg  修改于2011-04-14 01:51:00字数24392

文档摘要:
关键词:

工作流包装 1. 运行时包装 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Workflow.Runtime; namespace Nocturne.Workflow.Hosting { public class WorkflowRuntimeManager:IDisposable { private WorkflowRuntime _workflowRuntime; private Dictionary _workflows = new Dictionary(); public WorkflowRuntimeManager(WorkflowRuntime instance) { _workflowRuntime = instance; if (instance == null) { throw new NullReferenceException("需要一个非空的 WorkflowRuntime 实例"); } // 提交所有的工作流事件 SubscribeToEvents(instance); } /// /// 创建并启动一个工作流。 /// /// 待启动的工作流类型 /// 入口参数 /// 包装在一个WorkflowInstanceWrapper里的工作流实例 public WorkflowInstanceWrapper StartWorkflow(Type workflowType, Dictionary parameters) { WorkflowInstance instance = _workflowRuntime.CreateWorkflow(workflowType, parameters); WorkflowInstanceWrapper wrapper = AddWorkflowInstance(instance); instance.Start(); return wrapper; } #region 公共属性和事件 /// /// 获取WorkflowRuntime实例 /// public WorkflowRuntime WorkflowRuntime { get { return _workflowRuntime; } } /// /// 获取工作流实例包装的一个字典 /// public Dictionary Workflows { get { return _workflows; } } /// /// 记录该类的日志信息的事件 /// public event EventHandler MessageEvent; #endregion #region 工作流集合管理 /// /// 从工作流字典中移除某个实例 /// /// public void ClearWorkflow(Guid workflowId) { if (_workflows.ContainsKey(workflowId)) { _workflows.Remove(workflowId); } } /// /// 从字典中清除所有的工作流 /// public void ClearAllWorkflows() { _workflows.Clear(); } /// /// 向字典中添加一个新的工作流实例 /// /// /// private WorkflowInstanceWrapper AddWorkflowInstance(WorkflowInstance instance) { WorkflowInstanceWrapper wrapper = null; if (!_workflows.ContainsKey(instance.InstanceId)) { wrapper = new WorkflowInstanceWrapper(instance); _workflows.Add(wrapper.Id, wrapper); } return wrapper; } /// /// 依据Guid查找工作流实例 /// /// /// public WorkflowInstanceWrapper FindWorkflowInstance(Guid workflowId) { WorkflowInstanceWrapper result = null; if (_workflows.ContainsKey(workflowId)) { result = _workflows[workflowId]; } return result; } /// /// 等待所有的工作流实例完成 /// /// public void WaitAll(int msecondsTimeout) { if (_workflows.Count > 0) { WaitHandle[] handles = new WaitHandle[_workflows.Count]; int index = 0; foreach (WorkflowInstanceWrapper wrapper in _workflows.Values) { handles[index] = wrapper.WaitHandle; index++; } WaitHandle.WaitAll(handles, msecondsTimeout, false); } } #endregion #region IDisposable Members /// /// 销毁工作流运行时 /// public void Dispose() { if (_workflowRuntime != null) { _workflowRuntime.StopRuntime(); _workflowRuntime.Dispose(); } ClearAllWorkflows(); } #endregion #region 工作流事件处理 /// /// 订阅我们所有关心的事件 /// /// private void SubscribeToEvents(WorkflowRuntime runtime) { runtime.Started += new EventHandler(runtime_Started); runtime.Stopped += new EventHandler(runtime_Stopped); runtime.WorkflowAborted += new EventHandler(runtime_WorkflowAborted); runtime.WorkflowCompleted += new EventHandler(runtime_WorkflowCompleted); runtime.WorkflowCreated += new EventHandler(runtime_WorkflowCreated); runtime.WorkflowIdled += new EventHandler(runtime_WorkflowIdled); runtime.WorkflowLoaded += new EventHandler(runtime_WorkflowLoaded); runtime.WorkflowPersisted += new EventHandler(runtime_WorkflowPersisted); runtime.WorkflowResumed += new EventHandler(runtime_WorkflowResumed); runtime.WorkflowStarted += new EventHandler(runtime_WorkflowStarted); runtime.WorkflowSuspended += new EventHandler(runtime_WorkflowSuspended); runtime.WorkflowTerminated += new EventHandler(runtime_WorkflowTerminated); runtime.WorkflowUnloaded += new EventHandler(runtime_WorkflowUnloaded); } void runtime_Started(object sender, WorkflowRuntimeEventArgs e) { LogStatus(Guid.Empty, "Started"); } void runtime_Stopped(object sender, WorkflowRuntimeEventArgs e) { LogStatus(Guid.Empty, "Stopped"); } void runtime_WorkflowCreated(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowCreated"); } void runtime_WorkflowStarted(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowStarted"); } void runtime_WorkflowIdled(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowIdled"); } void runtime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowCompleted"); WorkflowInstanceWrapper wrapper = FindWorkflowInstance(e.WorkflowInstance.InstanceId); if (wrapper != null) { wrapper.OutputParameters = e.OutputParameters; wrapper.StopWaiting(); } } void runtime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowTerminated"); WorkflowInstanceWrapper wrapper = FindWorkflowInstance(e.WorkflowInstance.InstanceId); if (wrapper != null) { wrapper.Exception = e.Exception; wrapper.StopWaiting(); } } void runtime_WorkflowSuspended(object sender, WorkflowSuspendedEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowSuspended"); WorkflowInstanceWrapper wrapper = FindWorkflowInstance(e.WorkflowInstance.InstanceId); if (wrapper != null) { wrapper.ReasonSuspended = e.Error; } } void runtime_WorkflowResumed(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowResumed"); } void runtime_WorkflowPersisted(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowPersisted"); } void runtime_WorkflowLoaded(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowLoaded"); } void runtime_WorkflowAborted(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowAborted"); WorkflowInstanceWrapper wrapper = FindWorkflowInstance(e.WorkflowInstance.InstanceId); if (wrapper != null) { wrapper.StopWaiting(); } } void runtime_WorkflowUnloaded(object sender, WorkflowEventArgs e) { LogStatus(e.WorkflowInstance.InstanceId, "WorkflowUnloaded"); } private void LogStatus(Guid instanceId, String msg) { if (MessageEvent != null) { String formattedMsg; if (instanceId == Guid.Empty) { formattedMsg = String.Format("Runtime - {0}", msg); } else { formattedMsg = String.Format("{0} - {1}", instanceId, msg); } // 引发事件 MessageEvent(this, new WorkflowLogEventArgs(formattedMsg)); } } #endregion } /// /// 在管理类中用来记录日志信息的EventArgs /// public class WorkflowLogEventArgs : EventArgs { private string _msg = string.Empty; public WorkflowLogEventArgs(string msg) { _msg = msg; } public string Message { get { return _msg; } } } } 2. 工作流实例包装 using System; using System.Collections.Generic; using System.Threading; using System.Workflow.Runtime; namespace Nocturne.Workflow.Hosting { /// /// 工作流实例的容器 /// [Serializable] public class WorkflowInstanceWrapper { private WorkflowInstance _workflowInstance; private ManualResetEvent _waitHandle = new ManualResetEvent(false); private Dictionary _outputParameters = new Dictionary(); private Exception _exception; private string _reasonSuspended = string.Empty; public WorkflowInstanceWrapper(WorkflowInstance instance) { _workflowInstance = instance; } #region 公开属性与方法 /// /// 获取工作流实例的 ID /// public Guid Id { get { if (_workflowInstance != null) { return _workflowInstance.InstanceId; } else { return Guid.Empty; } } } /// /// 输出参数的集合 /// public Dictionary OutputParameters { get { return _outputParameters; } set { _outputParameters = value; } } /// /// 一个等待句柄。宿主应用程序可以使用它,挂起 /// 进程直到工作流完成。 /// public ManualResetEvent WaitHandle { get { return _waitHandle; } set { _waitHandle = value; } } /// /// 工作流可能抛出的异常对象 /// public Exception Exception { get { return _exception; } set { _exception = value; } } /// /// 工作流挂起的原因 /// /// public string ReasonSuspended { get { return _reasonSuspended; } set { _reasonSuspended = value; } } /// /// 真实的工作流实例 /// public WorkflowInstance WorkflowInstance { get { return _workflowInstance; } } /// /// 工作流完成的信号,宿主应用程序可以停止等待 /// public void StopWaiting() { _waitHandle.Set(); } #endregion } } 3. 测试程序 using System; using System.Collections.Generic; using System.Text; using System.Workflow.Runtime; using System.Workflow.Runtime.Hosting; using Nocturne.Workflow.Hosting; namespace ConsoleHostingManaged { /// /// 使用自定义封装类来host工作流 /// class WorkflowTest { /// Run 方法将在 Main 方法启动之后被执行,该方法创建一个 WorkflowRuntimeManager 的实例而启动, /// 使用 using 的目的在于一旦离开这个语句块,就可以自动调用 Dispose 方法来销毁对象,前面实现 /// IDisposable 接口的意义就在于此。 /// WorkflowRuntimeManager 构造函数被传入一个 WorkflowRuntime 类的实例。这就是我们设计管理类 /// 的目的,从外部构造 WorkflowRuntime,以此来提供附加的过占星。 /// 一个事件句柄被作为 WorkflowRuntimeManager.MessageEvent 添加。此事件在处理 WorkflowRuntime /// 事件的时候会被出发。这段代码仅仅是简单的将信息输出到屏幕上 /// /// 启动工作流 /// public static void Run() { Console.WriteLine("使用 persistence 服务运行测试"); using (WorkflowRuntimeManager manager = new WorkflowRuntimeManager(new WorkflowRuntime())) { // 添加一个事件句柄记录日志 manager.MessageEvent += delegate(object sender, WorkflowLogEventArgs e){ Console.WriteLine(e.Message); } // 创建完 WorkflowRuntime 及其包装之后,我们采用私有的 AddServices 方法向工作流运行 // 时添加服务。 AddServices(manager.WorkflowRuntime); // 启动工作流运行时。注意这一步并非必须,如果忽略这条语句,工作流运行时同样会自动运 // 行。但是所有的核心服务必须在启动运行时引擎之前声明,如果我们在调用这条语句之后 // (或者被自动调用了)才添加核心服务(也就是上面那句话),编译器会抛出异常。 manager.WorkflowRuntime.StartRuntime(); // 当核心服务添加到运行时引擎之后,就可以运行工作流了。Dictionary 就是用来传送参数的 // 桥梁 Dictionary wfArguments = new Dictionary(); wfArguments.Add("InputString", "One"); manager.StartWorkflow(typeof(SharedWorkflows.Workflow1), wfArguments); // 启动另一个实例。 wfArguments.Clear(); wfArguments.Add("InputString", "two"); manager.StartWorkflow(typeof(SharedWorkflows.Workflow1),wfArguments); wfArguments.Clear(); wfArguments.Add("InputString","three"); manager.StartWorkflow(typeof(SharedWorkflows.Workflow1),wfArguments); // 等待所有工作流实例完成 manager.WaitAll(15000); // 显示所有工作流实例的结果。由于这些工作流是存储在Dictionary里的,因此可以 // 使用 foreach 进行迭代 foreach(WorkflowInstanceWrapper wrapper in manager.Workflows.Values) { if (wrapper.OutputParameters.ContainsKey("Result")) { Console.WriteLine(wrapper.OutputParameters["Result"]); } else { if (wrapper.Exception!=null) { Console.WriteLine("{0} - 异常: {1}",wrapper.Id,wrapper.Exception.Message); } } } manager.ClearAllWorkflows(); } } /// /// 添加运行时引擎需要的服务 /// /// private static void AddServices(WorkflowRuntime instance) { string connStringPersistence = string.Format("Initial Catalog={0}; Data Source={1}; Integrated Security={2};", "WorkflowPersistence", @"localhost\SQLEXPRESS", "SSPI"); instance.AddService(new SqlWorkflowPersistenceService(connStringPersistence, true, new TimeSpan(0, 2, 0), new TimeSpan(0, 0, 5))); } } } 构建工作流平台 1. 平台类 using System; namespace wfTest { #region 工作流引擎 //引擎类 public class wfEngine { //实例池 protected System.Collections.SortedList InstancePool; public wfEngine() { InstancePool=new System.Collections.SortedList(); } /// /// 添加实例到引擎 /// /// 工作流实例 /// 实例ID public string AddInstance(wfTemplet Instance) { InstancePool.Add(Instance.InstanceID ,Instance.CurrentNode); return Instance.InstanceID; } /// /// 工作流下移一结点 /// /// 实例ID /// public bool ExecuteNextNode(string InstanceID) { if(InstancePool.Contains(InstanceID)) { if(((wfNode)InstancePool[InstanceID]).NextNode !=null) { InstancePool[InstanceID]=((wfNode)InstancePool[InstanceID]).execute(); return true; } else { ((wfNode)InstancePool[InstanceID]).execute(); InstancePool.Remove(InstanceID); return false; } } return false; } /// /// 一次执行完实例的所有结点 /// /// 实例ID public void AutoExecute(string InstanceID) { while (ExecuteNextNode(InstanceID)) { AutoExecute(InstanceID); } } //得到实例状态 public string getInstanceState(string InstanceID) { if(InstancePool.Contains(InstanceID)) { return ((wfNode)InstancePool[InstanceID]).NodeId; } return null; } //得到引擎内的所有实例 public System.Collections.SortedList getInstances() { return this.InstancePool; } //停止实例 public void StopInstance(string InstanceID) {} //继续被停止实例 public void runInstance(string InstanceID) {} } #endregion //--------------------------------------------------------------------- #region 工作流模板 //工作流类 public class wfTemplet { public string InstanceID;//实例ID /// /// 构造函数 /// /// 实例ID public wfTemplet(string InstanceID) { this.InstanceID=InstanceID; } public wfNode CurrentNode;//当前活动结点 } #endregion //--------------------------------------------------------------------- #region 结点模板 //结点模板类 public abstract class wfNode { public string InstanceId;//实例ID public string NodeId;//结点ID /// /// 构造函数 /// /// 实例ID /// 结点ID public wfNode(string InstanceID,string NodeId) { this.InstanceId=InstanceID; this.NodeId =NodeId; } //下一结点 public wfNode NextNode; //执行区 public abstract wfNode execute(); } #endregion //--------------------------------------------------------------------- #region 代码结点模板 //要执行的代码委托 public delegate void codeMethod(wfNode sender ,object data); //代码结点模板类 public class codeNode:wfNode { //构造函数 public codeNode(string InstanceID,string NodeId) :base(InstanceID, NodeId) {} public event codeMethod Code;//要执行的代码 public object CodeParameter ;//要执行的参数 //执行区 public override wfNode execute() { if(Code !=null) { Code(this,CodeParameter); } return this.NextNode; } } #endregion //--------------------------------------------------------------------- #region 条件结点模板 //条件表达式类 public class conditionExpression { public object leftExpression;//左表达式 public object rightExpression;//右表达式 //比效方法 //可以跟据需要自定义左、右表达式,并重载比效运算符 public bool contrast() { if(leftExpression.Equals(rightExpression)) {return true;} else {return false;} } } //条件结点模板类 public class conditionNode:wfNode { //构造函数 public conditionNode(string InstanceID,string NodeId) :base(InstanceID, NodeId) {} public conditionExpression expression;//表达式对象 public wfNode ElseNode;//否则结点 //执行区 public override wfNode execute() { if(expression.contrast()) {return this.NextNode;} else {return this.ElseNode;} } } #endregion //--------------------------------------------------------------------- } 2. 测试程序 using System; namespace Test { public class begin { static void Main() { wfTest.wfEngine 引擎=new wfTest.wfEngine(); 一个工作流 obj1=new 一个工作流("12345"); 一个工作流 obj2=new 一个工作流("12347"); 引擎.AddInstance(obj1); 引擎.AddInstance(obj2); 引擎.AutoExecute(obj1.InstanceID); 引擎.AutoExecute(obj2.InstanceID); System.Console.Read(); } } class 一个工作流:wfTest.wfTemplet { public 一个工作流(string InstanceID) :base(InstanceID) { /* * 结点A * | * | * 结点B * (true)/ \(false) * / \ * 结点C 结点D * \ / * \ / * 结点E */ //结点A:代码结点 wfTest.codeNode 结点A =new wfTest.codeNode(this.InstanceID,"结点A"); 结点A.Code+=new wfTest.codeMethod(结点A_Code); 结点A.CodeParameter="hello wf"; //结点B:条件结点 wfTest.conditionNode 结点B=new wfTest.conditionNode(this.InstanceID,"结点B"); //结点B的条件表达式 wfTest.conditionExpression 条件表达式=new wfTest.conditionExpression(); 条件表达式.leftExpression="123";//条件表达式左值 条件表达式.rightExpression ="123";//条件表达式右值 结点B.expression=条件表达式; //绑定条件表达式到结点B //结点C:代码结点 wfTest.codeNode 结点C =new wfTest.codeNode(this.InstanceID,"结点C"); 结点C.Code+=new wfTest.codeMethod(结点C_Code); 结点C.CodeParameter="i am 结点C,条件的真结点"; //结点D:代码结点 wfTest.codeNode 结点D =new wfTest.codeNode(this.InstanceID,"结点D"); 结点D.Code+=new wfTest.codeMethod(结点D_Code); 结点D.CodeParameter="这是_结点D,条件的假结点"; //结点E:代码结点 wfTest.codeNode 结点E =new wfTest.codeNode(this.InstanceID,"结点E"); 结点E.Code+=new wfTest.codeMethod(结点E_Code); 结点E.CodeParameter="完成了"; //指定入口结点 this.CurrentNode=结点A; //设置结点关系 结点A.NextNode =结点B; 结点B.NextNode =结点C; 结点B.ElseNode =结点D; 结点C.NextNode =结点E; 结点D.NextNode =结点E; } //结点A:代码 private void 结点A_Code(wfTest.wfNode sender, object data) { System.Console.WriteLine(sender.InstanceId + ":" + sender.NodeId + ":" + data.ToString()); } //结点C:代码 private void 结点C_Code(wfTest.wfNode sender, object data) { System.Console.WriteLine(sender.InstanceId + ":" + sender.NodeId + ":" + data.ToString()); } //结点B:代码 private void 结点D_Code(wfTest.wfNode sender, object data) { System.Console.WriteLine(sender.InstanceId + ":" + sender.NodeId + ":" + data.ToString()); } //结点E:代码 private void 结点E_Code(wfTest.wfNode sender, object data) { System.Console.WriteLine(sender.InstanceId + ":" + sender.NodeId + ":" + data.ToString()); } } } 1. Windows Workflow Foundation 通信服务使工作流能够使用方法和事件通过消息与外部系统交互。 l 事件用于将数据发送到工作流,而工作流使用方法将数据发送到主机应用程序。 l 通过事件与工作流进行通信的功能提供了一种将数据发送到工作流的异步方式。 图一 2. 基本的通讯行为 • 接口定义 – 在工作流和应用之间进行通讯 • CallExternalMethod Activity – 从工作流发送数据到应用程序(Workflow->App)见A • HandleExternalEvent Activity – 从应用程序发送数据到工作流(App->Workflow)见B   图二 A:本地通讯服务 图三   [DataExchangeService] public interface IHelpRequest { void OnRequestEscalated(string id); event EventHandler CloseRequest; }   工作流通讯的驻留需求 • 实现接口的定义 – 当工作流调用驻留程序的时候,该功能将被执行 – 提供帮助功能从驻留程序中发布工作流事件 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Workflow.Activities; using System.Windows.Forms; using System.Workflow.Runtime; namespace 工作流调用外部应用程序 { class InvokeExternalMethod:Iconnetor { public event EventHandler Approve; public event EventHandler Reject; public void CreatM(string Pro) { Console.WriteLine("调用应用程序方法开始"+WorkflowEnvironment.WorkBatch.ToString()); ShowDialog(Pro); } void ShowDialog(string pro) { DialogResult result = MessageBox.Show("是否同意进行通讯", "", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { Approve(null, new ConnetorEvnetArgs(WorkflowEnvironment.WorkflowInstanceId, pro)); } else Reject(null, new ConnetorEvnetArgs(WorkflowEnvironment.WorkflowInstanceId, pro)); } } [ExternalDataExchange] interface Iconnetor { void CreatM(string Pro); event EventHandler Approve; event EventHandler Reject; } [Serializable] public class ConnetorEvnetArgs : ExternalDataEventArgs { string _pro; public ConnetorEvnetArgs(Guid instanceid, string pro):base(instanceid) { this._pro = pro; } public string Pro { get { return this._pro; } } } } • 向运行时注册执行实例 using(WorkflowRuntime workflowRuntime = new WorkflowRuntime()) { AutoResetEvent waitHandle = new AutoResetEvent(false); workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) {waitHandle.Set();}; workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine(e.Exception.Message); waitHandle.Set(); }; ExternalDataExchangeService exchangeService = new ExternalDataExchangeService(); workflowRuntime.AddService(exchangeService); Iconnetor invokeService = new InvokeExternalMethod(); exchangeService.AddService(invokeService); WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(工作流调用外部应用程序.Workflow1)); instance.Start(); waitHandle.WaitOne(); Console.ReadLine(); } 工作流 图四 B:Web服务 • Web服务发布 – 将工作流都发布为Web 服务 – WebServiceInputActivity WebServiceOutputActivity 图五 Web服务调用 – InvokeWebServiceActivity 图六 Wcf的使用 l 创建wcf服务库项目,创建接口点与数据类型 namespace WcfServiceLibrary1 { // 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。 [ServiceContract] public interface IService1 { //[OperationContract] //string GetData(int value); //[OperationContract] //CompositeType GetDataUsingDataContract(CompositeType composite); [OperationContract] Boolean TestConnect(); [OperationContract] News GetNewsById(string id); [OperationContract] News GetNews(); [OperationContract] List GetTopNews(int num); // 任务: 在此处添加服务操作 } // 使用下面示例中说明的数据协定将复合类型添加到服务操作 [DataContract] public class News { [DataMember] public string Id { get; set; } [DataMember] public string Title { get; set; } [DataMember] public DateTime Date { get; set; } } } l 实现接口 namespace WcfServiceLibrary1 { // 注意: 如果更改此处的类名“IService1”,也必须更新 App.config 中对“IService1”的引用。 public class Service1 : IService1 { string constr = "Server=127.0.0.1,1423; database=DB_news; User ID=sa; password=sa;"; #region IService1 成员 public bool TestConnect() { SqlConnection con = new SqlConnection(constr); con.Open(); if (con.State == System.Data.ConnectionState.Open) { con.Close(); return true; } else return false; } #endregion #region IService1 成员 public News GetNewsById(string id) { SqlConnection con = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("select * from N_draft where id =" + id, con); con.Open(); SqlDataReader da = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); News n = null; if (da.Read()) { n= new News(); n.Date = DateTime.Parse(da["broadcastdate"].ToString()); n.Id = da["id"].ToString(); n.Title = da["title"].ToString(); } return n; } public News GetNews() { return GetTopNews(1)[0]; } #endregion #region IService1 成员 public List GetTopNews(int num) { List ns = new List(); SqlConnection con = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("select top " + num + " * from N_draft ", con); con.Open(); SqlDataReader da = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); News n = null; while (da.Read()) { n = new News(); n.Date = DateTime.Parse(da["broadcastdate"].ToString()); n.Id = da["id"].ToString(); n.Title = da["title"].ToString(); ns.Add(n); } return ns; } #endregion } } l 创建应用程序项目,添加服务引用 public partial class Form1 : Form { public Form1() { InitializeComponent(); } Service.News[] datas ; Service.Service1Client service = new WindowsFormsApplication1.Service.Service1Client(); private void button1_Click(object sender, EventArgs e) { datas = null; News n=service.GetNewsById(textBox1.Text ); datas = new News[] { n }; Bind(); } void Bind() { dataGridView1.DataSource = datas; dataGridView1.Columns[0].HeaderText = "id"; dataGridView1.Columns[0].DataPropertyName = "id"; dataGridView1.Columns[1].HeaderText = "title"; dataGridView1.Columns[1].DataPropertyName = "title"; dataGridView1.Columns[2].HeaderText = "date"; dataGridView1.Columns[2].DataPropertyName = "date"; } private void button2_Click(object sender, EventArgs e) { datas = null; datas = service.GetTopNews(int.Parse(textBox1.Text)); Bind(); } } 在工作流中移除activity using (WorkflowRuntime workflowRuntime = new WorkflowRuntime()) { AutoResetEvent waitHandle = new AutoResetEvent(false); workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { waitHandle.Set(); }; workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine(e.Exception.Message); waitHandle.Set(); }; WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1)); instance.Start(); // 检索此工作流实例的根活动。 // // 返回结果: // 一个 System.Workflow.ComponentModel.Activity 对象。 Activity WFActivity = instance.GetWorkflowDefinition(); //初始化 System.Workflow.ComponentModel.WorkflowChanges 类的新实例。 // // 参数: // rootActivity: // 工作流的根 System.Workflow.ComponentModel.Activity。 System.Workflow.ComponentModel.WorkflowChanges change = new WorkflowChanges(WFActivity); // 摘要: // 获取表示所有子活动的集合 System.Workflow.ComponentModel.ActivityCollection 的对象。 // // 返回结果: // 所有子活动的 System.Workflow.ComponentModel.ActivityCollection。 Activity activity = change.TransientWorkflow.Activities["codeActivity2"]; change.TransientWorkflow.Activities.Remove(activity); instance.ApplyWorkflowChanges(change); waitHandle.WaitOne(); Console.WriteLine(" 工作流执行完毕!"); } 使用记事本+wfc.exe制作工作流 using System; using System.Collections.Generic; using System.Text; using System.Workflow.Activities; using System.Workflow.ComponentModel; namespace WorkflowConsoleApplication2 { public class MySquentialWorkflow:SequentialWorkflowActivity { CodeActivity cdAc1, cdAc2; IfElseActivity ifAc; IfElseBranchActivity ifelseBranch1, ifelseBranch2; System.Workflow.Activities.CodeCondition codeCondition = new CodeCondition(); public bool BoolCondition { set; get; } public MySquentialWorkflow() { this.CanModifyActivities = true; codeCondition.Condition+=new EventHandler(codeCondition_Condition); this.Name="MySquentialWorkflow"; cdAc1 = new CodeActivity("mycodeActivity1"); cdAc1.ExecuteCode +=new EventHandler(cdAc1_ExecuteCode); cdAc2 = new CodeActivity("mycodeActivity2"); cdAc2.ExecuteCode+=new EventHandler(cdAc2_ExecuteCode); ifelseBranch1=new IfElseBranchActivity("branch1"); ifelseBranch1.Activities.Add(cdAc1); ifelseBranch2=new IfElseBranchActivity("branch2"); ifelseBranch1.Condition=codeCondition; ifelseBranch2.Activities.Add(cdAc2); ifAc = new IfElseActivity("myifelseActivity"); ifAc.Activities.Add(ifelseBranch1); ifAc.Activities.Add(ifelseBranch2); this.Activities.Add(ifAc); this.CanModifyActivities = false; } void codeCondition_Condition(object sender, ConditionalEventArgs e) { e.Result = BoolCondition; } void cdAc2_ExecuteCode(object sender, EventArgs e) { Console.WriteLine("---------current flow is false---------"); } void cdAc1_ExecuteCode(object sender, EventArgs e) { Console.WriteLine("---------current flow is true---------"); } } } 保存为MySquentialWorkflow.cs 在命令提示符下:Wfc.exe MySquentialWorkflow.cs target:assembly /out: MySquentialWorkflow.dll 在宿主程序中测试工作流: static void Main(string[] args) { using (WorkflowRuntime wfRuntime = new WorkflowRuntime()) { AutoResetEvent wait = new AutoResetEvent(false); wfRuntime.WorkflowTerminated +=delegate(object sender,WorkflowTerminatedEventArgs e) { Console.WriteLine(e.Exception.Message); wait.Set(); }; wfRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { wait.Set(); }; wfRuntime.StartRuntime(); Dictionary ds = new Dictionary(); ds.Add("BoolCondition", false); WorkflowInstance instance = wfRuntime.CreateWorkflow(typeof(MySquentialWorkflow), ds); instance.Start(); wait.WaitOne(); Console.Read(); } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 15 金币 [ 分享文档获得金币 ] 1 人已下载

下载文档