Lambda examples using Amazon SDK for .NET - Amazon SDK for .NET
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Lambda examples using Amazon SDK for .NET

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for .NET with Lambda.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Lambda.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

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}"); }); } }
  • For API details, see ListFunctions in Amazon SDK for .NET API Reference.

Actions

The following code example shows how to use CreateFunction.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }
  • For API details, see CreateFunction in Amazon SDK for .NET API Reference.

The following code example shows how to use DeleteFunction.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }
  • For API details, see DeleteFunction in Amazon SDK for .NET API Reference.

The following code example shows how to use GetFunction.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }
  • For API details, see GetFunction in Amazon SDK for .NET API Reference.

The following code example shows how to use Invoke.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }
  • For API details, see Invoke in Amazon SDK for .NET API Reference.

The following code example shows how to use ListFunctions.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }
  • For API details, see ListFunctions in Amazon SDK for .NET API Reference.

The following code example shows how to use UpdateFunctionCode.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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}."); }

The following code example shows how to use UpdateFunctionConfiguration.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <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; }

Scenarios

The following code example shows how to:

  • Create an IAM role and Lambda function, then upload handler code.

  • Invoke the function with a single parameter and get results.

  • Update the function code and configure with an environment variable.

  • Invoke the function with new parameters and get results. Display the returned execution log.

  • List the functions for your account, then clean up resources.

For more information, see Create a Lambda function with the console.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create methods that perform Lambda actions.

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; } }

Create a function that runs the scenario.

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(); } }

Define a Lambda handler that increments a number.

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; } } }

Define a second Lambda handler that performs arithmetic operations.

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 examples

The following code example shows how to implement a Lambda function that receives an event triggered by receiving records from a Kinesis stream. The function retrieves the Kinesis payload, decodes from Base64, and logs the record contents.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming a Kinesis event with Lambda using .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; } }

The following code example shows how to implement a Lambda function that receives an event triggered by receiving records from a DynamoDB stream. The function retrieves the DynamoDB payload and logs the record contents.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming a DynamoDB event with Lambda using .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."); } }

The following code example shows how to implement a Lambda function that receives an event triggered by uploading an object to an S3 bucket. The function retrieves the S3 bucket name and object key from the event parameter and calls the Amazon S3 API to retrieve and log the content type of the object.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an S3 event with Lambda using .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; } } } }

The following code example shows how to implement a Lambda function that receives an event triggered by receiving messages from an SNS topic. The function retrieves the messages from the event parameter and logs the content of each message.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an SNS event with Lambda using .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; } } }

The following code example shows how to implement a Lambda function that receives an event triggered by receiving messages from an SQS queue. The function retrieves the messages from the event parameter and logs the content of each message.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an SQS event with Lambda using .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; } } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from a Kinesis stream. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting Kinesis batch item failures with Lambda using .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; } } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from a DynamoDB stream. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting DynamoDB batch item failures with Lambda using .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; } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from an SQS queue. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting SQS batch item failures with Lambda using .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; } }