This chapter will explain you how to work with AWS Lambda function in C# in detail. Here, we are going to use visual studio to write and deploy the code to AWS Lambda. For any information and help regarding installation of Visual studio and adding AWS toolkit to Visual Studio, please refer to the Introduction chapter in this tutorial. Once you are done with installation of Visual Studio, please follow the steps given below. Refer to the respective screenshots for a better understanding −
Open your Visual Studio and follow the steps to create new project. Click on File -> New -> Project.
Now, the following screen is displayed wherein you select AWS Lambda for Visual C#. Select AWS Lambda Project (.NET Core).
You can change the name if required, will keep here the default name. Click OK to continue.
The next step will ask you to select a Blueprint.
Select Empty function for this example and click Finish. It will create a new project structure as shown below −
Now, select Function.cs which is the main file where the handler with event and context is created for AWS Lambda.
The display of the file Functions.cs is as follows −
You can use the command given below to serialize the input and output parameters to AWS Lambda function.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
The handler is displayed as follows −
public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); }
Various components of the above code are explained below −
FunctionHandler −This is the starting point of the C# AWS Lambda function.
String input − The parameters to the handler string input has all the event data such as S3 object, API gateway details etc.
ILambdaContext context − ILamdaContext is an interface which has context details. It has details like lambda function name, memory details, timeout details etc.
The Lambda handler can be invoked in sync and async way. If invoked in a sync way as shown above you can have the return type. If async than the return type has to be void.
Now, let us deploy the AWS Lambda C# and test the same. Right click the project and click Publish to AWS Lambda as shown below −
Fill up the Function Name and click on Next. The next screen displayed is the Advanced Function Details as shown −
Enter the Role Name, Memory and Timeout. detailsNote that here we have selected the existing role created and used memory as 128MB and timeout as 10seconds. Once done click Upload to publish to AWS Lambda console.
You can see the following screen once AWS Lambda function is uploaded. Click Invoke to execute the AWS Lambda function created. At present, it shows error as it needs some input as per the code written.
Now, let us enter some sample input and Invoke it again. Note that here we have entered some text in the input box and the same on clicking invoke is displayed in uppercase in the response section. The log output is displayed below −
Now, let us also check AWS console to see if the function is created as we have deployed the function from Visual Studio.
The Lambda function created above is aws lambda using csharp and the same is displayed in AWS console as shown in the screenshots given below −
Handler is start point for AWS to execute. The name of the handler should be defined as −
ASSEMBLY::TYPE::METHOD
The details of the signature are explained as below −
ASSEMBLY − This is the name of the .NET assembly for the application created. It is basically the name of the folder from where the project is created.
TYPE − This is the name of the handler. It is basically the namespace.classname.
METHOD − This is the name of the function handler.
The code for handler signature is as shown below −
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; 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.Json.JsonSerializer))] namespace AWSLambda3 { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } }
Note that here the assembly is AWSLamda3, Type is namespace.classname which is AWSLambda3.Function and Method is FunctionHandler. Thus, the handler signature is AWSLamda3::AWSLambda3.Function::FunctionHandler
Context Object gives useful information about the runtime in AWS environment. The properties available in the context object are as shown in the following table −
Sr.No | Properties & Description |
---|---|
1 | MemoryLimitInMB This will give details of the memory configured for AWS Lambda function |
2 | FunctionName Name of AWS Lambda function |
3 | FunctionVersion Version of AWS Lambda function |
4 | InvokedFunctionArn ARN used to invoke this function. |
5 | AwsRequestId AWS request id for the AWS function created |
6 | LogStreamName Cloudwatch log stream name |
7 | LogGroupName Cloudwatch group name |
8 | ClientContext Information about the client application and device when used with AWS mobile SDK |
9 | Identity Information about the amazon cogbnito identity when used with AWS mobile SDK |
10 | RemainingTime Remaining execution time till the function will be terminated |
11 | Logger The logger associated with the context |
In this section, let us test some of the above properties in AWS Lambda in C#. Observe the sample code given below −
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; 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.Json.JsonSerializer))] namespace AWSLambda6 { public class Function { /// <summary> /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public void FunctionHandler(ILambdaContext context) { LambdaLogger.Log("Function name: " + context.FunctionName+"\n"); context.Logger.Log("RemainingTime: " + context.RemainingTime+"\n"); LambdaLogger.Log("LogGroupName: " + context.LogGroupName+"\n"); } } }
The related output that you can observe when you invoke the above code in C# is as shown below −
The related output that you can observe when you invoke the above code in AWS Console is as shown below −
For logging, you can use two functions −
context.Logger.Log
LambdaLogger.Log
Observe the following example shown here −
public void FunctionHandler(ILambdaContext context) { LambdaLogger.Log("Function name: " + context.FunctionName+"\n"); context.Logger.Log("RemainingTime: " + context.RemainingTime+"\n"); LambdaLogger.Log("LogGroupName: " + context.LogGroupName+"\n"); }
The corresponding output fo the code given above is shown here −
You can get the logs from CloudWatch as shown below −
This section discusses about error handling in C#. For error handling,Exception class has to be extended as shown in the example shown below −
namespace example { public class AccountAlreadyExistsException : Exception { public AccountAlreadyExistsException(String message) : base(message) { } } } namespace example { public class Handler { public static void CreateAccount() { throw new AccountAlreadyExistsException("Error in AWS Lambda!"); } } }
The corresponding output for the code given above is as given below −
{ "errorType": "LambdaException", "errorMessage": "Error in AWS Lambda!" }