private static void ProcessHandler(int userId) { //获取待处理的流程 DbContext dbcontext = new DbContext(); var lst = dbcontext.FlowInfo.Where(x => x.RowState == RowStates.正常) .Where(x => x.HandlerId == userId) .ToList(); if (lst.Count <= 0) { Console.WriteLine("没有待处理的流程"); return; } int indexTMP = 0; lst.ForEach(x => Console.WriteLine(string.Format("索引:{0},流程ID:{1},处理人ID:{2},处理人:{3},表单:{4}", indexTMP++, x.WFInstanceId, x.HandlerId, x.HandlerName, x.FlowContext))); Console.WriteLine("请输入流程索引"); int index = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入审批意见"); Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.意, HandlerOptions.意.ToString())); Console.WriteLine(string.Format("{0}---{1}", (int)HandlerOptions.驳回, HandlerOptions.驳回.ToString())); HandlerOptions opt = (HandlerOptions)Convert.ToInt32(Console.ReadLine()); //组织表单数据 var formData = Newtonsoft.Json.Linq.JObject.Parse(lst[index].FlowContext); formData["HandlerOption"] = Newtonsoft.Json.Linq.JToken.FromObject(opt);//demo,这个键写死 //启动流程 System.Activities.WorkflowApplication wfa = new System.Activities.WorkflowApplication(new LeaveFlow()); InitWF(wfa); wfa.Load(lst[index].WFInstanceId); wfa.ResumeBookmark(lst[index].BookmarkName, formData); }
static void LoadAndCompleteInstance() { string input = Console.ReadLine(); WorkflowApplication application = new WorkflowApplication(activity); application.InstanceStore = instanceStore; application.Completed = (workflowApplicationCompletedEventArgs) => { Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState); }; application.Unloaded = (workflowApplicationEventArgs) => { Console.WriteLine("WorkflowApplication has Unloaded\n"); instanceUnloaded.Set(); }; application.Load(id); //this resumes the bookmark setup by readline application.ResumeBookmark(readLineBookmark, input); instanceUnloaded.WaitOne(); }
public SESampleProcess2WorkFlow(string instanceId) : base() { SESampleProcess2 wf = new SESampleProcess2(); app = new WorkflowApplication(wf); app.InstanceStore = TrackingSqlWorkflowInstanceStore.generateOne(); Guid g=new Guid(instanceId); app.Load(g); this.MakeAsyncSync(); }
//第一步以后,后续所有流程步骤的入口 private static void ApproveOp(bool op, Guid workflowId, HzWorkFlowContext hzwfContext) { System.Xaml.XamlXmlReaderSettings st = new System.Xaml.XamlXmlReaderSettings() { LocalAssembly = System.Reflection.Assembly.GetExecutingAssembly() }; System.Activities.Activity act = null; using (var reader = new System.Xaml.XamlXmlReader(workflowName, st)) { act = System.Activities.XamlIntegration.ActivityXamlServices.Load(reader); } var wfa = new System.Activities.WorkflowApplication(act); ConfigWfa(wfa); wfa.Load(workflowId); wfa.ResumeBookmark(bookmark, op); }
/// <summary> /// 加载工作流 /// </summary> /// <param name="id">工作流的唯一标示</param> /// <param name="bookMark">标签名称</param> /// <param name="ids">恢复指定名称的书签的时候,传入的参数</param> /// <returns>工作流的加载的状态</returns> public string Load(string id, object inputs = null) { _instanceStore = new SqlWorkflowInstanceStore(connectionString); InstanceView view = _instanceStore.Execute (_instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); _instanceStore.DefaultInstanceOwner = view.InstanceOwner; WorkflowApplication i = new WorkflowApplication(ActivityXamlServices.Load(path)); i.InstanceStore = _instanceStore; i.PersistableIdle = (waiea) => PersistableIdleAction.Unload; i.Load(new Guid(id)); return i.ResumeBookmark(bookMark, inputs).GetString(); }
public static void Start(Guid? instanceId) { var instance = new WorkflowApplication(new Workflow1()); instance.PersistableIdle += OnPersistableIdle; instance.Completed += OnCompleted; instance.Idle += OnIdle; instance.Unloaded += OnUnloaded; // UNDONE: (maj) rather than using parameters, first check to see if there is an incomplete persisted file // and start from there if (!instanceId.HasValue) { instance.InstanceStore = new XmlWorkflowInstanceStore(instance.Id); instance.Run(); } else { instance.InstanceStore = new XmlWorkflowInstanceStore(instanceId.Value); instance.Load(instanceId.Value); instance.Run(); } }
//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(); } }
private void cmdUpdateInstance_Click(object sender, RoutedEventArgs e) { SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(); instanceStore.ConnectionString = @"Data Source=(LocalDB)\v11.0;Initial Catalog=WFPersist;Integrated Security=True"; WorkflowApplicationInstance wfInstance = WorkflowApplication.GetInstance(new Guid(txtUpdateInstance.Text), instanceStore); DataContractSerializer s = new DataContractSerializer(typeof(DynamicUpdateMap)); using (FileStream fs = File.Open(txtUpdateMapFile.Text, FileMode.Open)) { updateMap = s.ReadObject(fs) as DynamicUpdateMap; } var wfApp = new WorkflowApplication(new MovieRentalProcess(), new WorkflowIdentity { Name = "v2MovieRentalProcess", Version = new System.Version(2, 0, 0, 0) }); IList<ActivityBlockingUpdate> act; if (wfInstance.CanApplyUpdate(updateMap, out act)) { wfApp.Load(wfInstance, updateMap); wfApp.Unload(); } }
/// <summary> /// 驱动并发的子流程 /// </summary> private static bool ParalleStateDealNew(WfInstanceEntity wfInstanceEntity, WfInstanceStatesEntity wfInstanceStatesEntity, List<DealPersonInfo> dealPersonInfo) { try { var sql = string.Format( " select WfInstanceId from WF_Messages with (nolock) where FormID='{0}' and ReceiveDeptId='{1}' and ReceiveUserId='{2}' and MessageType={3} ", wfInstanceEntity.FormID, wfInstanceStatesEntity.TransactDepartmentID, wfInstanceStatesEntity.TransactUserID, (int)EnumWfMessageType.WaitForDo); var instanceId = DataHelper.ExecuteScalar(sql) == null ? Guid.Empty : new Guid(DataHelper.ExecuteScalar(sql).ToString()); var sb = new StringBuilder(); if (dealPersonInfo != null && dealPersonInfo.Count > 0) { foreach (var personInfo in dealPersonInfo) { sb.Append(personInfo.PersonId + "," + personInfo.PersonName + "," + personInfo.DeptId + "," + personInfo.DeptName); sb.Append("$"); } } wfInstanceEntity.InstanceID = instanceId; wfInstanceStatesEntity.InstanceID = instanceId; var flowData = new FlowData { WFInstance = wfInstanceEntity, WfInstanceStates = wfInstanceStatesEntity, ParallelBranchesCount = 0, DealPersonInfo = sb.ToString() }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, { "DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper() } }; var cswfTemplateEntity = WfTemplateDataBusiness.GetWfTemplateDataByTemplateID(wfInstanceEntity.TemplateID); var activity = GetActivity(cswfTemplateEntity.TemplateData); var instance = new WorkflowApplication(activity); var instanceStore = new SqlWorkflowInstanceStore(DataHelper.CONNECTION_STRING); instanceStore.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry; instanceStore.HostLockRenewalPeriod = TimeSpan.FromSeconds(30); //解决再次load时lock的问题 instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; instance.Load(wfInstanceEntity.InstanceID); instance.ResumeBookmark("GetFlowData", inputParameter); return false; } catch (Exception ex) { LogWritter.WriteSystemExceptionLog(ex); throw ex; } }
public void WhenPersistedInstanceLoadedRunEpisodeShouldComplete() { var activity = new TestBookmark<int> { BookmarkName = "Test" }; var workflowApplication = new WorkflowApplication(activity) { InstanceStore = new MemoryStore(), PersistableIdle = args => PersistableIdleAction.Unload, }; // Episodes can end with until unloaded, aborted, completed, timeout // Run episode until unloaded because of persistable idle event var workflowIdleEpisodeResult = workflowApplication.RunEpisode(Constants.Timeout) as WorkflowIdleEpisodeResult; Assert.IsNotNull(workflowIdleEpisodeResult); // Cannot resume the same WorkflowApplication - it will cause a System.InvalidOperationException // Message=WorkflowInstance (guid) cannot be modified after it has started running. var workflowApplicationResume = new WorkflowApplication(activity) { InstanceStore = new MemoryStore(), }; // Load the instance with a new WorkflowApplication workflowApplicationResume.Load(workflowIdleEpisodeResult.InstanceId); // Resume and complete var result = workflowApplicationResume.ResumeEpisodeBookmark("Test", 1); Assert.IsInstanceOfType(result, typeof(WorkflowCompletedEpisodeResult)); Assert.AreEqual(ActivityInstanceState.Closed, result.State); AssertOutArgument.AreEqual(((WorkflowCompletedEpisodeResult)result).Outputs, "Result", 1); }
static void Run() { AutoResetEvent applicationUnloaded = new AutoResetEvent(false); WorkflowApplication application = new WorkflowApplication(workflow); application.InstanceStore = instanceStore; SetupApplication(application, applicationUnloaded); StepCountExtension stepCountExtension = new StepCountExtension(); application.Extensions.Add(stepCountExtension); application.Run(); Guid id = application.Id; applicationUnloaded.WaitOne(); while (stepCountExtension.CurrentCount < totalSteps) { application = new WorkflowApplication(workflow); application.InstanceStore = instanceStore; SetupApplication(application, applicationUnloaded); stepCountExtension = new StepCountExtension(); application.Extensions.Add(stepCountExtension); application.Load(id); string input = Console.ReadLine(); application.ResumeBookmark(echoPromptBookmark, input); applicationUnloaded.WaitOne(); } }
private TResponse ContinueWorkflow_todelete <TRequest, TResponse>(TRequest request, string OperationName) { TimeSpan timeOut = TimeSpan.FromMinutes(1); Action waitOne = delegate() { s_syncEvent = null; if (instanceStore != null) { s_syncEvent = s_unloadedEvent; s_unloadedEvent.WaitOne(); } else { s_syncEvent = s_idleEvent; s_idleEvent.WaitOne(); } }; WorkflowInstanceContext instanceContext = new WorkflowInstanceContext() { Request = request, Response = default(TResponse) }; invokeMode = WorkflowInvokeMode.ResumeBookmark; WorkflowApplication wfApp = null; Guid wfId = Guid.Empty; while (invokeMode != WorkflowInvokeMode.None) { if (invokeMode == WorkflowInvokeMode.Run) { wfApp = createWorkflowApplication(instanceContext); wfId = wfApp.Id; resetEvents(); wfApp.Run(timeOut); waitOne(); } else if (invokeMode == WorkflowInvokeMode.ResumeBookmark) { wfApp = createWorkflowApplication(instanceContext); resetEvents(); this.WorkflowId = (wfApp.InstanceStore as IStoreCorrelation).Correlation.CorrelationId; wfApp.Load(this.WorkflowId, timeOut); var isWaiting = wfApp.GetBookmarks().FirstOrDefault(b => b.BookmarkName == OperationName); if (isWaiting != null) { wfApp.ResumeBookmark(OperationName, "bookmark data", timeOut); waitOne(); } else { throw new Exception($"Bookmark {OperationName} missing on workflow with id {wfApp.Id}"); } } } ; TResponse response = default(TResponse); try { response = (TResponse)instanceContext.Response; } catch { } return(response); }
/// <summary> /// Invoked when a web request arrives. /// </summary> public void ProcessRequest(HttpContext context) { try { // bind ourselves to the context Context = context; // request was for a resource if (Request[ResourceQueryKey] != null) { // handle it and return, no need to deal with workflow ProcessResourceRequest(Request[ResourceQueryKey]); return; } // obtain our activity instance Activity = CreateActivity(); // configure application WorkflowApplication = Request[InstanceIdQueryKey] == null ? new WorkflowApplication(Activity, GetArguments()) : new WorkflowApplication(Activity); WorkflowApplication.Extensions.Add<ITwilioContext>(() => this); WorkflowApplication.SynchronizationContext = new SynchronizedSynchronizationContext(); WorkflowApplication.InstanceStore = CreateInstanceStore(); WorkflowApplication.Aborted = OnAborted; WorkflowApplication.Completed = OnCompleted; WorkflowApplication.Idle = OnIdle; WorkflowApplication.OnUnhandledException = OnUnhandledException; WorkflowApplication.PersistableIdle = OnPersistableIdle; WorkflowApplication.Unloaded = OnUnloaded; // attempt to resolve current instance id and reload workflow state if (Request[InstanceIdQueryKey] != null) WorkflowApplication.Load(Guid.Parse(Request[InstanceIdQueryKey]), Timeout); // postback to resume a bookmark if (Request[BookmarkQueryKey] != null) WorkflowApplication.ResumeBookmark(Request[BookmarkQueryKey], GetPostData(), Timeout); else // begin running the workflow from the start WorkflowApplication.Run(Timeout); // throw exception if (UnhandledExceptionInfo != null) UnhandledExceptionInfo.Throw(); // strip off temporary attributes foreach (var element in TwilioResponse.DescendantsAndSelf()) foreach (var attribute in element.Attributes()) if (attribute.Name.Namespace == tmpNs) attribute.Remove(); // write finished twilio output Response.ContentType = "text/xml"; using (var wrt = XmlWriter.Create(Response.Output)) TwilioResponse.WriteTo(wrt); // if we've reached the end, no need to force unload WorkflowApplication = null; } finally { // clean up application if possible if (WorkflowApplication != null) { try { WorkflowApplication.Unload(Timeout); WorkflowApplication = null; } catch { // ignore } } } }
private void QuitGame_Click(object sender, EventArgs e) { if (WorkflowInstanceId == Guid.Empty) { MessageBox.Show("Please select a workflow."); return; } WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store); // Use the persisted WorkflowIdentity to retrieve the correct workflow // definition from the dictionary. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity); // Associate the WorkflowApplication with the correct definition WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity); // Configure the extensions and lifecycle handlers ConfigureWorkflowApplication(wfApp); // Load the workflow. wfApp.Load(instance); // Terminate the workflow. wfApp.Terminate("User resigns."); }
static void Main(string[] args) { SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(connectionString); WorkflowApplication.CreateDefaultInstanceOwner(store, null, WorkflowIdentityFilter.Any); IDictionary<WorkflowIdentity, DynamicUpdateInfo> updateMaps = LoadMaps(); foreach (Guid id in GetIds()) { // Get a proxy to the instance. WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(id, store); Console.WriteLine("Inspecting: {0}", instance.DefinitionIdentity); // Only update v1 workflows. if (instance.DefinitionIdentity != null && instance.DefinitionIdentity.Version.Equals(new Version(1, 0, 0, 0))) { DynamicUpdateInfo info = updateMaps[instance.DefinitionIdentity]; // Associate the persisted WorkflowApplicationInstance with // a WorkflowApplication that is configured with the updated // definition and updated WorkflowIdentity. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(info.newIdentity); WorkflowApplication wfApp = new WorkflowApplication(wf, info.newIdentity); // Apply the Dynamic Update. wfApp.Load(instance, info.updateMap); // Persist the updated instance. wfApp.Unload(); Console.WriteLine("Updated to: {0}", info.newIdentity); } else { // Not updating this instance, so unload it. instance.Abandon(); } } }
private static void RunInstance(Guid guid, string bookmark, Activity activity, object args) { SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(ConnectString); WorkflowApplication application = new WorkflowApplication(activity); application.InstanceStore = instanceStore; application.PersistableIdle = (e) => { return PersistableIdleAction.Unload; }; application.Load(guid); application.ResumeBookmark(bookmark, args); }
/// <summary> /// 重新启动工作流,是审核过程中保存审核结果的必要流程 /// </summary> /// <param name="meeting">传入一个Meeting对象,主要是取里面的InstanceID和改变后的Status(这个status是标识meetingAndRoom的)</param> public static void ProcessEquipmentArr(Model.Meeting meeting) { //SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connectionString); //WorkflowApplication application1 = new WorkflowApplication(new MeetingApply()); //application1.InstanceStore = instanceStore; //application1.Completed = (workflowComplete) => //{ //}; //application1.Unloaded = (workflowUnloaded) => //{ // instanceUnloaded.Set(); //}; //application1.PersistableIdle = (e) => // { // instanceUnloaded.Set(); // return PersistableIdleAction.Unload; // }; //application1.Load(meeting.WFID); //application1.ResumeBookmark("MeetingApply", meeting.MeetingStatus); //instanceUnloaded.WaitOne(); SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connectionString); IDictionary<string, object> input = new Dictionary<string, object>() { { "Request", meeting } }; WorkflowApplication application1 = new WorkflowApplication(new MeetingApply()); application1.InstanceStore = instanceStore; application1.Completed = (workflowComplete) => { }; application1.Unloaded = (workflowUnloaded) => { instanceUnloaded.Set(); }; application1.PersistableIdle = (e) => { instanceUnloaded.Set(); return PersistableIdleAction.Unload; }; application1.Load(meeting.WFID); application1.ResumeBookmark("ArrEquipment", meeting.MeetingStatus); instanceUnloaded.WaitOne(); }
/// <summary> /// /// </summary> private static void DriveWorkFlowofChange(WfInstanceEntity wfInstanceEntity, WfInstanceStatesEntity wfInstanceStatesEntity) { var sql = string.Format(" select count(FormId) from WF_ModifyStatesInstance where FormId='{0}' and ExcuteState<>{1} ", wfInstanceEntity.FormID, (int)ExcuteState.Excuted); if (Convert.ToInt32(DataHelper.ExecuteScalar(sql)) > 0) { //var stateId = GetCurrentState(wfInstanceEntity.FormID); var res = WfModifyStatesInstanceBusiness.Deal(wfInstanceEntity.FormID.ToString(), wfInstanceStatesEntity.WfDealWayId.ToString(), wfInstanceStatesEntity.TransactUserID.ToString(), wfInstanceStatesEntity.StateDescription); var result = DataHelper.ExecuteScalar(sql); //所有状态都执行完了,继续主工作流程 if (res == 0 || Convert.ToInt32(result) == 0) { var flowData = new FlowData { WFInstance = wfInstanceEntity, WfInstanceStates = wfInstanceStatesEntity }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, {"DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper()} }; var cswfTemplateEntity = WfTemplateDataBusiness.GetWfTemplateDataByTemplateID(wfInstanceEntity.TemplateID); var activity = GetActivity(cswfTemplateEntity.TemplateData); var instance = new WorkflowApplication(activity); var instanceStore = new SqlWorkflowInstanceStore(Common.GetConnectString()); instanceStore.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry; instanceStore.HostLockRenewalPeriod = TimeSpan.FromSeconds(30); //解决再次load时lock的问题 instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; instance.Load(wfInstanceEntity.InstanceID); instance.ResumeBookmark("GetFlowData", inputParameter); } } else //按照原来的处理方式处理 { var flowData = new FlowData { WFInstance = wfInstanceEntity, WfInstanceStates = wfInstanceStatesEntity }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, {"DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper()} }; var cswfTemplateEntity = WfTemplateDataBusiness.GetWfTemplateDataByTemplateID(wfInstanceEntity.TemplateID); var activity = GetActivity(cswfTemplateEntity.TemplateData); var instance = new WorkflowApplication(activity); var instanceStore = new SqlWorkflowInstanceStore(Common.GetConnectString()); instanceStore.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry; instanceStore.HostLockRenewalPeriod = TimeSpan.FromSeconds(30); //解决再次load时lock的问题 instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; instance.Load(wfInstanceEntity.InstanceID); instance.ResumeBookmark("GetFlowData", inputParameter); } }
public static void RunArrangeDrawOutFrom(ArrangeDrawOutFrom form) { SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(@"server=.\SQLEXPRESS;database=aspnetdb;uid=sa;pwd=123456"); WorkflowApplication application1 = new WorkflowApplication(new UseCarApply()); application1.InstanceStore = instanceStore; application1.Completed = (workflowApplicationCompletedEventArgs) => { Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState); }; application1.PersistableIdle = (e) => { instanceUnloaded.Set(); return PersistableIdleAction.Unload; }; application1.Unloaded = (workflowApplicationEventArgs) => { Console.WriteLine("WorkflowApplication has Unloaded\n"); instanceUnloaded.Set(); }; application1.Load(form.WFID); application1.ResumeBookmark("WaitArrangeDrawOut", form); instanceUnloaded.WaitOne(); Console.ReadLine(); }
/// <summary> /// Runs this instance. /// </summary> public override void Run() { Trace.WriteLine("Starting processing of messages"); // Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump. this.Client.OnMessage( receivedMessage => { try { this.resetEvent = new ManualResetEvent(false); // Process the message Trace.WriteLine( "Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString()); // Name of workflow to trigger. var workflowToTrigger = receivedMessage.Properties["workflowName"]; // Prepare input message for Workflow. var channelData = new ChannelData { Payload = receivedMessage.GetBody<HostQueueMessage>() }; this.arrivedMessage = channelData.Payload; // You can save the workflow xaml externally (usually database). See this. var workflowXaml = File.ReadAllText($"{workflowToTrigger}.txt"); if (!string.IsNullOrWhiteSpace(workflowXaml)) { //// 5. Compose WF Application. var workflowApplication = new WorkflowApplication( Routines.CreateWorkflowActivityFromXaml(workflowXaml, this.GetType().Assembly), new Dictionary<string, object> { { "ChannelData", channelData } }); //// 6. Extract Request Identifier to set it as identifier of workflow. this.SetupWorkflowEnvironment( workflowApplication, channelData.Payload.WorkflowIdentifier); //// 7. Test whether this is a resumed bookmark or a fresh message. if (channelData.Payload.IsBookmark) { //// 8.1. Make sure there is data for this request identifier in storage to avoid errors due to transient errors. if (null != this.repository.GetById( "WorkflowInstanceStoreData", channelData.Payload.WorkflowIdentifier.ToString())) { //// Prepare a new workflow instance as we need to resume bookmark. var bookmarkedWorkflowApplication = new WorkflowApplication( Routines.CreateWorkflowActivityFromXaml( workflowXaml, this.GetType().Assembly)); this.SetupWorkflowEnvironment( bookmarkedWorkflowApplication, channelData.Payload.WorkflowIdentifier); //// 9. Resume bookmark and supply input as is from channel data. bookmarkedWorkflowApplication.Load(channelData.Payload.WorkflowIdentifier); //// 9.1. If workflow got successfully completed, remove the host message. if (BookmarkResumptionResult.Success == bookmarkedWorkflowApplication.ResumeBookmark( bookmarkedWorkflowApplication.GetBookmarks().Single().BookmarkName, channelData, TimeSpan.FromDays(7))) { Trace.Write( Routines.FormatStringInvariantCulture("Bookmark successfully resumed.")); this.resetEvent.WaitOne(); this.Client.Complete(receivedMessage.LockToken); return; } } else { //// This was a transient error. Trace.Write(Routines.FormatStringInvariantCulture("Error")); } } //// 10. Run workflow in case of normal execution. workflowApplication.Run(TimeSpan.FromDays(7)); Trace.Write( Routines.FormatStringInvariantCulture( "Workflow for request id has started execution")); this.resetEvent.WaitOne(); } } catch { // Handle any message processing specific exceptions here } }); this.CompletedEvent.WaitOne(); }
public static void RunCheckCheck(Guid id, ReviewCheckCheck Form) { SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(@"server=.\SQLEXPRESS;database=aspnetdb;uid=sa;pwd=123456"); WorkflowApplication application2 = new WorkflowApplication(new DocumentPublish()); application2.InstanceStore = instanceStore; application2.Completed = (workflowApplicationCompletedEventArgs) => { Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState); instanceUnloaded.Set(); }; application2.PersistableIdle = (e) => { instanceUnloaded.Set(); return PersistableIdleAction.Unload; }; application2.Unloaded = (workflowApplicationEventArgs) => { Console.WriteLine("WorkflowApplication has Unloaded\n"); instanceUnloaded.Set(); }; application2.Load(id); application2.ResumeBookmark("WaitCheckingChecking", Form); instanceUnloaded.WaitOne(); Console.ReadLine(); }
private void btnComplete_Click(object sender, RoutedEventArgs e) { if (lstLeads.SelectedIndex >= 0) { Assignment a = lstLeads.Items[lstLeads.SelectedIndex] as Assignment; a.Remarks = txtRemarks.Text; Guid id = a.WorkflowID; // Reload the workflow instance WorkflowApplication i = new WorkflowApplication(new WorkAssignment()); SetupInstance(i); i.Load(id); // Resume the instance from the last bookmark try { i.ResumeBookmark("GetCompletion", a); } catch (Exception e2) { AddEvent(e2.Message); } } }
// load and resume a workflow instance. If the instance is in memory, // will return the version from memory. If not, will load it from the // persistent store public WorkflowApplication LoadInstance(Guid instanceId) { // if the instance is in memory, return it if (this.instances.ContainsKey(instanceId)) return this.instances[instanceId]; // load the instance XmlWorkflowInstanceStore instStore = new XmlWorkflowInstanceStore(instanceId); WorkflowApplication instance = new WorkflowApplication(new PurchaseProcessWorkflow()); instance.InstanceStore = instStore; instance.Completed += OnWorkflowCompleted; instance.Idle += OnIdle; // add a tracking participant instance.Extensions.Add(new SaveAllEventsToTestFileTrackingParticipant()); // add the instance to the list of running instances in the host instance.Load(instanceId); this.instances.Add(instanceId, instance); return instance; }
private void EnterGuess_Click(object sender, EventArgs e) { if (WorkflowInstanceId == Guid.Empty) { MessageBox.Show("Please select a workflow."); return; } int guess; if (!Int32.TryParse(Guess.Text, out guess)) { MessageBox.Show("Please enter an integer."); Guess.SelectAll(); Guess.Focus(); return; } WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store); // Use the persisted WorkflowIdentity to retrieve the correct workflow // definition from the dictionary. Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity); // Associate the WorkflowApplication with the correct definition WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity); // Configure the extensions and lifecycle handlers. // Do this before the instance is loaded. Once the instance is // loaded it is too late to add extensions. ConfigureWorkflowApplication(wfApp); // Load the workflow. wfApp.Load(instance); // Resume the workflow. wfApp.ResumeBookmark("EnterGuess", guess); // Clear the Guess textbox. Guess.Clear(); Guess.Focus(); }
private static void DriveWorkFlowNew(WfInstanceEntity wfInstanceEntity, WfInstanceStatesEntity wfInstanceStatesEntity, List<DealPersonInfo> dealPersonInfo, List<Guid> parallelDeptGuid) { try { var sb = new StringBuilder(); if (dealPersonInfo != null && dealPersonInfo.Count > 0) { foreach (var personInfo in dealPersonInfo) { sb.Append(personInfo.PersonId + "," + personInfo.PersonName + "," + personInfo.DeptId + "," + personInfo.DeptName); sb.Append("$"); } } var parallelBranchesCount = 0; if (wfInstanceEntity.CurrentStateType == (int)EnumWfStateType.Parllel) //并行状态处理 { if (dealPersonInfo != null && dealPersonInfo.Count > 0) { parallelBranchesCount = dealPersonInfo.Count; } } //var isContinueWf = true; //if (wfInstanceEntity.CurrentStateType == (int) EnumWfStateType.Parllel) //并行状态处理 //{ // isContinueWf = ParalleStateDealNew(wfInstanceEntity, wfInstanceStatesEntity, dealPersonInfo); //} //if (isContinueWf) //{ var flowData = new FlowData { WFInstance = wfInstanceEntity, WfInstanceStates = wfInstanceStatesEntity, ParallelBranchesCount = parallelBranchesCount, DealPersonInfo = sb.ToString() }; var inputParameter = new Dictionary<string, object> { {"FlowDataParm", flowData}, {"NextDeptType", ""}, { "DealWay", wfInstanceStatesEntity.WfDealWayId.ToString().ToUpper() } }; var cswfTemplateEntity = WfTemplateDataBusiness.GetWfTemplateDataByTemplateID(wfInstanceEntity.TemplateID); var activity = GetActivity(cswfTemplateEntity.TemplateData); var instance = new WorkflowApplication(activity); var instanceStore = new SqlWorkflowInstanceStore(Common.GetConnectString()); instanceStore.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry; instanceStore.HostLockRenewalPeriod = TimeSpan.FromSeconds(30); //解决再次load时lock的问题 instance.InstanceStore = instanceStore; instance.PersistableIdle = (waiea) => PersistableIdleAction.Unload; instance.Load(wfInstanceEntity.InstanceID); instance.ResumeBookmark("GetFlowData", inputParameter); // } } catch (InstanceLockedException lockedException) { LogWritter.WriteSystemExceptionLog(lockedException); } catch (Exception ex) { LogWritter.WriteSystemExceptionLog(ex); throw ex; } }
public void createApp(Activity activity) { //var xh = new XamlHelper(workflow.xaml); //extraextension.updateProfile(xh.Variables.ToArray(), xh.ArgumentNames.ToArray()); TrackingParticipant = new WorkflowTrackingParticipant(); TrackingParticipant.OnVisualTracking += Participant_OnVisualTracking; if (string.IsNullOrEmpty(InstanceId)) { // Remove unknown Parameters, if we don't the workflow will fail foreach (var param in Parameters.ToList()) { var allowed = Workflow.Parameters.Where(x => x.name == param.Key).FirstOrDefault(); if (allowed == null || allowed.direction == workflowparameterdirection.@out) { Parameters.Remove(param.Key); } } // Ensure Type foreach (var wfparam in Workflow.Parameters) { if (Parameters.ContainsKey(wfparam.name) && wfparam.type == "System.Int32") { if (Parameters[wfparam.name] != null) { Parameters[wfparam.name] = int.Parse(Parameters[wfparam.name].ToString()); } } else if (Parameters.ContainsKey(wfparam.name) && wfparam.type == "System.Boolean") { if (Parameters[wfparam.name] != null) { Parameters[wfparam.name] = bool.Parse(Parameters[wfparam.name].ToString()); } } } wfApp = new System.Activities.WorkflowApplication(activity, Parameters); wfApp.Extensions.Add(TrackingParticipant); foreach (var t in Plugins.WorkflowExtensionsTypes) { try { var ext = (ICustomWorkflowExtension)Activator.CreateInstance(t); ext.Initialize(RobotInstance.instance, Workflow, this); wfApp.Extensions.Add(ext); } catch (Exception ex) { Log.Error("error init " + t.Name + ": " + ex.ToString()); } } if (Workflow.Serializable) { //if (Config.local.localstate) //{ // if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\state")) System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\state"); // wfApp.InstanceStore = new Store.XMLFileInstanceStore(System.IO.Directory.GetCurrentDirectory() + "\\state"); //} //else //{ // wfApp.InstanceStore = new Store.OpenFlowInstanceStore(); //} wfApp.InstanceStore = new Store.OpenFlowInstanceStore(); } addwfApphandlers(wfApp); } else { wfApp = new System.Activities.WorkflowApplication(activity); wfApp.Extensions.Add(TrackingParticipant); foreach (var t in Plugins.WorkflowExtensionsTypes) { try { var ext = (ICustomWorkflowExtension)Activator.CreateInstance(t); ext.Initialize(RobotInstance.instance, Workflow, this); wfApp.Extensions.Add(ext); } catch (Exception ex) { Log.Error("error init " + t.Name + ": " + ex.ToString()); } } addwfApphandlers(wfApp); if (Workflow.Serializable || !Workflow.Serializable) { //if (Config.local.localstate) //{ // if (!System.IO.Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\state")) System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\state"); // wfApp.InstanceStore = new Store.XMLFileInstanceStore(System.IO.Directory.GetCurrentDirectory() + "\\state"); //} //else //{ // wfApp.InstanceStore = new Store.OpenFlowInstanceStore(); //} wfApp.InstanceStore = new Store.OpenFlowInstanceStore(); } wfApp.Load(new Guid(InstanceId)); } state = "loaded"; }
private void btnAssign_Click(object sender, RoutedEventArgs e) { if (lstLeads.SelectedIndex >= 0) { Lead l = (Lead)lstLeads.Items[lstLeads.SelectedIndex]; Guid id = l.WorkflowID; WorkflowApplication i = new WorkflowApplication(new EnterLead()); SetupInstance(i); i.Load(id); try { i.ResumeBookmark("GetAssignment", txtAgent.Text); } catch (Exception e2) { AddEvent(e2.Message); } } //if (lstLeads.SelectedIndex >= 0) //{ // Lead l = (Lead)lstLeads.Items[lstLeads.SelectedIndex]; // Guid id = l.WorkflowID; // LeadDataDataContext dc = new LeadDataDataContext(_connectionString); // dc.Refresh(RefreshMode.OverwriteCurrentValues, dc.Leads); // l = dc.Leads.SingleOrDefault<Lead>(x => x.WorkflowID == id); // if (l != null) // { // l.AssignedTo = txtAgent.Text; // l.Status = "Assigned"; // dc.SubmitChanges(); // // Clear the input // txtAgent.Text = ""; // } // // Update the grid // lstLeads.Items[lstLeads.SelectedIndex] = l; // lstLeads.Items.Refresh(); // WorkflowApplication i = new WorkflowApplication(new EnterLead()); // //i.InstanceStore = _instanceStore; // // i.PersistableIdle = (waiea) => PersistableIdleAction.Unload; // SetupInstance(i); // i.Load(id); // try // { // i.ResumeBookmark("GetAssignment", l); // } // catch (Exception e2) // { // AddEvent(e2.Message); // } //} }