예제 #1
0
        public static void ResumeWorkflowTimer(IApplicationHost host, IDbContext dbContext, IMessaging messaging, Int64 processId)
        {
            AppWorkflow aw     = null;
            var         result = new WorkflowResult
            {
                InboxIds = new List <Int64>()
            };

            try
            {
                var      pi   = ProcessInfo.Load(dbContext, processId, 0);
                var      def  = WorkflowDefinition.Load(pi);
                Activity root = def.LoadFromDefinition();
                aw = Create(dbContext, root, null, def.Identity);
                aw._application.Extensions.Add(dbContext);
                aw._application.Extensions.Add(messaging);
                aw._application.Extensions.Add(host);
                aw._application.Extensions.Add(result);
                WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(pi.WorkflowId, aw._application.InstanceStore);
                aw._application.Load(instance, _wfTimeSpan);
                aw._application.Run(_wfTimeSpan);
            }
            catch (Exception ex)
            {
                if (!CatchWorkflow(aw, ex))
                {
                    throw;
                }
            }
            finally
            {
                ProcessFinally(aw);
            }
        }
        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.");
        }
        private void InstanceId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (InstanceId.SelectedIndex == -1)
            {
                return;
            }

            // Clear the status window.
            WorkflowStatus.Clear();

            // If there is tracking data for this workflow, display it
            // in the status window.
            if (File.Exists(WorkflowInstanceId.ToString()))
            {
                string status = File.ReadAllText(WorkflowInstanceId.ToString());
                UpdateStatus(status);
            }

            // Get the workflow version and display it.
            // If the workflow is just starting then this info will not
            // be available in the persistence store so do not try and retrieve it.
            if (!WorkflowStarting)
            {
                WorkflowApplicationInstance instance =
                    WorkflowApplication.GetInstance(this.WorkflowInstanceId, store);

                WorkflowVersion.Text =
                    WorkflowVersionMap.GetIdentityDescription(instance.DefinitionIdentity);

                // Unload the instance.
                instance.Abandon();
            }
        }
예제 #4
0
        private void Unload(Guid workflowInstanceId) //that's weird!
        {
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            // Unload the instance.
            instance.Abandon();
        }
      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>
        /// <param name="definitionPath"></param>
        /// <param name="mapPath"></param>
        /// <param name="connectionString"></param>
        /// <param name="instanceId"></param>
        public static void Update(String definitionPath, String mapPath, String connectionString, Guid instanceId)
        {
            // Store
            SqlWorkflowInstanceStore instanceStore = new SqlWorkflowInstanceStore
            {
                ConnectionString = connectionString
            };

            // Instance to update
            WorkflowApplicationInstance wfInstance = WorkflowApplication.GetInstance(instanceId, instanceStore);

            // Load update map
            DynamicUpdateMap       updateMap;
            DataContractSerializer s = new DataContractSerializer(typeof(DynamicUpdateMap));

            using (FileStream fs = File.Open(mapPath, FileMode.Open))
            {
                updateMap = s.ReadObject(fs) as DynamicUpdateMap;
            }
            // if (updateMap == null) return; // Throw

            WorkflowApplication wfApp =
                new WorkflowApplication(LoadActivityBuilder(definitionPath).Implementation);

            IList <ActivityBlockingUpdate> act;

            if (wfInstance.CanApplyUpdate(updateMap, out act))
            {
                wfApp.Load(wfInstance, updateMap);
                wfApp.Unload();
            }
        }
예제 #7
0
        private static void UpgradeExistingWorkflow(Guid id, DynamicUpdateMap map)
        {
            SqlWorkflowInstanceStore    store    = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(id, store);
            WorkflowApplication         app      = new WorkflowApplication(GetUpdatedWorkflow());

            app.Load(instance, map);
            app.Unload();
        }
예제 #8
0
        private static void LoadAndRunWorkflow(Guid id)
        {
            SqlWorkflowInstanceStore    store    = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(id, store);
            WorkflowApplication         app      = new WorkflowApplication(GetUpdatedWorkflow());
            ManualResetEvent            wait     = new ManualResetEvent(false);

            app.Completed = args => wait.Set();
            app.Run();
            wait.WaitOne();
        }
