Esempi di Step Functions utilizzando AWS SDK for .NET - Esempi di codice dell'AWS SDK

Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples GitHub .

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di Step Functions utilizzando AWS SDK for .NET

I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando AWS SDK for .NET with Step Functions.

Le basi sono esempi di codice che mostrano come eseguire le operazioni essenziali all'interno di un servizio.

Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Mentre le azioni mostrano come richiamare le singole funzioni di servizio, è possibile visualizzare le azioni nel loro contesto nei relativi scenari.

Ogni esempio include un collegamento al codice sorgente completo, in cui è possibile trovare istruzioni su come configurare ed eseguire il codice nel contesto.

Nozioni di base

I seguenti esempi di codice mostrano come iniziare a usare Step Functions.

AWS SDK for .NET
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

namespace StepFunctionsActions; using Amazon.StepFunctions; using Amazon.StepFunctions.Model; public class HelloStepFunctions { static async Task Main() { var stepFunctionsClient = new AmazonStepFunctionsClient(); Console.Clear(); Console.WriteLine("Welcome to AWS Step Functions"); Console.WriteLine("Let's list up to 10 of your state machines:"); var stateMachineListRequest = new ListStateMachinesRequest { MaxResults = 10 }; // Get information for up to 10 Step Functions state machines. var response = await stepFunctionsClient.ListStateMachinesAsync(stateMachineListRequest); if (response.StateMachines.Count > 0) { response.StateMachines.ForEach(stateMachine => { Console.WriteLine($"State Machine Name: {stateMachine.Name}\tAmazon Resource Name (ARN): {stateMachine.StateMachineArn}"); }); } else { Console.WriteLine("\tNo state machines were found."); } } }

Nozioni di base

L'esempio di codice seguente mostra come:

  • Crea un'attività.

  • Crea una macchina a stati da una definizione di Amazon States Language che contiene l'attività creata in precedenza come passaggio.

  • Esegui la macchina a stati e rispondi all'attività con l'input dell'utente.

