static void Main(string[] args) { WorkflowApplication wfApplication = new WorkflowApplication(new Activity1()); SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["ZhuangBPM"].ToString()); wfApplication.InstanceStore = instanceStore; InstanceView view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; wfApplication.PersistableIdle = (e) => { System.Console.WriteLine("persistableIdle:{0}", e.InstanceId); return PersistableIdleAction.Unload; }; wfApplication.Run(); Console.ReadKey(); }
public WorkflowService( IUsersService users ) { _users = users; T = NullLocalizer.Instance; Logger = NullLogger.Instance; SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(_users.ApplicationConnectionString); _wfApp = new WorkflowApplication(new XODB.Workflow.AssignResponsibility()); _wfApp.InstanceStore = store; XName wfHostTypeName = XName.Get("XODB", _users.ApplicationID.ToString()); Dictionary<XName, object> wfScope = new Dictionary<XName, object> { { workflowHostTypePropertyName, wfHostTypeName } }; _wfApp.AddInitialInstanceValues(wfScope); _wfApp.Extensions.Add(new ResponsibilityExtension()); List<XName> variantProperties = new List<XName>() { ResponsibilityExtension.xNS.GetName("CompanyID"), ResponsibilityExtension.xNS.GetName("ContactID") }; store.Promote("Responsibility", variantProperties, null); InstanceHandle handle = store.CreateInstanceHandle(null); var cmd = new CreateWorkflowOwnerCommand { InstanceOwnerMetadata = { {workflowHostTypePropertyName, new InstanceValue(wfHostTypeName)} } }; InstanceOwner owner = store.Execute(handle, cmd, TimeSpan.MaxValue).InstanceOwner; store.DefaultInstanceOwner = owner; handle.Free(); _wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e) { return PersistableIdleAction.Persist; }; _wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { foreach (var item in e.Outputs) { System.Diagnostics.Debug.WriteLine("Variable:{0} has value: {1}", item.Key, item.Value); } } }; var trackingParticipant = new TrackingHelper.DebugTrackingParticipant { TrackingProfile = TrackingHelper.SimpleProfile }; _wfApp.Extensions.Add(trackingParticipant); }
//end protected void btnEdit_ServerClick(object sender, EventArgs e) { if (((this.txtName.Value.Length == 0) || (this.uploadurl.Value.Length == 0)) || (this.selWorkFlow.SelectedValue.Length == 0)) { MessageBox.Show(this, "请您填写完整的信息"); } else { Model.SelectRecord selectRecord = new Model.SelectRecord("WorkFlow", "", "*", "where id='" + this.selWorkFlow.SelectedValue + "'"); DataTable table = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0]; string content = File.ReadAllText(System.Web.HttpContext.Current.Request.MapPath("../") + table.Rows[0]["URL"].ToString()); //ziyunhx add 2013-8-5 workflow Persistence //old code //WorkFlowTracking.instance = engineManager.createInstance(content, null, null); //WorkFlowTracking.instance.Run(); //new code instance = engineManager.createInstance(content, null, null); if (instanceStore == null) { instanceStore = new SqlWorkflowInstanceStore(SqlHelper.strconn); view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; } instance.InstanceStore = instanceStore; instance.Run(); //end Model.Document documents = new Model.Document { ID = id.Trim(), Name = this.txtName.Value.Trim(), URL = this.uploadurl.Value.Trim(), Remark = this.txtReMark.Value.Trim(), WID = this.selWorkFlow.SelectedValue, WStep = "0", Result = "0", UID = this.Session["admin"].ToString(), //ziyunhx add 2013-8-5 workflow Persistence //old code //FlowInstranceID = WorkFlowTracking.instance.Id, //new code FlowInstranceID = instance.Id, //end }; if (BLL.Document.DocumentUpdate(documents) == 1) { UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息成功"); MessageBox.ShowAndRedirect(this, "编辑公文成功!", "/document/DocumentList.aspx"); } else { UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "工作流管理", "编辑工作流" + documents.Name + "的信息失败"); MessageBox.Show(this, "编辑工作流失败"); } } }
static InstanceStore CreateInstanceStore() { string connectionString = ConfigurationManager.ConnectionStrings["InstanceStore"].ConnectionString; var instanceStore = new SqlWorkflowInstanceStore(connectionString); var instanceHandle = instanceStore.CreateInstanceHandle(); var ownerCommand = new CreateWorkflowOwnerCommand(); XNamespace hostNamespace = XNamespace.Get("urn:schemas-microsoft-com:System.Activities/4.0/properties"); XName hostKey = hostNamespace.GetName("WorkflowHostType"); var hostValue = new InstanceValue(XNamespace.Get("http://tempuri.org").GetName("SampleInstance")); ownerCommand.InstanceOwnerMetadata.Add(hostKey, hostValue); instanceStore.DefaultInstanceOwner = instanceStore.Execute( instanceHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner; instanceHandle.Free(); return instanceStore; }
public static Guid CreateAndRun(requestinfo requsetForm) { //工作流服务实例的状态信息持久保存到数据库中 //SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore("server=.;database=aspnetdb;uid=sa;pwd=0000"); SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(@"Data Source=.\SQLEXPRESS;Initial Catalog=aspnetdb;Integrated Security=True");//在宿主程序中首先我们创建SqlWorkflowInstanceStore的实例 InstanceView view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner;//对SqlWorkflowInstanceStore实例的各种配置 IDictionary<string, object> input = new Dictionary<string, object> { { "Request" , requsetForm } }; WorkflowApplication application = new WorkflowApplication(new DocumentPublish(), input); application.InstanceStore = instanceStore;//并将application的InstanceStore属性设置为该实例来指定使用的持久化存储 application.PersistableIdle = (e) =>//获取工作流实例处于空闲状态并且可被保留时调用 { instanceUnloaded.Set(); return PersistableIdleAction.Unload;//保持并且卸载工作流 }; application.Unloaded = (e) =>//获取或设置卸载当前工作流时调用 { instanceUnloaded.Set();//将事件设置为主终止状态允许其他的线程继续。 }; application.OnUnhandledException = (ex) =>//异常 { Console.Write("Exception"); return UnhandledExceptionAction.Terminate; }; Guid id = application.Id; //application.Persist(); application.Run(); instanceUnloaded.WaitOne();//阻止当前线程,直到收到信号 return id; }
/// <summary> /// 创建并启动一个工作流,在申请时候触发 /// </summary> /// <param name="meeting">申请时所填表单的数据</param> /// <returns>返回一个Guid</returns> public static Guid CreateAndRun(Model.Meeting meeting, Dictionary<int, int> d_EquipmentCount,Dictionary<string,string> MeetingUserNameAndEmail,Model.MeetingRoom MeetingRoomIDAndName) { SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connectionString); InstanceView view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(),TimeSpan.FromDays(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; IDictionary<string, object> input = new Dictionary<string, object>(); input.Add("Request",meeting); input.Add("EquipmentCount",d_EquipmentCount); input.Add("MeetingUserEmailFrom", MeetingUserNameAndEmail); input.Add("MeetingRoomIDAndName", MeetingRoomIDAndName); WorkflowApplication application = new WorkflowApplication(new MeetingApply(),input); application.InstanceStore = instanceStore; application.PersistableIdle = (e) => { instanceUnloaded.Set(); return PersistableIdleAction.Unload; }; application.Unloaded = (e) => { instanceUnloaded.Set(); }; application.OnUnhandledException = (ex) => { return UnhandledExceptionAction.Terminate; }; Guid id = application.Id; application.Persist(); application.Run(); instanceUnloaded.WaitOne(); return id; }
//end protected void btnEdit_ServerClick(object sender, EventArgs e) { if (this.DropDown_sp.SelectedValue.Length == 0) { MessageBox.Show(this, "请您选择审核结果"); } else { Model.SelectRecord selectRecords = new Model.SelectRecord("view_DocumentInfo", "", "*", "where id='" + id + "'"); DataTable dt = BLL.SelectRecord.SelectRecordData(selectRecords).Tables[0]; //ziyunhx add 2013-8-5 workflow Persistence if (dt == null) { return; } Model.SelectRecord selectRecord = new Model.SelectRecord("WorkFlow", "", "*", "where id='" + dt.Rows[0]["WorkFlowID"].ToString() + "'"); DataTable table = BLL.SelectRecord.SelectRecordData(selectRecord).Tables[0]; string content = File.ReadAllText(System.Web.HttpContext.Current.Request.MapPath("../") + table.Rows[0]["URL"].ToString()); instance = engineManager.createInstance(content, null, null); if (instanceStore == null) { instanceStore = new SqlWorkflowInstanceStore(SqlHelper.strconn); view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; } instance.InstanceStore = instanceStore; Guid guid = new Guid(dt.Rows[0]["FlowInstranceID"].ToString()); instance.Load(guid); //end if (this.DropDown_sp.SelectedValue == "true") { string[] s = dt.Rows[0]["OID"].ToString().Split(new char[] { ',' }); if (s[s.Length - 1] == "1") { Model.SelectRecord selectExecut = new Model.SelectRecord("WorkFlowExecution", "", "*", "where DID='" + id + "' and step ='" + dt.Rows[0]["WStep"].ToString() + "' and UID='"+this.Session["admin"].ToString()+"'"); DataTable executdt = BLL.SelectRecord.SelectRecordData(selectExecut).Tables[0]; if (executdt.Rows.Count > 0) { MessageBox.ShowAndRedirect(this, "该公文您已审核,请等待其他人审核!", "/document/DocumentList.aspx"); } else { Model.SelectRecord selectExecutCount = new Model.SelectRecord("WorkFlowExecution", "", "distinct UID", "where DID='" + id + "' and step ='" + dt.Rows[0]["WStep"].ToString() + "'"); DataTable dtcount = BLL.SelectRecord.SelectRecordData(selectExecutCount).Tables[0]; string where = "where IsState=2 AND (1=2 "; string[] str = dt.Rows[0]["OID"].ToString().Split(new char[] { ',' }); for (int j = 1; j < str.Length-1; j++) { where += "OR OID like '%" + str[j].ToString() + "%' "; } where += ") order by id desc"; Model.SelectRecord selectUserCount = new Model.SelectRecord("Users", "", "ID", where); DataTable usercount = BLL.SelectRecord.SelectRecordData(selectUserCount).Tables[0]; if (dtcount.Rows.Count + 1 == usercount.Rows.Count) { if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1) { instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString()); } } } } else { //一旦审批未通过,删除该公文当前流转步骤信息 BLL.GeneralMethods.GeneralDelDB("WorkFlowExecution", "where DID ='" + id + "' and step='" + dt.Rows[0]["WStep"].ToString() + "'"); if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1) { instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString()); } } Model.WorkFlowExecution workexe = new Model.WorkFlowExecution { DID = dt.Rows[0]["ID"].ToString(), UID = this.Session["admin"].ToString(), step = dt.Rows[0]["WStep"].ToString(), Remark = this.txtSP.Value.Trim(), Result = "1", }; BLL.WorkFlowExecution.Add(workexe); } else { Model.WorkFlowExecution workexe = new Model.WorkFlowExecution { DID = dt.Rows[0]["ID"].ToString(), UID = this.Session["admin"].ToString(), step = dt.Rows[0]["WStep"].ToString(), Remark = this.txtSP.Value.Trim(), Result = "2", }; BLL.WorkFlowExecution.Add(workexe); if (instance.GetBookmarks().Count(p => p.BookmarkName == dt.Rows[0]["value"].ToString()) == 1) { instance.ResumeBookmark(dt.Rows[0]["value"].ToString(), this.DropDown_sp.SelectedValue.ToString()); } } UserOperatingManager.InputUserOperating(this.Session["admin"].ToString(), "公文管理", "公文审核" + dt.Rows[0]["Name"].ToString() + "的信息成功"); MessageBox.ShowAndRedirect(this, "审核公文成功!", "/document/DocumentList.aspx"); instance.Unload(); } }
/// <summary> /// 根据指定模板启动工作流 /// </summary> private static void StartWorkFlow(Guid wfTemplateId, WfInstanceEntity wfInstance, WfInstanceStatesEntity wfInstanceStatesEntity, Guid parentWfInstaceId, string dealPersons) { try { var connectionString = DataHelper.CONNECTION_STRING; WorkflowApplication instance; var dealPersonInfo = dealPersons; var flowData = new FlowData() { WFInstance = wfInstance, WfInstanceStates = wfInstanceStatesEntity, DealPersonInfo = dealPersonInfo, ParallelBranchesCount = 0 }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, {"DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper()} }; instance = GetStartWorkflowApplicationInstanceByTemplateId(wfTemplateId, inputParameter); if (instance != null) { ((FlowData)inputParameter["FlowDataParm"]).WFInstance.InstanceID = instance.Id; ((FlowData)inputParameter["FlowDataParm"]).WfInstanceStates.InstanceID = instance.Id; ((FlowData)inputParameter["FlowDataParm"]).WFInstance.TemplateID = wfTemplateId; var instanceStore = new SqlWorkflowInstanceStore(connectionString); InstanceView view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; // instance.Aborted += InstanceAborted; if (parentWfInstaceId != Guid.Empty) //写流程实例关系表 { //WriteWfInstanceRelation(parentWfInstaceId,instance.Id,wfInstance.FormID); ((FlowData)inputParameter["FlowDataParm"]).WFInstance.ParentInstanceId = parentWfInstaceId; } instance.Run(); } else { throw new Exception("未找到对应的流程模板!请与系统管理员联系。"); } } catch (Exception ex) { LogWritter.WriteSystemExceptionLog(ex); throw new Exception("生成流程异常:" + ex.Message, ex.InnerException); } }
/// <summary> /// 根据指定模板启动工作流 /// </summary> private static void StartWorkFlow(Guid wfTemplateId, WfInstanceEntity wfInstance, WfInstanceStatesEntity wfInstanceStatesEntity) { try { var connectionString = Common.GetConnectString(); WorkflowApplication instance; var flowData = new FlowData() { WFInstance = wfInstance, WfInstanceStates = wfInstanceStatesEntity }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, {"DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper()} }; instance = GetStartWorkflowApplicationInstanceByTemplateId(wfTemplateId, inputParameter); if (instance != null) { ((FlowData)inputParameter["FlowDataParm"]).WFInstance.InstanceID = instance.Id; ((FlowData)inputParameter["FlowDataParm"]).WfInstanceStates.InstanceID = instance.Id; ((FlowData)inputParameter["FlowDataParm"]).WFInstance.TemplateID = wfTemplateId; var instanceStore = new SqlWorkflowInstanceStore(connectionString); InstanceView view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; // instance.Aborted += InstanceAborted; instance.Run(); } else { throw new Exception("未找到对应的流程模板!请与系统管理员联系。"); } } catch (Exception ex) { LogWritter.WriteSystemExceptionLog(ex); throw new Exception("生成流程异常:" + ex.Message, ex.InnerException); } }
static void SetupInstanceStore() { instanceStore = new SqlWorkflowInstanceStore(@"Data Source=.\SQLEXPRESS;Initial Catalog=SampleInstanceStore;Integrated Security=True;Asynchronous Processing=True"); InstanceHandle handle = instanceStore.CreateInstanceHandle(); InstanceView view = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); handle.Free(); instanceStore.DefaultInstanceOwner = view.InstanceOwner; }
private static SqlWorkflowInstanceStore CreateInstanceStore(WorkflowHandlerBase workflowInstance) { var store = new SqlWorkflowInstanceStore(ConnectionString); var ownerHandle = store.CreateInstanceHandle(); var wfHostTypeName = GetWorkflowHostTypeName(workflowInstance); var WorkflowHostTypePropertyName = GetWorkflowHostTypePropertyName(); var ownerCommand = new CreateWorkflowOwnerCommand() { InstanceOwnerMetadata = { { WorkflowHostTypePropertyName, new InstanceValue(wfHostTypeName) } } }; store.DefaultInstanceOwner = store.Execute(ownerHandle, ownerCommand, TimeSpan.FromSeconds(30)).InstanceOwner; return store; }