Lambda-Beispiele mit AWS SDK for .NET - AWS SDK-Codebeispiele

Weitere AWS SDK-Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Lambda-Beispiele mit AWS SDK for .NET

Die folgenden Codebeispiele zeigen Ihnen, wie Sie AWS SDK for .NET mit Lambda Aktionen ausführen und allgemeine Szenarien implementieren.

Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Während Aktionen Ihnen zeigen, wie Sie einzelne Servicefunktionen aufrufen, können Sie Aktionen im Kontext der zugehörigen Szenarien und serviceübergreifenden Beispiele sehen.

Szenarien sind Codebeispiele, die Ihnen zeigen, wie Sie eine bestimmte Aufgabe ausführen können, indem Sie mehrere Funktionen innerhalb desselben Services aufrufen.

Jedes Beispiel enthält einen Link zu GitHub, wo Sie Anweisungen zum Einrichten und Ausführen des Codes im Kontext finden.

Erste Schritte

Die folgenden Codebeispiele veranschaulichen, wie Sie mit der Verwendung von Lambda beginnen.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

namespace LambdaActions; using Amazon.Lambda; public class HelloLambda { static async Task Main(string[] args) { var lambdaClient = new AmazonLambdaClient(); Console.WriteLine("Hello AWS Lambda"); Console.WriteLine("Let's get started with AWS Lambda by listing your existing Lambda functions:"); var response = await lambdaClient.ListFunctionsAsync(); response.Functions.ForEach(function => { Console.WriteLine($"{function.FunctionName}\t{function.Description}"); }); } }
  • Einzelheiten zur API finden Sie ListFunctionsin der AWS SDK for .NET API-Referenz.

Aktionen

Das folgende Codebeispiel zeigt die VerwendungCreateFunction.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; }
  • Einzelheiten zur API finden Sie CreateFunctionin der AWS SDK for .NET API-Referenz.

Das folgende Codebeispiel zeigt die VerwendungDeleteFunction.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; }
  • Einzelheiten zur API finden Sie DeleteFunctionin der AWS SDK for .NET API-Referenz.

Das folgende Codebeispiel zeigt die VerwendungGetFunction.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; }
  • Einzelheiten zur API finden Sie GetFunctionin der AWS SDK for .NET API-Referenz.

Das folgende Codebeispiel zeigt die VerwendungInvoke.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; }
  • Weitere API-Informationen finden Sie unter Invoke in der AWS SDK for .NET -API-Referenz.

Das folgende Codebeispiel zeigt, wie man es benutztListFunctions.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; }
  • Einzelheiten zur API finden Sie ListFunctionsin der AWS SDK for .NET API-Referenz.

Das folgende Codebeispiel zeigt die VerwendungUpdateFunctionCode.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); }

Das folgende Codebeispiel zeigt die VerwendungUpdateFunctionConfiguration.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }

Szenarien

Wie das aussehen kann, sehen Sie am nachfolgenden Beispielcode:

  • Erstellen Sie eine IAM-Rolle und eine Lambda-Funktion und laden Sie den Handlercode hoch.

  • Rufen Sie die Funktion mit einem einzigen Parameter auf und erhalten Sie Ergebnisse.

  • Aktualisieren Sie den Funktionscode und konfigurieren Sie mit einer Umgebungsvariablen.

  • Rufen Sie die Funktion mit neuen Parametern auf und erhalten Sie Ergebnisse. Zeigt das zurückgegebene Ausführungsprotokoll an.

  • Listen Sie die Funktionen für Ihr Konto auf und bereinigen Sie dann die Ressourcen.

Weitere Informationen zur Verwendung von Lambda finden Sie unter Erstellen einer Lambda-Funktion mit der Konsole.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Erstellen Sie Methoden, die Lambda-Aktionen ausführen.

