AWS Lambda â Function in C#

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 −
MemoryLimitInMB
This will give details of the memory configured for AWS Lambda function
FunctionName
Name of AWS Lambda function
FunctionVersion
Version of AWS Lambda function
InvokedFunctionArn
ARN used to invoke this function.
AwsRequestId
AWS request id for the AWS function created
LogStreamName
Cloudwatch log stream name
LogGroupName
Cloudwatch group name
ClientContext
Information about the client application and device when used with AWS mobile SDK 
Identity
Information about the amazon cogbnito identity when used with AWS mobile SDK 
RemainingTime
Remaining execution time till the function will be terminated 
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
context.Logger.Log
LambdaLogger.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!"
}


    35 Lectures 
     7.5 hours 

 Mr. Pradeep Kshetrapal

    30 Lectures 
     3.5 hours 

 Priyanka Choudhary

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    51 Lectures 
     6 hours 

 Manuj Aggarwal

    41 Lectures 
     5 hours 

 AR Shankar

    14 Lectures 
     1 hours 

 Zach Miller
 Print
 Add Notes
 Bookmark this page