예제 #9
0
        public static async Task <WorkflowResult> ResumeWorkflow(IApplicationHost host, IDbContext dbContext, ResumeWorkflowInfo info)
        {
            AppWorkflow aw     = null;
            var         result = new WorkflowResult
            {
                InboxIds = new List <Int64>()
            };

            try
            {
                InboxInfo inbox = await InboxInfo.Load(dbContext, info.Id, info.UserId);

                result.ProcessId = inbox.ProcessId;
                var      def  = WorkflowDefinition.Load(inbox);
                Activity root = def.LoadFromSource(host);
                aw = Create(dbContext, root, null, def.Identity);
                aw._application.Extensions.Add(result);
                aw._application.Extensions.Add(dbContext);
                WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(inbox.WorkflowId, aw._application.InstanceStore);
                aw._application.Load(instance, _wfTimeSpan);
                foreach (var bm in aw._application.GetBookmarks())
                {
                    if (bm.BookmarkName == inbox.Bookmark)
                    {
                        var rr = new RequestResult
                        {
                            Answer  = info.Answer,
                            Comment = info.Comment,
                            Params  = info.Params,
                            UserId  = info.UserId,
                            InboxId = info.Id
                        };
                        aw._application.ResumeBookmark(bm.BookmarkName, rr);
                        return(result);                        // already resumed
                    }
                }
                // if a bookmark is not found
                aw._application.Unload();
            }
            catch (Exception ex)
            {
                if (!CatchWorkflow(aw, ex))
                {
                    throw;
                }
            }
            finally
            {
                ProcessFinally(aw);
            }
            return(result);
        }
예제 #10
0
        public void ResumeWorkFlow(BusinessObject.DtoModels.Game game)
        {
            Exception exception = new Exception();

            Guid workflowInstanceID = game.InstanceId;

            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(databaseConnection);

            store.InstanceLockedExceptionAction = InstanceLockedExceptionAction.BasicRetry;
            store.HostLockRenewalPeriod         = TimeSpan.FromSeconds(2);


            InstanceHandle             instanceHandle = store.CreateInstanceHandle();
            CreateWorkflowOwnerCommand createOwnerCmd = new CreateWorkflowOwnerCommand();
            InstanceView view = store.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSeconds(10));

            store.DefaultInstanceOwner = view.InstanceOwner;

            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceID, store);

            AutoResetEvent syncEvent = new AutoResetEvent(false);

            WorkflowApplication wfApplication = new WorkflowApplication(new FlowchartNumberGuessWorkflow(), instance.DefinitionIdentity);

            wfApplication.PersistableIdle      = (e) => PersistableIdleAction.Unload;
            wfApplication.Unloaded             = (e) => { syncEvent.Set(); };
            wfApplication.OnUnhandledException = (e) =>
            {
                exception = e.UnhandledException;
                syncEvent.Set();
                return(UnhandledExceptionAction.Cancel);
            };

            wfApplication.Load(instance);

            BookmarkResumptionResult result = wfApplication.ResumeBookmark("Decision", game);

            syncEvent.WaitOne();

            if (exception.Message != string.Empty && exception.StackTrace != null)
            {
                throw exception;
            }

            DeleteWorkflowOwnerCommand deleteOwnerCmd = new DeleteWorkflowOwnerCommand();

            store.Execute(instanceHandle, deleteOwnerCmd, TimeSpan.FromSeconds(10));
        }
예제 #11
0
        private static void LoadRunnableInstance(InstanceStore store, WorkflowApplicationInstance appInstance)
        {
            var app = CreateWorkflow(store, WorkflowApps.App1);

            switch (appInstance.DefinitionIdentity.Name)
            {
            case "App1":
                break;

            case "App2":
                app = CreateWorkflow(store, WorkflowApps.App2);
                break;
            }

            app.Load(appInstance);
            app.Run();
        }
        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();
        }
예제 #13
0
        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 void cmdReturnMovie_Click(object sender, RoutedEventArgs e)
        {
            InitiateWorkflowRuntime();
            WorkflowApplicationInstance wfInstance = WorkflowApplication.GetInstance(new Guid(txtInstanceId.Text), _wfApp.InstanceStore);
            int minVer = wfInstance.DefinitionIdentity.Version.Minor;

            _wfApp.Load(wfInstance);
            _wfApp.Run();

            var creditCard = new CreditCard()
            {
                CCNumber    = "1235626427465",
                FirstName   = "Bayer",
                LastName    = "White",
                ExpireMonth = 10,
                ExpireYear  = 14
            };

            _wfApp.ResumeBookmark("ReturnMovie", creditCard);
        }