namespace LambdaActions; using Amazon.Lambda; using Amazon.Lambda.Model; /// <summary> /// A class that implements AWS Lambda methods. /// </summary> public class LambdaWrapper { private readonly IAmazonLambda _lambdaService; /// <summary> /// Constructor for the LambdaWrapper class. /// </summary> /// <param name="lambdaService">An initialized Lambda service client.</param> public LambdaWrapper(IAmazonLambda lambdaService) { _lambdaService = lambdaService; } /// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; } /// <summary> /// Delete an AWS Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// delete.</param> /// <returns>A Boolean value that indicates the success of the action.</returns> public async Task<bool> DeleteFunctionAsync(string functionName) { var request = new DeleteFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.DeleteFunctionAsync(request); // A return value of NoContent means that the request was processed. // In this case, the function was deleted, and the return value // is intentionally blank. return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent; } /// <summary> /// Gets information about a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function for /// which to retrieve information.</param> /// <returns>Async Task.</returns> public async Task<FunctionConfiguration> GetFunctionAsync(string functionName) { var functionRequest = new GetFunctionRequest { FunctionName = functionName, }; var response = await _lambdaService.GetFunctionAsync(functionRequest); return response.Configuration; } /// <summary> /// Invoke a Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to /// invoke.</param /// <param name="parameters">The parameter values that will be passed to the function.</param> /// <returns>A System Threading Task.</returns> public async Task<string> InvokeFunctionAsync( string functionName, string parameters) { var payload = parameters; var request = new InvokeRequest { FunctionName = functionName, Payload = payload, }; var response = await _lambdaService.InvokeAsync(request); MemoryStream stream = response.Payload; string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return returnValue; } /// <summary> /// Get a list of Lambda functions. /// </summary> /// <returns>A list of FunctionConfiguration objects.</returns> public async Task<List<FunctionConfiguration>> ListFunctionsAsync() { var functionList = new List<FunctionConfiguration>(); var functionPaginator = _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in functionPaginator.Functions) { functionList.Add(function); } return functionList; } /// <summary> /// Update an existing Lambda function. /// </summary> /// <param name="functionName">The name of the Lambda function to update.</param> /// <param name="bucketName">The bucket where the zip file containing /// the Lambda function code is stored.</param> /// <param name="key">The key name of the source code file.</param> /// <returns>Async Task.</returns> public async Task UpdateFunctionCodeAsync( string functionName, string bucketName, string key) { var functionCodeRequest = new UpdateFunctionCodeRequest { FunctionName = functionName, Publish = true, S3Bucket = bucketName, S3Key = key, }; var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest); Console.WriteLine($"The Function was last modified at {response.LastModified}."); } /// <summary> /// Update the code of a Lambda function. /// </summary> /// <param name="functionName">The name of the function to update.</param> /// <param name="functionHandler">The code that performs the function's actions.</param> /// <param name="environmentVariables">A dictionary of environment variables.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateFunctionConfigurationAsync( string functionName, string functionHandler, Dictionary<string, string> environmentVariables) { var request = new UpdateFunctionConfigurationRequest { Handler = functionHandler, FunctionName = functionName, Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables }, }; var response = await _lambdaService.UpdateFunctionConfigurationAsync(request); Console.WriteLine(response.LastModified); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } }

Erstellen Sie eine Funktion, die das Szenario ausführt.

