Container for the parameters to the PollForDecisionTask operation.

Used by deciders to get a DecisionTask from the specified decision taskList . A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle the task.

This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.

IMPORTANT: Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the timeout).

IMPORTANT: Because the number of workflow history events for a single workflow execution might be very large, the result returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask using the nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken. Instead, call PollForDecisionTask again.

Access Control

You can use IAM policies to control this action's access to Amazon SWF resources as follows:

  • Use a Resource element with the domain name to limit the action to only specified domains.
  • Use an Action element to allow or deny permission to call this action.
  • Constrain the taskList.name parameter by using a Condition element with the swf:taskList.name key to allow the action to access only certain task lists.

If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified constraints, the action fails by throwing OperationNotPermitted . For details and example IAM policies, see Using IAM to Manage Access to Amazon SWF Workflows .

Inheritance: Amazon.Runtime.AmazonWebServiceRequest
 DecisionTask Poll()
 {
     Logger.LogMessage("Polling for Decision task ...");
     PollForDecisionTaskRequest request = new PollForDecisionTaskRequest()
     {
         Domain = Constants.SWF_DOMAIN,
         TaskList = new TaskList()
         {
             Name = Constants.SWF_DECIDER_TASKLIST
         }
     };
     PollForDecisionTaskResponse response = _swfClient.PollForDecisionTaskAsync(request).Result;
     return response.DecisionTask;
 }
        /// <summary>
        /// Constructor for the workflow event processor. 
        /// </summary>
        /// <param name="decisionTask">Decision task passed in from SWF as decision task response.</param>
        /// <param name="workflows">IEnumerable set of string for workflow name and Type for workflow class.</param>
        /// <param name="request">The request used to retrieve <paramref name="decisionTask"/>, which will be used to retrieve subsequent history event pages.</param>
        /// <param name="swfClient">An SWF client.</param>
        public WorkflowEventsProcessor(DecisionTask decisionTask, IEnumerable<KeyValuePair<string, Type>> workflows, PollForDecisionTaskRequest request, IAmazonSimpleWorkflow swfClient)
        {
            // Decision task can't be null.
            if (decisionTask == null)
            {
                throw new ArgumentNullException("decisionTask");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Store the decision task and allocate a new decision context and event dictionary which
            // we will use as we walk through the chain of events
            _decisionTask = decisionTask;
            _request = request;
            _decisionContext = new WorkflowDecisionContext();
            _swfClient = swfClient;

            // Set up our events data structure
            _events = new WorkflowEventsIterator(ref decisionTask, _request, _swfClient);
            _workflows = (Dictionary<string, Type>) workflows;
        }
Beispiel #3
0
 /// <summary>
 /// <para> Used by deciders to get a DecisionTask from the specified decision <c>taskList</c> .
 /// A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated
 /// view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle
 /// the task. </para> <para> This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task
 /// becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is
 /// returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.
 /// Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the timeout). </para>
 /// <para><b>IMPORTANT:</b> Because the number of workflow history events for a single workflow execution might be very large, the result
 /// returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask using the
 /// nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken. Instead, call
 /// PollForDecisionTask again. </para>
 /// </summary>
 /// 
 /// <param name="pollForDecisionTaskRequest">Container for the necessary parameters to execute the PollForDecisionTask service method on
 ///          AmazonSimpleWorkflow.</param>
 /// 
 /// <returns>The response from the PollForDecisionTask service method, as returned by AmazonSimpleWorkflow.</returns>
 /// 
 /// <exception cref="OperationNotPermittedException"/>
 /// <exception cref="UnknownResourceException"/>
 public PollForDecisionTaskResponse PollForDecisionTask(PollForDecisionTaskRequest pollForDecisionTaskRequest)
 {
     IAsyncResult asyncResult = invokePollForDecisionTask(pollForDecisionTaskRequest, null, null, true);
     return EndPollForDecisionTask(asyncResult);
 }
        /// <summary>
        /// <para> Used by deciders to get a DecisionTask from the specified decision <c>taskList</c> .
        /// A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated
        /// view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle
        /// the task. </para> <para> This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task
        /// becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is
        /// returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.
        /// </para> <para><b>IMPORTANT:</b> Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the
        /// timeout). </para> <para><b>IMPORTANT:</b> Because the number of workflow history events for a single workflow execution might be very large,
        /// the result returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask
        /// using the nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken.
        /// Instead, call PollForDecisionTask again. </para> <para> <b>Access Control</b> </para> <para>You can use IAM policies to control this
        /// action's access to Amazon SWF resources as follows:</para>
        /// <ul>
        /// <li>Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.</li>
        /// <li>Use an <c>Action</c> element to allow or deny permission to call this action.</li>
        /// <li>Constrain the <c>taskList.name</c> parameter by using a <b>Condition</b> element with the <c>swf:taskList.name</c> key to allow the
        /// action to access only certain task lists.</li>
        /// 
        /// </ul>
        /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified
        /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF Workflows</a>
        /// .</para>
        /// </summary>
        /// 
        /// <param name="pollForDecisionTaskRequest">Container for the necessary parameters to execute the PollForDecisionTask service method on
        /// AmazonSimpleWorkflow.</param>
        /// 
        /// <returns>The response from the PollForDecisionTask service method, as returned by AmazonSimpleWorkflow.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.OperationNotPermittedException" />
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.UnknownResourceException" />
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.LimitExceededException" />
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public Task<PollForDecisionTaskResponse> PollForDecisionTaskAsync(PollForDecisionTaskRequest pollForDecisionTaskRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PollForDecisionTaskRequestMarshaller();
            var unmarshaller = PollForDecisionTaskResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, PollForDecisionTaskRequest, PollForDecisionTaskResponse>(pollForDecisionTaskRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
		internal PollForDecisionTaskResponse PollForDecisionTask(PollForDecisionTaskRequest request)
        {
            var task = PollForDecisionTaskAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the PollForDecisionTask operation.
        /// <seealso cref="Amazon.SimpleWorkflow.IAmazonSimpleWorkflow"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the PollForDecisionTask operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<PollForDecisionTaskResponse> PollForDecisionTaskAsync(PollForDecisionTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PollForDecisionTaskRequestMarshaller();
            var unmarshaller = PollForDecisionTaskResponseUnmarshaller.Instance;

            return InvokeAsync<PollForDecisionTaskRequest,PollForDecisionTaskResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
        /// <summary>
        /// Used by deciders to get a <a>DecisionTask</a> from the specified decision <code>taskList</code>.
        /// A decision task may be returned for any open workflow execution that is using the
        /// specified task list. The task includes a paginated view of the history of the workflow
        /// execution. The decider should use the workflow type and the history to determine how
        /// to properly handle the task. 
        /// 
        ///  
        /// <para>
        ///  This action initiates a long poll, where the service holds the HTTP connection open
        /// and responds as soon a task becomes available. If no decision task is available in
        /// the specified task list before the timeout of 60 seconds expires, an empty result
        /// is returned. An empty result, in this context, means that a DecisionTask is returned,
        /// but that the value of taskToken is an empty string. 
        /// </para>
        ///  <important> Deciders should set their client side socket timeout to at least 70 seconds
        /// (10 seconds higher than the timeout). </important> <important> Because the number
        /// of workflow history events for a single workflow execution might be very large, the
        /// result returned might be split up across a number of pages. To retrieve subsequent
        /// pages, make additional calls to <code>PollForDecisionTask</code> using the <code>nextPageToken</code>
        /// returned by the initial call. Note that you do <b>not</b> call <code>GetWorkflowExecutionHistory</code>
        /// with this <code>nextPageToken</code>. Instead, call <code>PollForDecisionTask</code>
        /// again. </important> 
        /// <para>
        /// <b>Access Control</b>
        /// </para>
        ///  
        /// <para>
        /// You can use IAM policies to control this action's access to Amazon SWF resources as
        /// follows:
        /// </para>
        ///  <ul> <li>Use a <code>Resource</code> element with the domain name to limit the action
        /// to only specified domains.</li> <li>Use an <code>Action</code> element to allow or
        /// deny permission to call this action.</li> <li>Constrain the <code>taskList.name</code>
        /// parameter by using a <b>Condition</b> element with the <code>swf:taskList.name</code>
        /// key to allow the action to access only certain task lists.</li> </ul> 
        /// <para>
        /// If the caller does not have sufficient permissions to invoke the action, or the parameter
        /// values fall outside the specified constraints, the action fails by throwing <code>OperationNotPermitted</code>.
        /// For details and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using
        /// IAM to Manage Access to Amazon SWF Workflows</a>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the PollForDecisionTask service method.</param>
        /// 
        /// <returns>The response from the PollForDecisionTask service method, as returned by SimpleWorkflow.</returns>
        /// <exception cref="LimitExceededException">
        /// Returned by any operation if a system imposed limitation has been reached. To address
        /// this fault you should either clean up unused resources or increase the limit by contacting
        /// AWS.
        /// </exception>
        /// <exception cref="OperationNotPermittedException">
        /// Returned when the caller does not have sufficient permissions to invoke the action.
        /// </exception>
        /// <exception cref="UnknownResourceException">
        /// Returned when the named resource cannot be found with in the scope of this operation
        /// (region or domain). This could happen if the named resource was never created or is
        /// no longer available for this operation.
        /// </exception>
        public PollForDecisionTaskResponse PollForDecisionTask(PollForDecisionTaskRequest request)
        {
            var marshaller = new PollForDecisionTaskRequestMarshaller();
            var unmarshaller = PollForDecisionTaskResponseUnmarshaller.Instance;

            return Invoke<PollForDecisionTaskRequest,PollForDecisionTaskResponse>(request, marshaller, unmarshaller);
        }
 internal PollForDecisionTaskPaginator(IAmazonSimpleWorkflow client, PollForDecisionTaskRequest request)
 {
     this._client  = client;
     this._request = request;
 }
Beispiel #9
0
 /// <summary>
 /// Helper method to poll for decision task from the task list.
 /// </summary>
 /// <returns>Decision task returned from the long poll</returns>
 DecisionTask Poll()
 {
     Console.WriteLine("Polling for decision task ...");
     PollForDecisionTaskRequest request = new PollForDecisionTaskRequest()
     {
         Domain = CQRS.AWS.Common.Constants.WFDomain,
         TaskList = new TaskList()
         {
             Name = CQRS.AWS.DecisionConsole.Shared.Constants.WFTaskList
         }
     };
     PollForDecisionTaskResponse response = _swfClient.PollForDecisionTask(request);
     return response.DecisionTask;
 }
        /// <summary>
        /// <para> Used by deciders to get a DecisionTask from the specified decision <c>taskList</c> .
        /// A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated
        /// view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle
        /// the task. </para> <para> This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task
        /// becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is
        /// returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.
        /// </para> <para><b>IMPORTANT:</b> Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the
        /// timeout). </para> <para><b>IMPORTANT:</b> Because the number of workflow history events for a single workflow execution might be very large,
        /// the result returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask
        /// using the nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken.
        /// Instead, call PollForDecisionTask again. </para> <para> <b>Access Control</b> </para> <para>You can use IAM policies to control this
        /// action's access to Amazon SWF resources as follows:</para>
        /// <ul>
        /// <li>Use a <c>Resource</c> element with the domain name to limit the action to only specified domains.</li>
        /// <li>Use an <c>Action</c> element to allow or deny permission to call this action.</li>
        /// <li>Constrain the <c>taskList.name</c> parameter by using a <b>Condition</b> element with the <c>swf:taskList.name</c> key to allow the
        /// action to access only certain task lists.</li>
        /// 
        /// </ul>
        /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified
        /// constraints, the action fails by throwing <c>OperationNotPermitted</c> . For details and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF Workflows</a>
        /// .</para>
        /// </summary>
        /// 
        /// <param name="pollForDecisionTaskRequest">Container for the necessary parameters to execute the PollForDecisionTask service method on
        /// AmazonSimpleWorkflow.</param>
        /// 
        /// <returns>The response from the PollForDecisionTask service method, as returned by AmazonSimpleWorkflow.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.OperationNotPermittedException" />
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.UnknownResourceException" />
        /// <exception cref="T:Amazon.SimpleWorkflow.Model.LimitExceededException" />
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public async Task<PollForDecisionTaskResponse> PollForDecisionTaskAsync(PollForDecisionTaskRequest pollForDecisionTaskRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PollForDecisionTaskRequestMarshaller();
            var unmarshaller = PollForDecisionTaskResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, PollForDecisionTaskRequest, PollForDecisionTaskResponse>(pollForDecisionTaskRequest, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
		internal PollForDecisionTaskResponse PollForDecisionTask(PollForDecisionTaskRequest request)
        {
            var task = PollForDecisionTaskAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
Beispiel #12
0
 /// <summary>
 /// Paginator for PollForDecisionTask operation
 ///</summary>
 public IPollForDecisionTaskPaginator PollForDecisionTask(PollForDecisionTaskRequest request)
 {
     return(new PollForDecisionTaskPaginator(this.client, request));
 }
Beispiel #13
0
        // Simple logic
        //  Creates four activities at the begining
        //  Waits for them to complete and completes the workflow
        static void Decider()
        {
            int activityCount = 0; // This refers to total number of activities per workflow
              IAmazonSimpleWorkflow swfClient = AWSClientFactory.CreateAmazonSimpleWorkflowClient();
              while (true)
              {
            Console.WriteLine("Decider: Polling for decision task ...");
            PollForDecisionTaskRequest request = new PollForDecisionTaskRequest()
                              {
                                Domain = domainName,
                                TaskList = new TaskList() {Name = "HelloWorld"}
                              };

            PollForDecisionTaskResponse response = swfClient.PollForDecisionTask(request);
            if (response.DecisionTask.TaskToken == null)
            {
              Console.WriteLine("Decider: NULL");
              continue;
            }

            int completedActivityTaskCount = 0, totalActivityTaskCount = 0;
            foreach (HistoryEvent e in response.DecisionTask.Events)
            {
              Console.WriteLine("Decider: EventType - " + e.EventType +
              ", EventId - " + e.EventId);
              if (e.EventType == "ActivityTaskCompleted")
            completedActivityTaskCount++;
              if (e.EventType.Value.StartsWith("Activity"))
            totalActivityTaskCount++;
            }
            Console.WriteLine(".... completedCount=" + completedActivityTaskCount);

            List<Decision> decisions = new List<Decision>();
            if (totalActivityTaskCount == 0) // Create this only at the begining
            {
              ScheduleActivity("Activity1A", decisions);
              ScheduleActivity("Activity1B", decisions);
              ScheduleActivity("Activity2", decisions);
              ScheduleActivity("Activity2", decisions);
              activityCount = 4;
            }
            else if (completedActivityTaskCount == activityCount)
            {
              Decision decision = new Decision()
              {
            DecisionType = DecisionType.CompleteWorkflowExecution,
            CompleteWorkflowExecutionDecisionAttributes =
                new CompleteWorkflowExecutionDecisionAttributes {
                          Result = "{\"Result\":\"WF Complete!\"}"
                        }
              };
              decisions.Add(decision);

              Console.WriteLine("Decider: WORKFLOW COMPLETE!!!!!!!!!!!!!!!!!!!!!!");
            }
            RespondDecisionTaskCompletedRequest respondDecisionTaskCompletedRequest =
            new RespondDecisionTaskCompletedRequest() {
                      Decisions = decisions,
                      TaskToken = response.DecisionTask.TaskToken
                    };
            swfClient.RespondDecisionTaskCompleted(respondDecisionTaskCompletedRequest);
              }
        }
 /// <summary>
 /// <para> Used by deciders to get a DecisionTask from the specified decision <c>taskList</c> .
 /// A decision task may be returned for any open workflow execution that is using the specified task list. The task includes a paginated
 /// view of the history of the workflow execution. The decider should use the workflow type and the history to determine how to properly handle
 /// the task. </para> <para> This action initiates a long poll, where the service holds the HTTP connection open and responds as soon a task
 /// becomes available. If no decision task is available in the specified task list before the timeout of 60 seconds expires, an empty result is
 /// returned. An empty result, in this context, means that a DecisionTask is returned, but that the value of taskToken is an empty string.
 /// </para> <para><b>IMPORTANT:</b> Deciders should set their client side socket timeout to at least 70 seconds (10 seconds higher than the
 /// timeout). </para> <para><b>IMPORTANT:</b> Because the number of workflow history events for a single workflow execution might be very large,
 /// the result returned might be split up across a number of pages. To retrieve subsequent pages, make additional calls to PollForDecisionTask
 /// using the nextPageToken returned by the initial call. Note that you do not call GetWorkflowExecutionHistory with this nextPageToken.
 /// Instead, call PollForDecisionTask again. </para>
 /// </summary>
 /// 
 /// <param name="pollForDecisionTaskRequest">Container for the necessary parameters to execute the PollForDecisionTask service method on
 ///           AmazonSimpleWorkflow.</param>
 /// 
 /// <returns>The response from the PollForDecisionTask service method, as returned by AmazonSimpleWorkflow.</returns>
 /// 
 /// <exception cref="OperationNotPermittedException"/>
 /// <exception cref="UnknownResourceException"/>
 public PollForDecisionTaskResponse PollForDecisionTask(PollForDecisionTaskRequest pollForDecisionTaskRequest)
 {
     IRequest<PollForDecisionTaskRequest> request = new PollForDecisionTaskRequestMarshaller().Marshall(pollForDecisionTaskRequest);
     PollForDecisionTaskResponse response = Invoke<PollForDecisionTaskRequest, PollForDecisionTaskResponse> (request, this.signer, PollForDecisionTaskResponseUnmarshaller.GetInstance());
     return response;
 }
        public static void Main(string[] args)
        {
            // Define the workflows that we know of that event processor will be handling
            var workflows = new Dictionary<string, Type>
                {
                    {"CustomerOrderWorkflow", typeof (CustomerOrderWorkflow)},
                    {"VerifyCustomerWorkflow", typeof (VerifyCustomerWorkflow)}
                };


            // Stopwatch to see how well we are performing
            var stopwatch = new Stopwatch();

            // We will use this ID as our decision task ID and activity task ID to identify ourselves when polling for
            // decision and activity tasks.
            var workflowWorkerIdentity = Guid.NewGuid();
            
            // Print out our AWS SWF domains, workflows and activities
            Console.Write(GetServiceOutput());

            var loop = true;
            do
            {
                // Our super simple application menu
                Console.WriteLine("");
                Console.WriteLine("=============");
                Console.WriteLine("| Main Menu |");
                Console.WriteLine("=============");
                Console.WriteLine("[1] Submit a new workflow");
                Console.WriteLine("[2] Wait for decide using a decision task");
                Console.WriteLine("[3] Wait for and do some work for an activity task");
                Console.WriteLine("[4] Quit");

                Console.Write("\nChoice: ");
                var key = Console.ReadLine();

                if (String.IsNullOrEmpty(key))
                {
                    continue;
                }

                switch (key)
                {
                    // Initiate a workflow execution
                    case "1":
                        {
                            Console.WriteLine("Option [1] selected - Submit a new workflow");

                            // SWF client is disposable, so dispose it
                            using (var swfClient = new AmazonSimpleWorkflowClient(RegionEndpoint.USWest2))
                            {
                                // Our simple property bag: we just need to the email for the account
                                var propertyBag = new Dictionary<string, object> { { "SampleOrderNumber", "12345" } };

                                // Setup the workflow request
                                var workflowRequest = new StartWorkflowExecutionRequest
                                {
                                    Domain = "demo-domain",
                                    WorkflowId = Guid.NewGuid().ToString(),
                                    WorkflowType = new WorkflowType
                                    {
                                        Name = "CustomerOrderWorkflow",
                                        Version = "1.0"
                                    },
                                    Input = JsonConvert.SerializeObject(propertyBag)
                                };

                                try
                                {
                                    // Call AWS SWF and submit the workflow request
                                    swfClient.StartWorkflowExecution(workflowRequest);
                                }
                                catch (AmazonSimpleWorkflowException ex)
                                {
                                    Console.WriteLine("Caught Exception: " + ex.Message);
                                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                                    Console.WriteLine("Error Type: " + ex.ErrorType);
                                    Console.WriteLine("Request ID: " + ex.RequestId);
                                    Console.WriteLine("Data: " + ex.Data);
                                    Console.WriteLine("Stacktrace: " + ex.StackTrace);
                                }
                            }
                        }
                        break;

                    // Poll for decision task
                    case "2":
                        {
                            Console.WriteLine("Option [2] selected - Wait for decide using a decision task");
                            Console.WriteLine("Waiting...");

                            // SWF client is disposable, so dispose it
                            using (var swfClient = new AmazonSimpleWorkflowClient(RegionEndpoint.USWest2))
                            {
                                try
                                {
                                    // Setup the decision request
                                    var decisionTaskRequest = new PollForDecisionTaskRequest
                                    {
                                        Domain = "demo-domain",
                                        Identity = workflowWorkerIdentity.ToString(),
                                        TaskList = new TaskList { Name = "DeciderTaskList-Default" }
                                    };

                                    // Call AWS SWF and wait for (default timeout: 60 secs) a decision task
                                    var decisionTaskResponse = swfClient.PollForDecisionTask(decisionTaskRequest);

                                    // Task token being an empty string means there are no tasks available and 
                                    // we are past the 60 seconds that AWS holds a connection in case a task
                                    // becomes available. If this is the case, we simply retry.
                                    var taskToken =
                                        decisionTaskResponse.DecisionTask.TaskToken;
                                    if (!String.IsNullOrEmpty(taskToken))
                                    {
                                        // We have a valid task, do something...
                                        var decisionTask =
                                            decisionTaskResponse.DecisionTask;

                                        switch (decisionTask.WorkflowType.Name)
                                        {
                                            case "CustomerOrderWorkflow":
                                            case "VerifyCustomerWorkflow":
                                                {
                                                    Debug.Assert(decisionTask.WorkflowType.Version == "1.0");
                                                }
                                                break;

                                            default:
                                                Console.WriteLine("ERROR: Unknown workflow.");
                                                break;
                                        }

                                        // Define a new WorkflowEventsProcessor object and let it make the decision!
                                        stopwatch.Start();
                                        var workflowProcessor = new WorkflowEventsProcessor(decisionTask, workflows, decisionTaskRequest, swfClient);
                                        var decisionRequest = workflowProcessor.Decide();
                                        stopwatch.Stop();

                                        Console.WriteLine(">>> Decision(s) made in " + stopwatch.ElapsedMilliseconds + "ms");

                                        // We have our decision, send it away and do something 
                                        // more productive with the response
                                        swfClient.RespondDecisionTaskCompleted(decisionRequest);
                                    }
                                }
                                catch (AmazonSimpleWorkflowException ex)
                                {
                                    Console.WriteLine("Caught Exception: " + ex.Message);
                                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                                    Console.WriteLine("Error Type: " + ex.ErrorType);
                                    Console.WriteLine("Request ID: " + ex.RequestId);
                                    Console.WriteLine("Data: " + ex.Data);
                                    Console.WriteLine("Stacktrace: " + ex.StackTrace);
                                }
                            }
                        }
                        break;

                    // Poll for activity task
                    case "3":
                        {
                            Console.WriteLine("Option [3] selected - Wait for decide using a activity task");
                            Console.WriteLine("Waiting...");

                            // SWF client is disposable, so dispose it
                            using (var swfClient = new AmazonSimpleWorkflowClient(RegionEndpoint.USWest2))
                            {
                                try
                                {
                                    // Setup the activity request
                                    var activityTaskRequest = new PollForActivityTaskRequest
                                    {
                                        Domain = "demo-domain",
                                        Identity = workflowWorkerIdentity.ToString(),
                                        TaskList = new TaskList { Name = "ActivityTaskList-Default" }
                                    };

                                    // Call AWS SWF and wait for (default timeout: 60 secs) a activity task
                                    var activityTaskResponse = swfClient.PollForActivityTask(activityTaskRequest);

                                    // Task token being an empty string means there are no tasks available and 
                                    // we are past the 60 seconds that AWS holds a connection in case a task
                                    // becomes available. If this is the case, we simply retry.
                                    var taskToken =
                                        activityTaskResponse.ActivityTask.TaskToken;
                                    if (!String.IsNullOrEmpty(taskToken))
                                    {
                                        // We have a valid task, do something...
                                        var activityTask =
                                            activityTaskResponse.ActivityTask;

                                        Console.WriteLine("\n");
                                        Console.WriteLine(">>> Activity: " + activityTask.ActivityType.Name);

                                        // In the real world we would define the activity code in a separate object
                                        // and fire off a thread to actually work on it but in this case we are just
                                        // testing the workflow so this suffices
                                        switch (activityTask.ActivityType.Name)
                                        {
                                            // CustomerOrderWorkflow activities
                                            case "VerifyOrder":
                                            case "ShipOrder":
                                                {
                                                    Debug.Assert(activityTask.ActivityType.Version == "1.0");
                                                }
                                                break;

                                            // VerifyCustomerWorkflow activities
                                            case "VerifyCustomerAddress":
                                            case "CheckFraudDB":
                                            case "ChargeCreditCard":
                                                {
                                                    Debug.Assert(activityTask.ActivityType.Version == "1.0");
                                                }
                                                break;

                                            default:
                                                Console.WriteLine("ERROR: Unknown activity.");
                                                break;
                                        }

                                        var activityCompletedRequest = new RespondActivityTaskCompletedRequest
                                        {
                                            TaskToken = activityTask.TaskToken,
                                            Result = activityTask.Input
                                        };

                                        // Completion request setup complete, send it away. NOTE: Do something more
                                        // productive with the response
                                        swfClient.RespondActivityTaskCompleted(activityCompletedRequest);

                                        //var activityFailedRequest = new RespondActivityTaskFailedRequest
                                        //    {
                                        //        TaskToken = activityTask.TaskToken,
                                        //        Details = "Test failure."
                                        //    };
                                        //// Completion request setup complete, send it away. NOTE: Do something more
                                        //// productive with the response
                                        //swfClient.RespondActivityTaskFailed(activityFailedRequest);
                                    }
                                }
                                catch (AmazonSimpleWorkflowException ex)
                                {
                                    Console.WriteLine("Caught Exception: " + ex.Message);
                                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                                    Console.WriteLine("Error Type: " + ex.ErrorType);
                                    Console.WriteLine("Request ID: " + ex.RequestId);
                                    Console.WriteLine("Data: " + ex.Data);
                                    Console.WriteLine("Stacktrace: " + ex.StackTrace);
                                }
                            }
                        }
                        break;

                    case "4":
                        // Quit
                        loop = false;
                        break;

                    default:
                        Console.WriteLine("ERROR: Unknown command.");
                        break;
                }
            } while (loop);
        }
Beispiel #16
0
 IAsyncResult invokePollForDecisionTask(PollForDecisionTaskRequest pollForDecisionTaskRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new PollForDecisionTaskRequestMarshaller().Marshall(pollForDecisionTaskRequest);
     var unmarshaller = PollForDecisionTaskResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Beispiel #17
0
 /// <summary>
 /// Initiates the asynchronous execution of the PollForDecisionTask operation.
 /// <seealso cref="Amazon.SimpleWorkflow.AmazonSimpleWorkflow.PollForDecisionTask"/>
 /// </summary>
 /// 
 /// <param name="pollForDecisionTaskRequest">Container for the necessary parameters to execute the PollForDecisionTask operation on
 ///          AmazonSimpleWorkflow.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
 ///         EndPollForDecisionTask operation.</returns>
 public IAsyncResult BeginPollForDecisionTask(PollForDecisionTaskRequest pollForDecisionTaskRequest, AsyncCallback callback, object state)
 {
     return invokePollForDecisionTask(pollForDecisionTaskRequest, callback, state, false);
 }
        /// <summary>
        /// Initiates the asynchronous execution of the PollForDecisionTask operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the PollForDecisionTask operation on AmazonSimpleWorkflowClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPollForDecisionTask
        ///         operation.</returns>
        public IAsyncResult BeginPollForDecisionTask(PollForDecisionTaskRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new PollForDecisionTaskRequestMarshaller();
            var unmarshaller = PollForDecisionTaskResponseUnmarshaller.Instance;

            return BeginInvoke<PollForDecisionTaskRequest>(request, marshaller, unmarshaller,
                callback, state);
        }