예제 #15
0
        private void Terminate(Guid workflowInstanceId, Func <WorkflowIdentity, Activity> workflowMap,
                               string terminationMessage, Action <string> writelineListener = null)
        {
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            // Use the persisted WorkflowIdentity to retrieve the correct workflow
            // definition from the dictionary.
            Activity wf = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition
            WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity);

            // Configure the extensions and lifecycle handlers
            ConfigureWorkflowApplication(wfApp, writelineListener);

            // Load the workflow.
            wfApp.Load(instance);

            // Terminate the workflow.
            wfApp.Terminate(terminationMessage);
        }
예제 #16
0
        private static void SendInstance(string customerName, string bookmarkName)
        {
            if (!customers.Exists(c => c.Name == customerName))
            {
                Console.WriteLine(string.Format("No such customer {0}.", customerName));
                return;
            }

            var customer = customers.Find(c => c.Name == customerName);

            if (customer.InstanceId == "")
            {
                Console.WriteLine(string.Format("Customer {0} does not have workflow instance.", customerName));
                return;
            }

            SqlWorkflowInstanceStore store = new SqlWorkflowInstanceStore(connectionString);

            WorkflowApplication.CreateDefaultInstanceOwner(store, null, WorkflowIdentityFilter.Any);

            WorkflowApplicationInstance instance =
                WorkflowApplication.GetInstance(new Guid(customer.InstanceId), store);

            Activity wf = GetWorkflow(customer.WorkflowId);

            if (wf == null)
            {
                Console.WriteLine(string.Format("Unknown workflow {0}", customer.WorkflowId));
                return;
            }
            WorkflowApplication wfApp =
                new WorkflowApplication(wf, instance.DefinitionIdentity);

            ConfigureWFApp(wfApp, customer);
            wfApp.Load(instance);
            instanceUnloaded.Reset();
            wfApp.ResumeBookmark(bookmarkName, null);
        }
예제 #17
0
        private void ResumeBookmark(Guid workflowInstanceId,
                                    Func <WorkflowIdentity, Activity> workflowMap, string bookmarkName, object bookmarkResumeContext)
        {
            // >>>> RESUME A WORKFLOW <<<<
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            Activity workflow = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition (a name & version)
            WorkflowApplication wfApp = new WorkflowApplication(workflow, 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); //takes a Guid InstanceId or WorkflowApplicationInstance instance from store

            // Resume the workflow.
            wfApp.ResumeBookmark(bookmarkName, bookmarkResumeContext);
        }
