static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); // create the workflow app and add handlers for the Idle and Completed actions WorkflowApplication app = new WorkflowApplication(new Sequence1()); app.Idle = delegate(WorkflowApplicationIdleEventArgs e) { syncEvent.Set(); }; app.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); }; // start the application app.Run(); syncEvent.WaitOne(); // read some text from the console and resume the readText bookmark (created in the first WaitForInput activity) string text = Console.ReadLine(); app.ResumeBookmark("readText", text); syncEvent.WaitOne(); // read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity) int number = ReadNumberFromConsole(); app.ResumeBookmark("readNumber", number); syncEvent.WaitOne(); Console.WriteLine(""); Console.WriteLine("Press [ENTER] to exit..."); Console.ReadLine(); }
// single interaction with the user. The user enters a string in the console and that // string is used to resume the ReadLine activity bookmark static void Interact(WorkflowApplication application, AutoResetEvent resetEvent) { Console.WriteLine("Workflow is ready for input"); Console.WriteLine("Special commands: 'unload', 'exit'"); bool done = false; while (!done) { Console.Write("> "); string s = Console.ReadLine(); if (s.Equals("unload")) { try { // attempt to unload will fail if the workflow is idle within a NoPersistZone application.Unload(TimeSpan.FromSeconds(5)); done = true; } catch (TimeoutException e) { Console.WriteLine(e.Message); } } else if (s.Equals("exit")) { application.ResumeBookmark("inputBookmark", s); done = true; } else { application.ResumeBookmark("inputBookmark", s); } } resetEvent.WaitOne(); }
private static void Main(string[] args) { const int workflowCompleted = 0; const int workflowIdle = 1; var syncEvents = new[] { new AutoResetEvent(false), new AutoResetEvent(false), }; var wfApp = new WorkflowApplication(new TestReadLine()); string bookmarkName = string.Empty; bool workflowComplete = false; // Signal the main thread we are done wfApp.Completed = (e) => syncEvents[workflowCompleted].Set(); // When the host detects an idle wfApp.Idle = (e) => { // Search the bookmarks foreach ( var bi in e.Bookmarks.Where( bi => bi.BookmarkName == "FirstName" || bi.BookmarkName == "LastName")) { Console.WriteLine("Found bookmark {0}", bi.BookmarkName); // For FirstName or LastName bookmarks prompt with a readline bookmarkName = bi.BookmarkName; syncEvents[workflowIdle].Set(); } }; wfApp.Run(); while (!workflowComplete) { // Wait for events switch (WaitHandle.WaitAny(syncEvents, TimeSpan.FromSeconds(5))) { case WaitHandle.WaitTimeout: Console.WriteLine("Sorry you took too long"); wfApp.Terminate("Timeout"); break; case workflowCompleted: workflowComplete = true; break; case workflowIdle: Console.WriteLine("Reading response for bookmark {0}", bookmarkName); // Resume with the response from the user wfApp.ResumeBookmark(bookmarkName, Console.ReadLine()); break; } } Console.WriteLine("Sample Completed - press any key to exit"); Console.ReadKey(true); }
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); } } } }
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 Main(string[] args) { _event = new AutoResetEvent(false); bool more = true; int result = 0; var activity = new AccumulatorActivity(); var accumulator = new WorkflowApplication(activity); accumulator.Completed = new Action<WorkflowApplicationCompletedEventArgs>((e) => { result = (int)e.Outputs["Sum"]; more = false; _event.Set(); }); accumulator.Extensions.Add(new Notification(NotifySum)); accumulator.Run(); while (more) { Console.Write("Enter number: "); int number = int.Parse(Console.ReadLine()); accumulator.ResumeBookmark("GetNumber", number); _event.WaitOne(); } Console.WriteLine("Result is " + result); }
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(); }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); AutoResetEvent idleEvent = new AutoResetEvent(false); Dictionary<string, object> input = new Dictionary<string, object> { { "MaxNumber", 100 } }; WorkflowApplication app = new WorkflowApplication(new SequentialNumberGuessWorkflow(), input); app.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { int Turns = Convert.ToInt32(e.Outputs["Turns"]); Console.WriteLine("Congratulations, you guessed the number in {0} turns", Turns); syncEvent.Set(); }; app.Aborted = delegate(WorkflowApplicationAbortedEventArgs e) { Console.WriteLine(e.Reason); syncEvent.Set(); }; app.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { Console.WriteLine(e.UnhandledException.ToString()); syncEvent.Set(); return UnhandledExceptionAction.Abort; }; app.Idle = delegate(WorkflowApplicationIdleEventArgs e) { idleEvent.Set(); }; app.Run(); // Loop until the workflow completes. WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent }; while (WaitHandle.WaitAny(handles) != 0) { // Gather the user input and resume the bookmark. bool validEntry = false; while (!validEntry) { int Guess; if (!Int32.TryParse(Console.ReadLine(), out Guess)) { Console.WriteLine("Please enter an integer."); } else { validEntry = true; app.ResumeBookmark("EnterGuess", Guess); } } } }
static void Main(string[] args) { ManualResetEvent workflowCompleted = new ManualResetEvent(false); ManualResetEvent workflowIdled = new ManualResetEvent(false); Activity activity; using (Stream stream = File.OpenRead("Program.xaml")) { activity = ActivityXamlServices.Load(stream); stream.Close(); } //create the WorkflowApplication using the Activity loaded from Program.xaml WorkflowApplication application = new WorkflowApplication(activity); //set up the Completed and Idle callbacks application.Completed = workflowCompletedEventArgs => workflowCompleted.Set(); application.Idle = (e) => { workflowIdled.Set(); }; //run the program application.Run(); while (true) { string input = Console.ReadLine(); workflowIdled.Reset(); //provide the Console input to the Workflow application.ResumeBookmark("PromptBookmark", input); //wait for either the Idle or the Completion signal int signalled = WaitHandle.WaitAny(new WaitHandle[] { workflowCompleted, workflowIdled }); //if completion was signalled, then we are done. if (signalled == 0) { break; } } Console.WriteLine(); Console.WriteLine("Press [ENTER] to exit."); Console.ReadLine(); }
//第一步以后,后续所有流程步骤的入口 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(); }
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(); }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); string bookmarkName = "GreetingBookmark"; WorkflowApplication wfApp = new WorkflowApplication(new Workflow1() { BookmarkNameInArg = bookmarkName }); wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); }; wfApp.Run(); wfApp.ResumeBookmark(bookmarkName, Console.ReadLine()); syncEvent.WaitOne(); }
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(); }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); string bookmarkName = "HostGreeting"; WorkflowApplication wfApp = new WorkflowApplication(new Workflow1() { BookmarkNameInArg = bookmarkName }); /* * To clean up the persistence database to have a fresh database, run the scripts in: %WINDIR%\Microsoft.NET\Framework\v4.xxx\SQL\EN in the following order. SqlWorkflowInstanceStoreSchema.sql SqlWorkflowInstanceStoreLogic.sql * */ string connectionString = "Server=.\\SQLSERVER14;Initial Catalog=Persistence45;Integrated Security=SSPI"; Console.WriteLine("Workflow ID: " + wfApp.Id); wfApp.InstanceStore = (InstanceStore)new SqlWorkflowInstanceStore(connectionString); wfApp.PersistableIdle = delegate(WorkflowApplicationIdleEventArgs e) { syncEvent.Set(); Console.WriteLine("Persisting.."); return PersistableIdleAction.Persist; }; wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); Console.WriteLine("Completing.."); }; wfApp.Run(); wfApp.ResumeBookmark(bookmarkName, Console.ReadLine()); syncEvent.WaitOne(); syncEvent.WaitOne(); }
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(); }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); AutoResetEvent idleEvent = new AutoResetEvent(false); var inputs = new Dictionary<string, object>() { { "MaxNumber", 100 } }; WorkflowApplication wfApp = new WorkflowApplication(new SequentialNumberGuessWorkflow(), inputs); wfApp.Completed = (e) => { int Turns = Convert.ToInt32(e.Outputs["Turns"]); Console.WriteLine("Congratulations, you guessed the number in {0} turns.", Turns); syncEvent.Set(); }; wfApp.Aborted = (e) => { Console.WriteLine(e.Reason); syncEvent.Set(); }; wfApp.OnUnhandledException = (e) => { Console.WriteLine(e.UnhandledException.ToString()); return UnhandledExceptionAction.Terminate; }; wfApp.Idle = (e) => { idleEvent.Set(); }; var config = @"{ ""WorkflowInstanceQuery"" : [{ ""States"": [ ""*"" ] , ""QueryAnnotations"": {} }] , ""ActivityStateQuery"" : [{ ""ActivityName"": ""*"" , ""Arguments"": [] , ""Variables"": [] , ""States"": [""*""] , ""QueryAnnotations"": {} }] , ""CustomTrackingQuery"": [{ ""Name"": ""*"", ""ActivityName"": ""*"", ""QueryAnnotations"": {} }] , ""FaultPropagationQuery"": [{ ""FaultHandlerActivityName"": ""*"", ""FaultSourceActivityName"": ""*"", ""QueryAnnotations"": {} }], ""BookmarkResumptionQuery"": [{ ""Name"": ""*"", ""QueryAnnotations"": {} }], ""ActivityScheduledQuery"": [{ ""ActivityName"": ""*"", ""ChildActivityName"": ""*"", ""QueryAnnotations"": {} }], ""CancelRequestedQuery"": [{ ""ActivityName"": ""*"", ""ChildActivityName"": ""*"", ""QueryAnnotations"": {} }] }"; var trackingProfile = WorkFlowHelper .GetTrackingProfileFromJson ( config , true ); var etwTrackingParticipant = new EtwTrackingParticipant(); etwTrackingParticipant.TrackingProfile = trackingProfile; var commonTrackingParticipant = new CommonTrackingParticipant() { TrackingProfile = trackingProfile , OnTrackingRecordReceived = (x, y) => { Console.WriteLine("{1}{0}{2}", ",", x, y); return true; } }; wfApp .Extensions .Add ( etwTrackingParticipant ); wfApp .Extensions .Add ( commonTrackingParticipant ); wfApp.Run(); // Loop until the workflow completes. WaitHandle[] handles = new WaitHandle[] { syncEvent, idleEvent }; while (WaitHandle.WaitAny(handles) != 0) { // Gather the user input and resume the bookmark. bool validEntry = false; while (!validEntry) { int Guess; if (!int.TryParse(Console.ReadLine(), out Guess)) { Console.WriteLine("Please enter an integer."); } else { validEntry = true; wfApp.ResumeBookmark("EnterGuess", Guess); } } } }
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); } } }
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> /// 重新启动工作流,是审核过程中保存审核结果的必要流程 /// </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); } }
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); }
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(); } }
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(); }
//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 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; } }
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); }
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; } }
/// <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 } } } }
/// <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(); }
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); // } //} }
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(); }