global using System.Threading.Tasks; global using Amazon.IdentityManagement; global using Amazon.Lambda; global using LambdaActions; global using LambdaScenarioCommon; 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; using Amazon.Lambda.Model; using Microsoft.Extensions.Configuration; namespace LambdaBasics; public class LambdaBasics { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for the Amazon service. 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<IAmazonLambda>() .AddAWSService<IAmazonIdentityManagementService>() .AddTransient<LambdaWrapper>() .AddTransient<LambdaRoleWrapper>() .AddTransient<UIWrapper>() ) .Build(); var 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(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<LambdaBasics>(); var lambdaWrapper = host.Services.GetRequiredService<LambdaWrapper>(); var lambdaRoleWrapper = host.Services.GetRequiredService<LambdaRoleWrapper>(); var uiWrapper = host.Services.GetRequiredService<UIWrapper>(); string functionName = configuration["FunctionName"]!; string roleName = configuration["RoleName"]!; string policyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [ " + " {" + " \"Effect\": \"Allow\"," + " \"Principal\": {" + " \"Service\": \"lambda.amazonaws.com\" " + " }," + " \"Action\": \"sts:AssumeRole\" " + " }" + "]" + "}"; var incrementHandler = configuration["IncrementHandler"]; var calculatorHandler = configuration["CalculatorHandler"]; var bucketName = configuration["BucketName"]; var incrementKey = configuration["IncrementKey"]; var calculatorKey = configuration["CalculatorKey"]; var policyArn = configuration["PolicyArn"]; uiWrapper.DisplayLambdaBasicsOverview(); // Create the policy to use with the AWS Lambda functions and then attach the // policy to a new role. var roleArn = await lambdaRoleWrapper.CreateLambdaRoleAsync(roleName, policyDocument); Console.WriteLine("Waiting for role to become active."); uiWrapper.WaitABit(15, "Wait until the role is active before trying to use it."); // Attach the appropriate AWS Identity and Access Management (IAM) role policy to the new role. var success = await lambdaRoleWrapper.AttachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(10, "Allow time for the IAM policy to be attached to the role."); // Create the Lambda function using a zip file stored in an Amazon Simple Storage Service // (Amazon S3) bucket. uiWrapper.DisplayTitle("Create Lambda Function"); Console.WriteLine($"Creating the AWS Lambda function: {functionName}."); var lambdaArn = await lambdaWrapper.CreateLambdaFunctionAsync( functionName, bucketName, incrementKey, roleArn, incrementHandler); Console.WriteLine("Waiting for the new function to be available."); Console.WriteLine($"The AWS Lambda ARN is {lambdaArn}"); // Get the Lambda function. Console.WriteLine($"Getting the {functionName} AWS Lambda function."); FunctionConfiguration config; do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.State != State.Active); Console.WriteLine($"\nThe function, {functionName} has been created."); Console.WriteLine($"The runtime of this Lambda function is {config.Runtime}."); uiWrapper.PressEnter(); // List the Lambda functions. uiWrapper.DisplayTitle("Listing all Lambda functions."); var functions = await lambdaWrapper.ListFunctionsAsync(); DisplayFunctionList(functions); uiWrapper.DisplayTitle("Invoke increment function"); Console.WriteLine("Now that it has been created, invoke the Lambda increment function."); string? value; do { Console.Write("Enter a value to increment: "); value = Console.ReadLine(); } while (string.IsNullOrEmpty(value)); string functionParameters = "{" + "\"action\": \"increment\", " + "\"x\": \"" + value + "\"" + "}"; var answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"{value} + 1 = {answer}."); uiWrapper.DisplayTitle("Update function"); Console.WriteLine("Now update the Lambda function code."); await lambdaWrapper.UpdateFunctionCodeAsync(functionName, bucketName, calculatorKey); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); await lambdaWrapper.UpdateFunctionConfigurationAsync( functionName, calculatorHandler, new Dictionary<string, string> { { "LOG_LEVEL", "DEBUG" } }); do { config = await lambdaWrapper.GetFunctionAsync(functionName); Console.Write("."); } while (config.LastUpdateStatus == LastUpdateStatus.InProgress); uiWrapper.DisplayTitle("Call updated function"); Console.WriteLine("Now call the updated function..."); bool done = false; do { string? opSelected; Console.WriteLine("Select the operation to perform:"); Console.WriteLine("\t1. add"); Console.WriteLine("\t2. subtract"); Console.WriteLine("\t3. multiply"); Console.WriteLine("\t4. divide"); Console.WriteLine("\tOr enter \"q\" to quit."); Console.WriteLine("Enter the number (1, 2, 3, 4, or q) of the operation you want to perform: "); do { Console.Write("Your choice? "); opSelected = Console.ReadLine(); } while (opSelected == string.Empty); var operation = (opSelected) switch { "1" => "add", "2" => "subtract", "3" => "multiply", "4" => "divide", "q" => "quit", _ => "add", }; if (operation == "quit") { done = true; } else { // Get two numbers and an action from the user. value = string.Empty; do { Console.Write("Enter the first value: "); value = Console.ReadLine(); } while (value == string.Empty); string? value2; do { Console.Write("Enter a second value: "); value2 = Console.ReadLine(); } while (value2 == string.Empty); functionParameters = "{" + "\"action\": \"" + operation + "\", " + "\"x\": \"" + value + "\"," + "\"y\": \"" + value2 + "\"" + "}"; answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters); Console.WriteLine($"The answer when we {operation} the two numbers is: {answer}."); } uiWrapper.PressEnter(); } while (!done); // Delete the function created earlier. uiWrapper.DisplayTitle("Clean up resources"); // Detach the IAM policy from the IAM role. Console.WriteLine("First detach the IAM policy from the role."); success = await lambdaRoleWrapper.DetachLambdaRolePolicyAsync(policyArn, roleName); uiWrapper.WaitABit(15, "Let's wait for the policy to be fully detached from the role."); Console.WriteLine("Delete the AWS Lambda function."); success = await lambdaWrapper.DeleteFunctionAsync(functionName); if (success) { Console.WriteLine($"The {functionName} function was deleted."); } else { Console.WriteLine($"Could not remove the function {functionName}"); } // Now delete the IAM role created for use with the functions // created by the application. Console.WriteLine("Now we can delete the role that we created."); success = await lambdaRoleWrapper.DeleteLambdaRoleAsync(roleName); if (success) { Console.WriteLine("The role has been successfully removed."); } else { Console.WriteLine("Couldn't delete the role."); } Console.WriteLine("The Lambda Scenario is now complete."); uiWrapper.PressEnter(); // Displays a formatted list of existing functions returned by the // LambdaMethods.ListFunctions. void DisplayFunctionList(List<FunctionConfiguration> functions) { functions.ForEach(functionConfig => { Console.WriteLine($"{functionConfig.FunctionName}\t{functionConfig.Description}"); }); } } } namespace LambdaActions; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; public class LambdaRoleWrapper { private readonly IAmazonIdentityManagementService _lambdaRoleService; public LambdaRoleWrapper(IAmazonIdentityManagementService lambdaRoleService) { _lambdaRoleService = lambdaRoleService; } /// <summary> /// Attach an AWS Identity and Access Management (IAM) role policy to the /// IAM role to be assumed by the AWS Lambda functions created for the scenario. /// </summary> /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param> /// <param name="roleName">The name of the IAM role to attach the IAM policy to.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AttachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } /// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="policyDocument">The policy document for the new IAM role.</param> /// <returns>A string representing the ARN for newly created role.</returns> public async Task<string> CreateLambdaRoleAsync(string roleName, string policyDocument) { var request = new CreateRoleRequest { AssumeRolePolicyDocument = policyDocument, RoleName = roleName, }; var response = await _lambdaRoleService.CreateRoleAsync(request); return response.Role.Arn; } /// <summary> /// Deletes an IAM role. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <returns>A Boolean value indicating the success of the operation.</returns> public async Task<bool> DeleteLambdaRoleAsync(string roleName) { var request = new DeleteRoleRequest { RoleName = roleName, }; var response = await _lambdaRoleService.DeleteRoleAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } public async Task<bool> DetachLambdaRolePolicyAsync(string policyArn, string roleName) { var response = await _lambdaRoleService.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } } namespace LambdaScenarioCommon; public class UIWrapper { public readonly string SepBar = new('-', Console.WindowWidth); /// <summary> /// Show information about the AWS Lambda Basics scenario. /// </summary> public void DisplayLambdaBasicsOverview() { Console.Clear(); DisplayTitle("Welcome to AWS Lambda Basics"); Console.WriteLine("This example application does the following:"); Console.WriteLine("\t1. Creates an AWS Identity and Access Management (IAM) role that will be assumed by the functions we create."); Console.WriteLine("\t2. Attaches an IAM role policy that has Lambda permissions."); Console.WriteLine("\t3. Creates a Lambda function that increments the value passed to it."); Console.WriteLine("\t4. Calls the increment function and passes a value."); Console.WriteLine("\t5. Updates the code so that the function is a simple calculator."); Console.WriteLine("\t6. Calls the calculator function with the values entered."); Console.WriteLine("\t7. Deletes the Lambda function."); Console.WriteLine("\t7. Detaches the IAM role policy."); Console.WriteLine("\t8. Deletes the IAM role."); PressEnter(); } /// <summary> /// Display a message and wait until the user presses enter. /// </summary> public void PressEnter() { Console.Write("\nPress <Enter> to continue. "); _ = Console.ReadLine(); Console.WriteLine(); } /// <summary> /// Pad a string with spaces to center it on the console display. /// </summary> /// <param name="strToCenter">The string to be centered.</param> /// <returns>The padded string.</returns> public 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); } /// <summary> /// Display a countdown and wait for a number of seconds. /// </summary> /// <param name="numSeconds">The number of seconds to wait.</param> public void WaitABit(int numSeconds, string msg) { Console.WriteLine(msg); // Wait for the requested number of seconds. for (int i = numSeconds; i > 0; i--) { System.Threading.Thread.Sleep(1000); Console.Write($"{i}..."); } PressEnter(); } }

Definieren Sie einen Lambda-Handler, der eine Zahl inkrementiert.

using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace LambdaIncrement; public class Function { /// <summary> /// A simple function increments the integer parameter. /// </summary> /// <param name="input">A JSON string containing an action, which must be /// "increment" and a string representing the value to increment.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the incremented value of the parameter.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { if (input["action"] == "increment") { int inputValue = Convert.ToInt32(input["x"]); return inputValue + 1; } else { return 0; } } }

Definieren Sie einen zweiten Lambda-Handler, der arithmetische Operationen ausführt.

using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace LambdaCalculator; public class Function { /// <summary> /// A simple function that takes two number in string format and performs /// the requested arithmetic function. /// </summary> /// <param name="input">JSON data containing an action, and x and y values. /// Valid actions include: add, subtract, multiply, and divide.</param> /// <param name="context">The context object passed by Lambda containing /// information about invocation, function, and execution environment.</param> /// <returns>A string representing the results of the calculation.</returns> public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context) { var action = input["action"]; int x = Convert.ToInt32(input["x"]); int y = Convert.ToInt32(input["y"]); int result; switch (action) { case "add": result = x + y; break; case "subtract": result = x - y; break; case "multiply": result = x * y; break; case "divide": if (y == 0) { Console.Error.WriteLine("Divide by zero error."); result = 0; } else result = x / y; break; default: Console.Error.WriteLine($"{action} is not a valid operation."); result = 0; break; } return result; } }

Serverless-Beispiele

Das folgende Codebeispiel zeigt, wie eine Lambda-Funktion implementiert wird, die ein Ereignis empfängt, das durch den Empfang von Datensätzen aus einem Kinesis-Stream ausgelöst wird. Die Funktion ruft die Kinesis-Nutzlast ab, dekodiert von Base64 und protokolliert den Datensatzinhalt.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Nutzen eines Kinesis-Ereignisses mit Lambda unter Verwendung von .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace KinesisIntegrationSampleCode; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return; } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); throw; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } }

Das folgende Codebeispiel zeigt, wie eine Lambda-Funktion implementiert wird, die ein Ereignis empfängt, das durch den Empfang von Datensätzen aus einem DynamoDB-Stream ausgelöst wird. Die Funktion ruft die DynamoDB-Nutzlast ab und protokolliert den Inhalt des Datensatzes.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Verwenden eines DynamoDB-Ereignisses mit Lambda unter Verwendung von.NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace AWSLambda_DDB; public class Function { public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { context.Logger.LogInformation($"Event ID: {record.EventID}"); context.Logger.LogInformation($"Event Name: {record.EventName}"); context.Logger.LogInformation(JsonSerializer.Serialize(record)); } context.Logger.LogInformation("Stream processing complete."); } }