예제 #18
0
        // >>>> RESUME A WORKFLOW <<<<
        public WorkflowResult ResumeBookmark(Guid workflowInstanceId, Func <WorkflowIdentity, Activity> workflowMap,
                                             string bookmarkName, object bookmarkResumeContext, Action <string> writelineListener = null)
        {
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(workflowInstanceId, _store);

            Activity workflow = workflowMap(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition (a name & version)
            WorkflowApplication wfApp = new WorkflowApplication(workflow, 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, writelineListener);

            // Load the workflow.
            wfApp.Load(instance); //takes a Guid InstanceId or WorkflowApplicationInstance instance from store

            // Resume the workflow.
            wfApp.ResumeBookmark(bookmarkName, bookmarkResumeContext);

            return(WaitAndReturnData());
        }
예제 #19
0
        public static void RunScenario()
        {
            //***********************************************************
            // STEP 1: create a WorkflowApplication with a definition,
            //         and an identity, start an instance, and persist it and
            //         unload it when it gets idle
            //***********************************************************

            // Create a workflow application using identity
            // notice that the delta between WF4 is the following:
            //    - create an instance of WorkflowIdentity
            //    - pass it to WorkflowApplication in its constructor
            WorkflowIdentity identityV1 =
                new WorkflowIdentity("Dev11-Sample",
                                     new Version(1, 0, 0, 0), null);
            WorkflowApplication application = new WorkflowApplication(new Activity1(), identityV1);

            // create the instance store and assign it to the workflow application
            application.InstanceStore = Utils.SetupInstanceStore();

            // start an instance, unload it, and persist it into the instance store
            Guid instanceId = Utils.StartAndUnloadInstance(application);

            // read input from the console
            string input = Console.ReadLine();


            //***********************************************************
            // STEP 2: given an instance id, look up the definition in the
            //         instance store, configure a workflow application
            //         load the instance, and continue with its execution
            //***********************************************************
            // load the instance with the correct definition
            WorkflowApplicationInstance instance       = null;
            WorkflowApplication         newApplication = null;
            AutoResetEvent syncEvent = new AutoResetEvent(false);

            try
            {
                // get a proxy to the running instance
                instance = WorkflowApplication.GetInstance(instanceId, Utils.SetupInstanceStore());

                // get the definition associated to the identity of the instance
                // for this we are using a dictionary with key=identity; value=activity
                Activity definition = WorkflowDefinitionRepository.GetActivity(instance.DefinitionIdentity);

                // create and configure the workflowApplication
                newApplication = new WorkflowApplication(definition, instance.DefinitionIdentity);

                // configure the workflow application
                newApplication.Completed = (e) => Utils.ShowMessageFromHost(string.Format("WorkflowApplication has Completed in the {0} state.", e.CompletionState), ConsoleColor.Green);
                newApplication.Unloaded  = (e) => syncEvent.Set();

                // show messages in the console
                Utils.ShowMessageFromHost("Loading the workflow using its identity in the InstanceStore...", ConsoleColor.Cyan);
                Utils.ShowMessageFromHost(string.Format("Loading with identity '{0}'", instance.DefinitionIdentity.ToString()));

                // load the application (passing the instance that we got previously)
                newApplication.Load(instance);

                //this resumes the bookmark setup by readline
                newApplication.ResumeBookmark("ReadLine", input);
                syncEvent.WaitOne();
            }
            catch
            {
                // if there is an error, discard the instance so it does not remain locked
                if (newApplication != null && instance != null)
                {
                    instance.Abandon();
                }
            }
        }
예제 #20
0
        public static async Task <WorkflowResult> ResumeWorkflow(IApplicationHost host, IDbContext dbContext, IMessaging messaging, ResumeWorkflowInfo info)
        {
            AppWorkflow aw       = null;
            var         profiler = host.Profiler;
            var         result   = new WorkflowResult
            {
                InboxIds = new List <Int64>()
            };

            try
            {
                InboxInfo inbox = await InboxInfo.Load(dbContext, info.Id, info.UserId);

                if (inbox == null)
                {
                    throw new WorkflowException("The task is already done by another user");
                }
                using (profiler.CurrentRequest.Start(ProfileAction.Workflow, $"Load '{inbox.Kind}'"))
                {
                    result.ProcessId = inbox.ProcessId;
                    var      def  = WorkflowDefinition.Load(inbox);
                    Activity root = def.LoadFromSource(host, dbContext);
                    aw = Create(dbContext, root, null, def.Identity);
                    aw._application.Extensions.Add(result);
                    aw._application.Extensions.Add(dbContext);
                    aw._application.Extensions.Add(messaging);
                    aw._application.Extensions.Add(host);
                    WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(inbox.WorkflowId, aw._application.InstanceStore);
                    aw._application.Load(instance, _wfTimeSpan);
                }
                foreach (var bm in aw._application.GetBookmarks())
                {
                    if (bm.BookmarkName == inbox.Bookmark)
                    {
                        var rr = new RequestResult
                        {
                            Answer  = info.Answer,
                            Comment = info.Comment,
                            Params  = info.Params,
                            UserId  = info.UserId,
                            InboxId = info.Id
                        };
                        using (profiler.CurrentRequest.Start(ProfileAction.Workflow, $"Resume '{bm.BookmarkName}'"))
                        {
                            aw._application.ResumeBookmark(bm.BookmarkName, rr);
                        }
                        return(result);                        // already resumed
                    }
                }
                // if a bookmark is not found
                aw._application.Unload();
            }
            catch (Exception ex)
            {
                if (!CatchWorkflow(aw, ex))
                {
                    throw;
                }
            }
            finally
            {
                ProcessFinally(aw);
            }
            return(result);
        }