  • Ottieni lo stato e l'output finali al termine dell'esecuzione, quindi ripulisci le risorse.

AWS SDK for .NET
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Esegui uno scenario interattivo al prompt dei comandi.

global using System.Text.Json; global using Amazon.StepFunctions; global using Microsoft.Extensions.Configuration; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; global using Microsoft.Extensions.Logging.Console; global using Microsoft.Extensions.Logging.Debug; global using StepFunctionsActions; global using LogLevel = Microsoft.Extensions.Logging.LogLevel; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.StepFunctions.Model; namespace StepFunctionsBasics; public class StepFunctionsBasics { private static ILogger _logger = null!; private static IConfigurationRoot _configuration = null!; private static IAmazonIdentityManagementService _iamService = null!; static async Task Main(string[] args) { // Set up dependency injection for AWS Step Functions. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonStepFunctions>() .AddAWSService<IAmazonIdentityManagementService>() .AddTransient<StepFunctionsWrapper>() ) .Build(); _logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<StepFunctionsBasics>(); // Load configuration settings. _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load test settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); var activityName = _configuration["ActivityName"]; var stateMachineName = _configuration["StateMachineName"]; var roleName = _configuration["RoleName"]; var repoBaseDir = _configuration["RepoBaseDir"]; var jsonFilePath = _configuration["JsonFilePath"]; var jsonFileName = _configuration["JsonFileName"]; var uiMethods = new UiMethods(); var stepFunctionsWrapper = host.Services.GetRequiredService<StepFunctionsWrapper>(); _iamService = host.Services.GetRequiredService<IAmazonIdentityManagementService>(); // Load definition for the state machine from a JSON file. var stateDefinitionJson = File.ReadAllText($"{repoBaseDir}{jsonFilePath}{jsonFileName}"); Console.Clear(); uiMethods.DisplayOverview(); uiMethods.PressEnter(); uiMethods.DisplayTitle("Create activity"); Console.WriteLine("Let's start by creating an activity."); string activityArn; string stateMachineArn; // Check to see if the activity already exists. var activityList = await stepFunctionsWrapper.ListActivitiesAsync(); var existingActivity = activityList.FirstOrDefault(activity => activity.Name == activityName); if (existingActivity is not null) { activityArn = existingActivity.ActivityArn; Console.WriteLine($"Activity, {activityName}, already exists."); } else { activityArn = await stepFunctionsWrapper.CreateActivity(activityName); } // Swap the placeholder in the JSON file with the Amazon Resource Name (ARN) // of the recently created activity. var stateDefinition = stateDefinitionJson.Replace("{{DOC_EXAMPLE_ACTIVITY_ARN}}", activityArn); uiMethods.DisplayTitle("Create state machine"); Console.WriteLine("Now we'll create a state machine."); // Find or create an IAM role that can be assumed by Step Functions. var role = await GetOrCreateStateMachineRole(roleName); // See if the state machine already exists. var stateMachineList = await stepFunctionsWrapper.ListStateMachinesAsync(); var existingStateMachine = stateMachineList.FirstOrDefault(stateMachine => stateMachine.Name == stateMachineName); if (existingStateMachine is not null) { Console.WriteLine($"State machine, {stateMachineName}, already exists."); stateMachineArn = existingStateMachine.StateMachineArn; } else { // Create the state machine. stateMachineArn = await stepFunctionsWrapper.CreateStateMachine(stateMachineName, stateDefinition, role.Arn); uiMethods.PressEnter(); } Console.WriteLine("The state machine has been created."); var describeStateMachineResponse = await stepFunctionsWrapper.DescribeStateMachineAsync(stateMachineArn); Console.WriteLine($"{describeStateMachineResponse.Name}\t{describeStateMachineResponse.StateMachineArn}"); Console.WriteLine($"Current status: {describeStateMachineResponse.Status}"); Console.WriteLine($"Amazon Resource Name (ARN) of the role assumed by the state machine: {describeStateMachineResponse.RoleArn}"); var userName = string.Empty; Console.Write("Before we start the state machine, tell me what should ChatSFN call you? "); userName = Console.ReadLine(); // Keep asking until the user enters a string value. while (string.IsNullOrEmpty(userName)) { Console.Write("Enter your name: "); userName = Console.ReadLine(); } var executionJson = @"{""name"": """ + userName + @"""}"; // Start the state machine execution. Console.WriteLine("Now we'll start execution of the state machine."); var executionArn = await stepFunctionsWrapper.StartExecutionAsync(executionJson, stateMachineArn); Console.WriteLine("State machine started."); Console.WriteLine($"Thank you, {userName}. Now let's get started..."); uiMethods.PressEnter(); uiMethods.DisplayTitle("ChatSFN"); var isDone = false; var response = new GetActivityTaskResponse(); var taskToken = string.Empty; var userChoice = string.Empty; while (!isDone) { response = await stepFunctionsWrapper.GetActivityTaskAsync(activityArn, "MvpWorker"); taskToken = response.TaskToken; // Parse the returned JSON string. var taskJsonResponse = JsonDocument.Parse(response.Input); var taskJsonObject = taskJsonResponse.RootElement; var message = taskJsonObject.GetProperty("message").GetString(); var actions = taskJsonObject.GetProperty("actions").EnumerateArray().Select(x => x.ToString()).ToList(); Console.WriteLine($"\n{message}\n"); // Prompt the user for another choice. Console.WriteLine("ChatSFN: What would you like me to do?"); actions.ForEach(action => Console.WriteLine($"\t{action}")); Console.Write($"\n{userName}, tell me your choice: "); userChoice = Console.ReadLine(); if (userChoice?.ToLower() == "done") { isDone = true; } Console.WriteLine($"You have selected: {userChoice}"); var jsonResponse = @"{""action"": """ + userChoice + @"""}"; await stepFunctionsWrapper.SendTaskSuccessAsync(taskToken, jsonResponse); } await stepFunctionsWrapper.StopExecution(executionArn); Console.WriteLine("Now we will wait for the execution to stop."); DescribeExecutionResponse executionResponse; do { executionResponse = await stepFunctionsWrapper.DescribeExecutionAsync(executionArn); } while (executionResponse.Status == ExecutionStatus.RUNNING); Console.WriteLine("State machine stopped."); uiMethods.PressEnter(); uiMethods.DisplayTitle("State machine executions"); Console.WriteLine("Now let's take a look at the execution values for the state machine."); // List the executions. var executions = await stepFunctionsWrapper.ListExecutionsAsync(stateMachineArn); uiMethods.DisplayTitle("Step function execution values"); executions.ForEach(execution => { Console.WriteLine($"{execution.Name}\t{execution.StartDate} to {execution.StopDate}"); }); uiMethods.PressEnter(); // Now delete the state machine and the activity. uiMethods.DisplayTitle("Clean up resources"); Console.WriteLine("Deleting the state machine..."); await stepFunctionsWrapper.DeleteStateMachine(stateMachineArn); Console.WriteLine("State machine deleted."); Console.WriteLine("Deleting the activity..."); await stepFunctionsWrapper.DeleteActivity(activityArn); Console.WriteLine("Activity deleted."); Console.WriteLine("The Amazon Step Functions scenario is now complete."); } static async Task<Role> GetOrCreateStateMachineRole(string roleName) { // Define the policy document for the role. var stateMachineRolePolicy = @"{ ""Version"": ""2012-10-17"", ""Statement"": [{ ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""states.amazonaws.com""}, ""Action"": ""sts:AssumeRole""}]}"; var role = new Role(); var roleExists = false; try { var getRoleResponse = await _iamService.GetRoleAsync(new GetRoleRequest { RoleName = roleName }); roleExists = true; role = getRoleResponse.Role; } catch (NoSuchEntityException) { // The role doesn't exist. Create it. Console.WriteLine($"Role, {roleName} doesn't exist. Creating it..."); } if (!roleExists) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = stateMachineRolePolicy, }; var createRoleResponse = await _iamService.CreateRoleAsync(request); role = createRoleResponse.Role; } return role; } } namespace StepFunctionsBasics; /// <summary> /// Some useful methods to make screen display easier. /// </summary> public class UiMethods { private readonly string _sepBar = new('-', Console.WindowWidth); /// <summary> /// Show information about the scenario. /// </summary> public void DisplayOverview() { Console.Clear(); DisplayTitle("Welcome to the AWS Step Functions Demo"); Console.WriteLine("This example application will do the following:"); Console.WriteLine("\t 1. Create an activity."); Console.WriteLine("\t 2. Create a state machine."); Console.WriteLine("\t 3. Start an execution."); Console.WriteLine("\t 4. Run the worker, then stop it."); Console.WriteLine("\t 5. List executions."); Console.WriteLine("\t 6. Clean up the resources created for the example."); } /// <summary> /// Display a message and wait until the user presses enter. /// </summary> public void PressEnter() { Console.Write("\nPress <Enter> to continue."); _ = Console.ReadLine(); } /// <summary> /// Pad a string with spaces to center it on the console display. /// </summary> /// <param name="strToCenter"></param> /// <returns></returns> private string CenterString(string strToCenter) { var padAmount = (Console.WindowWidth - strToCenter.Length) / 2; var leftPad = new string(' ', padAmount); return $"{leftPad}{strToCenter}"; } /// <summary> /// Display a line of hyphens, the centered text of the title, and another /// line of hyphens. /// </summary> /// <param name="strTitle">The string to be displayed.</param> public void DisplayTitle(string strTitle) { Console.WriteLine(_sepBar); Console.WriteLine(CenterString(strTitle)); Console.WriteLine(_sepBar); } }

Definisci una classe che racchiuda le azioni della macchina a stati e delle attività.

namespace StepFunctionsActions; using Amazon.StepFunctions; using Amazon.StepFunctions.Model; /// <summary> /// Wrapper that performs AWS Step Functions actions. /// </summary> public class StepFunctionsWrapper { private readonly IAmazonStepFunctions _amazonStepFunctions; /// <summary> /// The constructor for the StepFunctionsWrapper. Initializes the /// client object passed to it. /// </summary> /// <param name="amazonStepFunctions">An initialized Step Functions client object.</param> public StepFunctionsWrapper(IAmazonStepFunctions amazonStepFunctions) { _amazonStepFunctions = amazonStepFunctions; } /// <summary> /// Create a Step Functions activity using the supplied name. /// </summary> /// <param name="activityName">The name for the new Step Functions activity.</param> /// <returns>The Amazon Resource Name (ARN) for the new activity.</returns> public async Task<string> CreateActivity(string activityName) { var response = await _amazonStepFunctions.CreateActivityAsync(new CreateActivityRequest { Name = activityName }); return response.ActivityArn; } /// <summary> /// Create a Step Functions state machine. /// </summary> /// <param name="stateMachineName">Name for the new Step Functions state /// machine.</param> /// <param name="definition">A JSON string that defines the Step Functions /// state machine.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role.</param> /// <returns></returns> public async Task<string> CreateStateMachine(string stateMachineName, string definition, string roleArn) { var request = new CreateStateMachineRequest { Name = stateMachineName, Definition = definition, RoleArn = roleArn }; var response = await _amazonStepFunctions.CreateStateMachineAsync(request); return response.StateMachineArn; } /// <summary> /// Delete a Step Machine activity. /// </summary> /// <param name="activityArn">The Amazon Resource Name (ARN) of /// the activity.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteActivity(string activityArn) { var response = await _amazonStepFunctions.DeleteActivityAsync(new DeleteActivityRequest { ActivityArn = activityArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Delete a Step Functions state machine. /// </summary> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// state machine.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteStateMachine(string stateMachineArn) { var response = await _amazonStepFunctions.DeleteStateMachineAsync(new DeleteStateMachineRequest { StateMachineArn = stateMachineArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Retrieve information about the specified Step Functions execution. /// </summary> /// <param name="executionArn">The Amazon Resource Name (ARN) of the /// Step Functions execution.</param> /// <returns>The API response returned by the API.</returns> public async Task<DescribeExecutionResponse> DescribeExecutionAsync(string executionArn) { var response = await _amazonStepFunctions.DescribeExecutionAsync(new DescribeExecutionRequest { ExecutionArn = executionArn }); return response; } /// <summary> /// Retrieve information about the specified Step Functions state machine. /// </summary> /// <param name="StateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine to retrieve.</param> /// <returns>Information about the specified Step Functions state machine.</returns> public async Task<DescribeStateMachineResponse> DescribeStateMachineAsync(string StateMachineArn) { var response = await _amazonStepFunctions.DescribeStateMachineAsync(new DescribeStateMachineRequest { StateMachineArn = StateMachineArn }); return response; } /// <summary> /// Retrieve a task with the specified Step Functions activity /// with the specified Amazon Resource Name (ARN). /// </summary> /// <param name="activityArn">The Amazon Resource Name (ARN) of /// the Step Functions activity.</param> /// <param name="workerName">The name of the Step Functions worker.</param> /// <returns>The response from the Step Functions activity.</returns> public async Task<GetActivityTaskResponse> GetActivityTaskAsync(string activityArn, string workerName) { var response = await _amazonStepFunctions.GetActivityTaskAsync(new GetActivityTaskRequest { ActivityArn = activityArn, WorkerName = workerName }); return response; } /// <summary> /// List the Step Functions activities for the current account. /// </summary> /// <returns>A list of ActivityListItems.</returns> public async Task<List<ActivityListItem>> ListActivitiesAsync() { var request = new ListActivitiesRequest(); var activities = new List<ActivityListItem>(); do { var response = await _amazonStepFunctions.ListActivitiesAsync(request); if (response.NextToken is not null) { request.NextToken = response.NextToken; } activities.AddRange(response.Activities); } while (request.NextToken is not null); return activities; } /// <summary> /// Retrieve information about executions of a Step Functions /// state machine. /// </summary> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine.</param> /// <returns>A list of ExecutionListItem objects.</returns> public async Task<List<ExecutionListItem>> ListExecutionsAsync(string stateMachineArn) { var executions = new List<ExecutionListItem>(); ListExecutionsResponse response; var request = new ListExecutionsRequest { StateMachineArn = stateMachineArn }; do { response = await _amazonStepFunctions.ListExecutionsAsync(request); executions.AddRange(response.Executions); if (response.NextToken is not null) { request.NextToken = response.NextToken; } } while (response.NextToken is not null); return executions; } /// <summary> /// Retrieve a list of Step Functions state machines. /// </summary> /// <returns>A list of StateMachineListItem objects.</returns> public async Task<List<StateMachineListItem>> ListStateMachinesAsync() { var stateMachines = new List<StateMachineListItem>(); var listStateMachinesPaginator = _amazonStepFunctions.Paginators.ListStateMachines(new ListStateMachinesRequest()); await foreach (var response in listStateMachinesPaginator.Responses) { stateMachines.AddRange(response.StateMachines); } return stateMachines; } /// <summary> /// Indicate that the Step Functions task, indicated by the /// task token, has completed successfully. /// </summary> /// <param name="taskToken">Identifies the task.</param> /// <param name="taskResponse">The response received from executing the task.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> SendTaskSuccessAsync(string taskToken, string taskResponse) { var response = await _amazonStepFunctions.SendTaskSuccessAsync(new SendTaskSuccessRequest { TaskToken = taskToken, Output = taskResponse }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Start execution of an AWS Step Functions state machine. /// </summary> /// <param name="executionName">The name to use for the execution.</param> /// <param name="executionJson">The JSON string to pass for execution.</param> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine.</param> /// <returns>The Amazon Resource Name (ARN) of the AWS Step Functions /// execution.</returns> public async Task<string> StartExecutionAsync(string executionJson, string stateMachineArn) { var executionRequest = new StartExecutionRequest { Input = executionJson, StateMachineArn = stateMachineArn }; var response = await _amazonStepFunctions.StartExecutionAsync(executionRequest); return response.ExecutionArn; } /// <summary> /// Stop execution of a Step Functions workflow. /// </summary> /// <param name="executionArn">The Amazon Resource Name (ARN) of /// the Step Functions execution to stop.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> StopExecution(string executionArn) { var response = await _amazonStepFunctions.StopExecutionAsync(new StopExecutionRequest { ExecutionArn = executionArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } }

Azioni

Il seguente esempio di codice mostra come utilizzareCreateActivity.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Create a Step Functions activity using the supplied name. /// </summary> /// <param name="activityName">The name for the new Step Functions activity.</param> /// <returns>The Amazon Resource Name (ARN) for the new activity.</returns> public async Task<string> CreateActivity(string activityName) { var response = await _amazonStepFunctions.CreateActivityAsync(new CreateActivityRequest { Name = activityName }); return response.ActivityArn; }
  • Per API i dettagli, vedi CreateActivityin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareCreateStateMachine.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Create a Step Functions state machine. /// </summary> /// <param name="stateMachineName">Name for the new Step Functions state /// machine.</param> /// <param name="definition">A JSON string that defines the Step Functions /// state machine.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role.</param> /// <returns></returns> public async Task<string> CreateStateMachine(string stateMachineName, string definition, string roleArn) { var request = new CreateStateMachineRequest { Name = stateMachineName, Definition = definition, RoleArn = roleArn }; var response = await _amazonStepFunctions.CreateStateMachineAsync(request); return response.StateMachineArn; }

Il seguente esempio di codice mostra come utilizzareDeleteActivity.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Delete a Step Machine activity. /// </summary> /// <param name="activityArn">The Amazon Resource Name (ARN) of /// the activity.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteActivity(string activityArn) { var response = await _amazonStepFunctions.DeleteActivityAsync(new DeleteActivityRequest { ActivityArn = activityArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • Per API i dettagli, vedi DeleteActivityin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareDeleteStateMachine.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Delete a Step Functions state machine. /// </summary> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// state machine.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteStateMachine(string stateMachineArn) { var response = await _amazonStepFunctions.DeleteStateMachineAsync(new DeleteStateMachineRequest { StateMachineArn = stateMachineArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }

Il seguente esempio di codice mostra come utilizzareDescribeExecution.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Retrieve information about the specified Step Functions execution. /// </summary> /// <param name="executionArn">The Amazon Resource Name (ARN) of the /// Step Functions execution.</param> /// <returns>The API response returned by the API.</returns> public async Task<DescribeExecutionResponse> DescribeExecutionAsync(string executionArn) { var response = await _amazonStepFunctions.DescribeExecutionAsync(new DescribeExecutionRequest { ExecutionArn = executionArn }); return response; }

Il seguente esempio di codice mostra come utilizzareDescribeStateMachine.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Retrieve information about the specified Step Functions state machine. /// </summary> /// <param name="StateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine to retrieve.</param> /// <returns>Information about the specified Step Functions state machine.</returns> public async Task<DescribeStateMachineResponse> DescribeStateMachineAsync(string StateMachineArn) { var response = await _amazonStepFunctions.DescribeStateMachineAsync(new DescribeStateMachineRequest { StateMachineArn = StateMachineArn }); return response; }

Il seguente esempio di codice mostra come utilizzareGetActivityTask.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Retrieve a task with the specified Step Functions activity /// with the specified Amazon Resource Name (ARN). /// </summary> /// <param name="activityArn">The Amazon Resource Name (ARN) of /// the Step Functions activity.</param> /// <param name="workerName">The name of the Step Functions worker.</param> /// <returns>The response from the Step Functions activity.</returns> public async Task<GetActivityTaskResponse> GetActivityTaskAsync(string activityArn, string workerName) { var response = await _amazonStepFunctions.GetActivityTaskAsync(new GetActivityTaskRequest { ActivityArn = activityArn, WorkerName = workerName }); return response; }
  • Per API i dettagli, vedi GetActivityTaskin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareListActivities.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// List the Step Functions activities for the current account. /// </summary> /// <returns>A list of ActivityListItems.</returns> public async Task<List<ActivityListItem>> ListActivitiesAsync() { var request = new ListActivitiesRequest(); var activities = new List<ActivityListItem>(); do { var response = await _amazonStepFunctions.ListActivitiesAsync(request); if (response.NextToken is not null) { request.NextToken = response.NextToken; } activities.AddRange(response.Activities); } while (request.NextToken is not null); return activities; }
  • Per API i dettagli, vedi ListActivitiesin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareListExecutions.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Retrieve information about executions of a Step Functions /// state machine. /// </summary> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine.</param> /// <returns>A list of ExecutionListItem objects.</returns> public async Task<List<ExecutionListItem>> ListExecutionsAsync(string stateMachineArn) { var executions = new List<ExecutionListItem>(); ListExecutionsResponse response; var request = new ListExecutionsRequest { StateMachineArn = stateMachineArn }; do { response = await _amazonStepFunctions.ListExecutionsAsync(request); executions.AddRange(response.Executions); if (response.NextToken is not null) { request.NextToken = response.NextToken; } } while (response.NextToken is not null); return executions; }
  • Per API i dettagli, vedi ListExecutionsin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareListStateMachines.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Retrieve a list of Step Functions state machines. /// </summary> /// <returns>A list of StateMachineListItem objects.</returns> public async Task<List<StateMachineListItem>> ListStateMachinesAsync() { var stateMachines = new List<StateMachineListItem>(); var listStateMachinesPaginator = _amazonStepFunctions.Paginators.ListStateMachines(new ListStateMachinesRequest()); await foreach (var response in listStateMachinesPaginator.Responses) { stateMachines.AddRange(response.StateMachines); } return stateMachines; }

Il seguente esempio di codice mostra come utilizzareSendTaskSuccess.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Indicate that the Step Functions task, indicated by the /// task token, has completed successfully. /// </summary> /// <param name="taskToken">Identifies the task.</param> /// <param name="taskResponse">The response received from executing the task.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> SendTaskSuccessAsync(string taskToken, string taskResponse) { var response = await _amazonStepFunctions.SendTaskSuccessAsync(new SendTaskSuccessRequest { TaskToken = taskToken, Output = taskResponse }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • Per API i dettagli, vedi SendTaskSuccessin AWS SDK for .NET APIReference.

Il seguente esempio di codice mostra come utilizzareStartExecution.

AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Start execution of an AWS Step Functions state machine. /// </summary> /// <param name="executionName">The name to use for the execution.</param> /// <param name="executionJson">The JSON string to pass for execution.</param> /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the /// Step Functions state machine.</param> /// <returns>The Amazon Resource Name (ARN) of the AWS Step Functions /// execution.</returns> public async Task<string> StartExecutionAsync(string executionJson, string stateMachineArn) { var executionRequest = new StartExecutionRequest { Input = executionJson, StateMachineArn = stateMachineArn }; var response = await _amazonStepFunctions.StartExecutionAsync(executionRequest); return response.ExecutionArn; }
  • Per API i dettagli, vedi StartExecutionin AWS SDK for .NET APIReference.