public string ResumeWizard(IWizardModel model) { _workflowApplication.Load(model.Id); string bookmarkName = "final"; System.Collections.ObjectModel.ReadOnlyCollection <System.Activities.Hosting.BookmarkInfo> bookmarks = _workflowApplication.GetBookmarks(); if (bookmarks != null && bookmarks.Count > 0) { bookmarkName = bookmarks[0].BookmarkName; } return(bookmarkName); }
private void SetBookmarkState(ActivityState state) { foreach (var bookmark in _application.GetBookmarks()) { _application.ResumeBookmark(bookmark.BookmarkName, state); } }
static void Interact(WorkflowApplication application) { IList <BookmarkInfo> bookmarks = application.GetBookmarks(); while (true) { Console.Write("Bookmarks:"); foreach (BookmarkInfo info in bookmarks) { Console.Write(" '" + info.BookmarkName + "'"); } Console.WriteLine(); Console.WriteLine("Enter the name of the bookmark to resume"); string bookmarkName = Console.ReadLine(); if (bookmarkName != null && !bookmarkName.Equals(string.Empty)) { Console.WriteLine("Enter the payload for the bookmark '{0}'", bookmarkName); string bookmarkPayload = Console.ReadLine(); BookmarkResumptionResult result = application.ResumeBookmark(bookmarkName, bookmarkPayload); if (result == BookmarkResumptionResult.Success) { return; } else { Console.WriteLine("BookmarkResumptionResult: " + result); } } } }
static void Main(string[] args) { var connStr = @"Data Source=.\sqlexpress;Initial Catalog=WorkflowInstanceStore;Integrated Security=True;Pooling=False"; SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore(connStr); Workflow1 w = new Workflow1(); //instanceStore. //IDictionary<string, object> xx=WorkflowInvoker.Invoke(new Workflow1()); //ICollection<string> keys=xx.Keys; WorkflowApplication a = new WorkflowApplication(w); a.InstanceStore = instanceStore; a.GetBookmarks(); //a.ResumeBookmark("Final State", new object()); a.Run(); //a.ResumeBookmark( //a.Persist(); //a.Unload(); //Guid id = a.Id; //WorkflowApplication b = new WorkflowApplication(w); //b.InstanceStore = instanceStore; //b.Load(id); //WorkflowApplication a=new WorkflowApplication( }
private void GetBookMarksOnAbortedWorkflow(bool isDefaultTimeout) { const string traceToWaitMsg = "Continue WaitForTrace1"; Sequence sequence = new Sequence() { Activities = { new WaitForTrace() { DisplayName = "WaitForTrace1", TraceToWait = new InArgument <string>(traceToWaitMsg) }, new ReadLine <string>(bookMarkName_InvalidOperationsOnAbortedWorkflow) { } } }; WorkflowApplication instance = new WorkflowApplication(sequence) { Aborted = OnWorkflowInstanceAborted }; instance.Run(); TestTraceManager.Instance.WaitForTrace(instance.Id, new SynchronizeTrace(WaitForTrace.EnterExecute), 1); instance.Abort(); //Continue WaitForTrace. The instance should get aborted after WaitForTrace1 activity is done TestTraceManager.Instance.AddTrace(instance.Id, new SynchronizeTrace(traceToWaitMsg)); SynchronizeTrace.Trace(instance.Id, traceToWaitMsg); TestTraceManager.Instance.WaitForTrace(instance.Id, new SynchronizeTrace(WorkflowInstanceAbortTests.AbortedHandlerCalled), 1); string message = String.Format(ExceptionStrings.WorkflowApplicationAborted, instance.Id); ExceptionHelpers.CheckForException(typeof(WorkflowApplicationAbortedException), message, delegate { if (isDefaultTimeout) { instance.GetBookmarks(); } else { instance.GetBookmarks(TimeSpan.FromMilliseconds(1)); } }); }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); WorkflowApplication myApplication = new WorkflowApplication(new Sequence1()); myApplication.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); }; myApplication.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { Console.WriteLine(e.UnhandledException.ToString()); syncEvent.Set(); return(UnhandledExceptionAction.Terminate); }; myApplication.Aborted = delegate(WorkflowApplicationAbortedEventArgs e) { Console.WriteLine(e.Reason); syncEvent.Set(); }; myApplication.Run(); while (true) { if (myApplication.GetBookmarks().Count > 0) { string bookmarkName = myApplication.GetBookmarks()[0].BookmarkName; string input = Console.ReadLine().Trim(); myApplication.ResumeBookmark(bookmarkName, input); // Exit out of this loop only when the user has entered a non-empty string. if (!String.IsNullOrEmpty(input)) { break; } } } syncEvent.WaitOne(); System.Console.WriteLine("The program has ended. Please press [ENTER] to exit..."); System.Console.ReadLine(); }
// Returns true if the WorkflowApplication has any pending bookmark static bool HasPendingBookmarks(WorkflowApplication application) { try { return(application.GetBookmarks().Count > 0); } catch (WorkflowApplicationCompletedException) { return(false); } }
public string ResumeWizard(Guid id) { wfApp.PersistableIdle = (e) => { Console.WriteLine("Persistable Idle"); return(PersistableIdleAction.Persist); }; wfApp.Idle = (e) => { Console.WriteLine("Idle"); syncEvent.Set(); }; wfApp.Completed = (e) => { Console.WriteLine("Completed workflow!"); _isCompleted = true; syncEvent.Set(); }; wfApp.Aborted = (e) => { Console.WriteLine("Aborted"); Console.WriteLine(e.Reason); syncEvent.Set(); }; wfApp.OnUnhandledException = (e) => { Console.WriteLine("Unhandled Exception"); Console.WriteLine(e.UnhandledException.ToString()); return(UnhandledExceptionAction.Terminate); }; wfApp.Load(id); string bookmarkName = "final"; System.Collections.ObjectModel.ReadOnlyCollection <System.Activities.Hosting.BookmarkInfo> bookmarks = wfApp.GetBookmarks(); if (bookmarks != null && bookmarks.Count > 0) { bookmarkName = bookmarks[0].BookmarkName; } return(bookmarkName); }
// returns true if a vendor can submit a proposal to an instance by // checking if there is a pending bookmark for that vendor public bool CanSubmitProposalToInstance(Guid instanceId, int vendorId) { WorkflowApplication instance = this.LoadInstance(instanceId); // if there are no bookmarks, the process has finalized if (instance.GetBookmarks().Count == 0) { return(false); } else // if there are bookmarks, check if one of them correspond with the "logged" vendor { foreach (BookmarkInfo bookmarkInfo in instance.GetBookmarks()) { if (bookmarkInfo.BookmarkName.Equals("waitingFor_" + vendorId)) { return(true); } } return(false); } }
private static Boolean IsBookmarkValid(WorkflowApplication wfApp, String bookmarkName) { Boolean result = false; var bookmarks = wfApp.GetBookmarks(); if (bookmarks != null) { result = (from b in bookmarks where b.BookmarkName == bookmarkName select b).Any(); } return(result); }
public string ExecuteWF(User user, bool reject = false) { string retMsg = "SuccessWF"; if (user == null || user.WorkflowInstId == Guid.Empty) { Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("model", user); instance = new WorkflowApplication(new AdminRights(), dic); this.InitWorkflowApplication(); instance.Run(); } else { AdminRights rights = new AdminRights(); instance = new WorkflowApplication(rights); this.InitWorkflowApplication(); instance.Load(user.WorkflowInstId); string approver = "SuperAdmin"; if (reject) { //更新状态 WFinstanceDAL wfDal = new WFinstanceDAL(); wfDal.Add(user.WorkflowInstId.ToString(), approver, "驳回"); WFCurrentNodeInfoDAL infoDal = new WFCurrentNodeInfoDAL(); infoDal.UpdateExitTime(user.WorkflowInstId.ToString(), DateTime.Now); instance.Cancel(); retMsg = "驳回成功"; } if (instance.GetBookmarks().Count > 0) { Dictionary <string, object> dic = new Dictionary <string, object>(); dic.Add("model", user); dic.Add("curApproveUser", approver); instance.ResumeBookmark("BookmarkTest", dic); } } user.WorkflowInstId = instance.Id; //等待工作线程结束 idleEvent.WaitOne(); instance.Unload(); return(retMsg); }
static void Main(string[] args) { bool running = true; // create the workflow application and start its execution AutoResetEvent syncEvent = new AutoResetEvent(false); WorkflowApplication application = new WorkflowApplication(new GuessingGameWF()); application.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { running = false; syncEvent.Set(); }; application.Idle = delegate(WorkflowApplicationIdleEventArgs e) { syncEvent.Set(); }; application.Run(); // main loop (manages bookmarks) while (running) { if (!syncEvent.WaitOne(10, false)) { if (running) { // if there are pending bookmarks... if (HasPendingBookmarks(application)) { // get the name of the bookmark string bookmarkName = application.GetBookmarks()[0].BookmarkName; // resume the bookmark (passing the data read from the console) application.ResumeBookmark(bookmarkName, Console.ReadLine()); syncEvent.WaitOne(); } } } } // wait for user input Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
public Guid AssignMetadata(Guid companyID, Guid contactID, Guid?tryWorkflowID = null, Guid referenceID = default(Guid), string referenceClass = null, string referenceTable = null) { using (new TransactionScope(TransactionScopeOption.Suppress)) { if (tryWorkflowID.HasValue && tryWorkflowID.Value != default(Guid)) { _wfApp.Load(tryWorkflowID.Value); } //else // _wfApp.LoadRunnableInstance(); // if any in SQL store _wfApp.Run(); var b = _wfApp.GetBookmarks(); var r = _wfApp.ResumeBookmark("SubmitMetadata", new Dictionary <string, object>() { { "CompanyID", Guid.NewGuid() }, { "ContactID", Guid.NewGuid() } }); //WorkflowInvoker.Invoke( } return(_wfApp.Id); //Real Workflow ID }
public void ResumeBookmark(int workflowToDoListID, int userID, List <string> exchangeParamLists) { Dictionary <string, object> exchangeParams = new Dictionary <string, object>(); foreach (string item in exchangeParamLists) { string[] x = item.Split('^'); exchangeParams.Add(x[0], x[1]); } WorkflowApplication workflowApplication = null; SqlWorkflowInstanceStore instanceStore = null; InstanceView view; DynEntity workflowToDoEntity = GatewayFactory.Default.Find("WorkflowToDoList", workflowToDoListID); DynEntity workflowInstance = null; if (workflowToDoEntity != null) { workflowInstance = GatewayFactory.Default.Find("WorkflowInstance", Convert.ToInt32(workflowToDoEntity["WorkflowInstanceID"])); string bookmarkName = workflowToDoEntity["BookmarkName"].ToString(); if (workflowInstance != null) { string definition = ExecuteScalar("select RuntimeDefinition from Workflow where WorkflowID = " + workflowToDoEntity["WorkflowID"]); //加载并运行工作流 byte[] bs = Encoding.UTF8.GetBytes(definition); Activity activity = null; using (MemoryStream memoryStream = new MemoryStream(bs)) { activity = ActivityXamlServices.Load(memoryStream); } workflowApplication = new WorkflowApplication(activity); if (instanceStore == null) { string connectionString = GatewayFactory.DefaultConnectionString; instanceStore = new SqlWorkflowInstanceStore(connectionString); view = instanceStore.Execute(instanceStore.CreateInstanceHandle(), new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30)); instanceStore.DefaultInstanceOwner = view.InstanceOwner; } workflowApplication.InstanceStore = instanceStore; workflowApplication.PersistableIdle = workflowPersistableIdle; workflowApplication.Idle = workflowIdle; workflowApplication.Unloaded = unload; workflowApplication.Aborted = workflowAborted; workflowApplication.Completed = workflowCompleted; workflowApplication.OnUnhandledException = workflowUnhandledException; Guid guid = new Guid(workflowInstance["InstanceGUID"].ToString()); try { workflowApplication.Load(guid); } catch (Exception ex) { throw ex; } if (workflowApplication != null) { if (workflowApplication.GetBookmarks().Count(p => p.BookmarkName == bookmarkName) == 1) { DynEntity workflowActivityInstance = GatewayFactory.Default.Find("WorkflowActivityInstance", Convert.ToInt32(workflowToDoEntity["WorkflowActivityInstanceID"])); if (workflowActivityInstance != null) { foreach (string item in exchangeParamLists) { string[] arg = item.Split('^'); switch (arg[0]) { case "Handler": workflowActivityInstance["Handler"] = arg[1]; break; case "ObjType": workflowActivityInstance["ObjType"] = arg[1]; break; case "ObjID": workflowActivityInstance["ObjID"] = arg[1]; break; case "DetailID": workflowActivityInstance["DetailID"] = arg[1]; break; case "Opinion": workflowActivityInstance["Opinion"] = arg[1]; break; default: break; } } exchangeParams["Actor"] = userID; workflowActivityInstance["State"] = "已执行"; workflowActivityInstance["EndTime"] = DateTime.Now; using (TransactionScope trans = new TransactionScope()) { GatewayFactory.Default.Save(workflowActivityInstance); GatewayFactory.Default.Delete("WorkflowToDoList", workflowToDoListID); //更新状态字段 if (exchangeParams.ContainsKey("ObjType") && exchangeParams.ContainsKey("ObjID") && exchangeParams.ContainsKey("StateField") && exchangeParams.ContainsKey("StateValue")) { string sqlString = "UPDATE [" + exchangeParams["ObjType"] + "] SET [" + exchangeParams["StateField"] + "] = '" + exchangeParams["StateValue"] + "' WHERE " + exchangeParams["ObjType"] + "ID = " + exchangeParams["ObjID"]; ExcuteNoneReturnQuery(sqlString); } //执行附加SQL if (exchangeParams.ContainsKey("AdditionalSql")) { ExcuteNoneReturnQuery(exchangeParams["AdditionalSql"].ToString()); } workflowApplication.ResumeBookmark(bookmarkName, exchangeParams); trans.Complete(); } } else { throw new ApplicationException(string.Format("在工作流活动:{0} 不存在无法执行,请检查", workflowActivityInstance["WorkflowActivityInstanceName"], bookmarkName)); } } else { throw new ApplicationException(string.Format("在工作流实例{0}中找不到书签名为{1}的活动", workflowToDoEntity["WorkflowInstanceID"], bookmarkName)); } } else { throw new ApplicationException("工作流创建实例失败!"); } } } else { throw new ApplicationException("当前待做任务在数据库中不存在,请检查!"); } }
// returns true if the instance is waiting for proposals (has pending vendor bookmarks) public bool IsInstanceWaitingForProposals(Guid instanceId) { WorkflowApplication instance = this.LoadInstance(instanceId); return(instance.GetBookmarks().Count > 0); }
public TResponse StartWorkflow <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.Run; 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(); wfApp.Load(wfId, 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); }
static void Main(string[] args) { try { AutoResetEvent syncEvent = new AutoResetEvent(false); WorkflowApplication wfApp = new WorkflowApplication(new ProblemReporting()); wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); }; wfApp.Idle = delegate(WorkflowApplicationIdleEventArgs e) { Console.WriteLine("Workflow is idle"); }; wfApp.OnUnhandledException = delegate( WorkflowApplicationUnhandledExceptionEventArgs e) { Console.WriteLine(e.UnhandledException.Message.ToString()); return(UnhandledExceptionAction.Terminate); }; HostEventNotifier extension = new HostEventNotifier(); extension.Notification += delegate( Object sender, HostNotifyEventArgs e) { Console.WriteLine(e.Message); var bookmarks = wfApp.GetBookmarks(); if (bookmarks != null && bookmarks.Count > 0) { Console.WriteLine("Select one of these available actions:"); foreach (BookmarkInfo bookmark in bookmarks) { Console.WriteLine("->{0}", bookmark.BookmarkName); } } Boolean isWaitingForChoice = true; while (isWaitingForChoice) { String newAction = Console.ReadLine(); if (IsBookmarkValid(wfApp, newAction)) { isWaitingForChoice = false; wfApp.ResumeBookmark(newAction, null); } else { Console.WriteLine("Incorrect choice!"); } } }; wfApp.Extensions.Add(extension); wfApp.Run(); syncEvent.WaitOne(); } catch (Exception exception) { Console.WriteLine("Error: {0}", exception.Message); } }
//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 TResponse execute <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(); } }; Action correlate = delegate() { if (instanceStore is IStoreCorrelation) { (instanceStore as IStoreCorrelation).Correlate(); this.WorkflowId = (instanceStore as IStoreCorrelation).Correlation.WorkflowId; } }; WorkflowInstanceContext instanceContext = new WorkflowInstanceContext() { Request = request, Response = default(TResponse) }; WorkflowApplication wfApp = null; //Guid wfId = Guid.Empty; while (invokeMode != WorkflowInvokeMode.None) { if (invokeMode == WorkflowInvokeMode.Run) { wfApp = createWorkflowApplication(instanceContext); this.WorkflowId = wfApp.Id; (wfApp.InstanceStore as IStoreCorrelation).Correlation.WorkflowId = wfApp.Id; resetEvents(); wfApp.Run(timeOut); waitOne(); } else if (invokeMode == WorkflowInvokeMode.ResumeBookmark) { wfApp = createWorkflowApplication(instanceContext); resetEvents(); correlate(); if (this.WorkflowId == Guid.Empty) { throw new Exception($"WorkflowId missing on workflow with"); } wfApp.Load(this.WorkflowId, timeOut); var ext = wfApp.Extensions; 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}"); } } if (exception != null) { throw exception; } } ; TResponse response = default(TResponse); try { response = (TResponse)instanceContext.Response; } catch (Exception exc) //TODO: System.InvalidCastException { throw exc; } return(response); }
static void Main(string[] args) { Activity wf = new SampleWorkflow(); var app = new WorkflowApplication(wf); // http://blogs.msmvps.com/theproblemsolver/2011/01/07/doing-synchronous-workflow-execution-using-the-workflowapplication/ // app.SynchronizationContext = new SynchronousSynchronizationContext(); app.Run(); while (true) { System.Threading.Thread.Sleep(100); try { var bms = app.GetBookmarks(); Console.WriteLine(); Console.WriteLine(); var n = 0; foreach (var bm in bms) { n++; Console.WriteLine("[{1} {0}] ", bm.BookmarkName, n); } Console.Write("Enter 1..{0} or q-quit: ", bms.Count); var l = Console.ReadLine(); switch (l.Trim().ToLowerInvariant()) { case "q": app.Abort(); return; case "1": app.ResumeBookmark(bms[0].BookmarkName, null); break; case "2": app.ResumeBookmark(bms[1].BookmarkName, null); break; case "3": app.ResumeBookmark(bms[2].BookmarkName, null); break; case "4": app.ResumeBookmark(bms[3].BookmarkName, null); break; case "5": app.ResumeBookmark(bms[4].BookmarkName, null); break; } } catch (Exception ex) { app.Abort(); Console.Write("{0}. Press return to quit ... ", ex.Message); Console.ReadLine(); return; } } }
static void testOffline() { SESampleProcess2 p2 = new SESampleProcess2(); //SESampleWorkFlow p2 = new SESampleWorkFlow(); WorkflowApplication app = new WorkflowApplication(p2); AutoResetEvent rre = new AutoResetEvent(false); app.Idle = (e) => { rre.Set(); }; //TrackingProfile trackingProfile = new TrackingProfile(); ////trackingProfile.Queries.Add(new WorkflowInstanceQuery ////{ //// States = { "*"} ////}); ////trackingProfile.Queries.Add(new ActivityStateQuery ////{ //// States = {"*" } ////}); //trackingProfile.Queries.Add(new CustomTrackingQuery //{ // ActivityName="*", // Name = "*" //}); //SETrackingParticipant p = new SETrackingParticipant(); //p.TrackingProfile = trackingProfile; //app.Extensions.Add(p); app.Completed = (e) => { Console.WriteLine("shit"); }; ReadOnlyCollection <BookmarkInfo> bookmarks = null; //bookmarks = app.GetBookmarks(); //rre.WaitOne(); WorkflowInstanceExtensionManager extensions = app.Extensions; BookmarkResumptionResult result; //result= app.ResumeBookmark("ProcessStart", new ChooseTransitionResult()); //rre.WaitOne(); //bookmarks = app.GetBookmarks(); app.Run(); rre.WaitOne(); bookmarks = app.GetBookmarks(); result = app.ResumeBookmark("RequireMoreInformation", new ChooseTransitionResult()); rre.WaitOne(); bookmarks = app.GetBookmarks(); //app.Run(); result = app.ResumeBookmark("ProvideMoreInformation", new ChooseTransitionResult()); rre.WaitOne(); bookmarks = app.GetBookmarks(); result = app.ResumeBookmark("AssignToInvestigation", new ChooseTransitionResult()); rre.WaitOne(); bookmarks = app.GetBookmarks(); result = app.ResumeBookmark("AssignToTriage", new ChooseTransitionResult()); rre.WaitOne(); bookmarks = app.GetBookmarks(); result = app.ResumeBookmark("FinishProcess", new ChooseTransitionResult()); rre.WaitOne(); bookmarks = app.GetBookmarks(); // ChooseTransitionResult rslt=new ChooseTransitionResult(); //// rslt.ChooseResult="Not Need"; // result=app.ResumeBookmark("AssignToTriage", rslt); // rre.WaitOne(); // result = app.ResumeBookmark("FinishProcess", rslt); // rre.WaitOne(); bookmarks = app.GetBookmarks(); Console.WriteLine(); }
/// <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(); }