Das folgende Codebeispiel zeigt, wie eine Lambda-Funktion implementiert wird, die ein Ereignis empfängt, das durch das Hochladen eines Objekts in einen S3-Bucket ausgelöst wird. Die Funktion ruft den Namen des S3-Buckets sowie den Objektschlüssel aus dem Ereignisparameter ab und ruft die Amazon-S3-API auf, um den Inhaltstyp des Objekts abzurufen und zu protokollieren.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Nutzen eines S3-Ereignisses mit Lambda unter Verwendung von .NET

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for {bucket} and {key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning {objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - {e.Message}"); return string.Empty; } } } }

Das folgende Codebeispiel zeigt, wie eine Lambda-Funktion implementiert wird, die ein Ereignis empfängt, das durch den Empfang von Nachrichten von einem SNS-Thema ausgelöst wird. Die Funktion ruft die Nachrichten aus dem Ereignisparameter ab und protokolliert den Inhalt jeder Nachricht.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Nutzen eines SNS-Ereignisses mit Lambda unter Verwendung von .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace SnsIntegration; public class Function { public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach (var record in evnt.Records) { await ProcessRecordAsync(record, context); } context.Logger.LogInformation("done"); } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { try { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

Das folgende Codebeispiel zeigt, wie eine Lambda-Funktion implementiert wird, die ein Ereignis empfängt, das durch den Empfang von Nachrichten aus einer SQS-Warteschlange ausgelöst wird. Die Funktion ruft die Nachrichten aus dem Ereignisparameter ab und protokolliert den Inhalt jeder Nachricht.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Nutzen eines SQS-Ereignisses mit Lambda unter Verwendung von .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace SqsIntegrationSampleCode { public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach (var message in evnt.Records) { await ProcessMessageAsync(message, context); } context.Logger.LogInformation("done"); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { try { context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }

Das folgende Codebeispiel zeigt, wie eine partielle Batch-Antwort für Lambda-Funktionen implementiert wird, die Ereignisse aus einem Kinesis-Stream empfangen. Die Funktion meldet die Batch-Elementfehler in der Antwort und signalisiert Lambda, diese Nachrichten später erneut zu versuchen.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Melden von Fehlern bei Kinesis-Batchelementen mit Lambda unter Verwendung von .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text; using System.Text.Json.Serialization; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using AWS.Lambda.Powertools.Logging; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace KinesisIntegration; public class Function { // Powertools Logger requires an environment variables against your function // POWERTOOLS_SERVICE_NAME [Logging(LogEvent = true)] public async Task<StreamsEventResponse> FunctionHandler(KinesisEvent evnt, ILambdaContext context) { if (evnt.Records.Count == 0) { Logger.LogInformation("Empty Kinesis Event received"); return new StreamsEventResponse(); } foreach (var record in evnt.Records) { try { Logger.LogInformation($"Processed Event with EventId: {record.EventId}"); string data = await GetRecordDataAsync(record.Kinesis, context); Logger.LogInformation($"Data: {data}"); // TODO: Do interesting work based on the new data } catch (Exception ex) { Logger.LogError($"An error occurred {ex.Message}"); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return new StreamsEventResponse { BatchItemFailures = new List<StreamsEventResponse.BatchItemFailure> { new StreamsEventResponse.BatchItemFailure { ItemIdentifier = record.Kinesis.SequenceNumber } } }; } } Logger.LogInformation($"Successfully processed {evnt.Records.Count} records."); return new StreamsEventResponse(); } private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context) { byte[] bytes = record.Data.ToArray(); string data = Encoding.UTF8.GetString(bytes); await Task.CompletedTask; //Placeholder for actual async work return data; } } public class StreamsEventResponse { [JsonPropertyName("batchItemFailures")] public IList<BatchItemFailure> BatchItemFailures { get; set; } public class BatchItemFailure { [JsonPropertyName("itemIdentifier")] public string ItemIdentifier { get; set; } } }

Das folgende Codebeispiel zeigt, wie eine partielle Batch-Antwort für Lambda-Funktionen implementiert wird, die Ereignisse aus einem DynamoDB-Stream empfangen. Die Funktion meldet die Batch-Elementfehler in der Antwort und signalisiert Lambda, diese Nachrichten später erneut zu versuchen.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Melden von DynamoDB-Batchelementfehlern mit Lambda mithilfe von.NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace AWSLambda_DDB; public class Function { public StreamsEventResponse FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new List<StreamsEventResponse.BatchItemFailure>(); StreamsEventResponse streamsEventResponse = new StreamsEventResponse(); foreach (var record in dynamoEvent.Records) { try { var sequenceNumber = record.Dynamodb.SequenceNumber; context.Logger.LogInformation(sequenceNumber); } catch (Exception ex) { context.Logger.LogError(ex.Message); batchItemFailures.Add(new StreamsEventResponse.BatchItemFailure() { ItemIdentifier = record.Dynamodb.SequenceNumber }); } } if (batchItemFailures.Count > 0) { streamsEventResponse.BatchItemFailures = batchItemFailures; } context.Logger.LogInformation("Stream processing complete."); return streamsEventResponse; } }

Das folgende Codebeispiel zeigt, wie eine partielle Batch-Antwort für Lambda-Funktionen implementiert wird, die Ereignisse aus einer SQS-Warteschlange empfangen. Die Funktion meldet die Batch-Elementfehler in der Antwort und signalisiert Lambda, diese Nachrichten später erneut zu versuchen.

AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu. GitHub Das vollständige Beispiel sowie eine Anleitung zum Einrichten und Ausführen finden Sie im Repository mit Serverless-Beispielen.

Melden von SQS-Batchelementfehlern mit Lambda unter Verwendung von .NET.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace sqsSample; public class Function { public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>(); foreach(var message in evnt.Records) { try { //process your message await ProcessMessageAsync(message, context); } catch (System.Exception) { //Add failed message identifier to the batchItemFailures list batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); } } return new SQSBatchResponse(batchItemFailures); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { if (String.IsNullOrEmpty(message.Body)) { throw new Exception("No Body in SQS Message."); } context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }