Write Serverless Functions Using AWS Lambda And C#

What is Serverless Framework?

Serverless Framework refers to building a stateless function that does not have a dependency on base operating systems or hardware resources. It lets developer focus on building stateless functions without worrying about how to provision and scale resources

Serverless functions are stateless, event-driven, and executed in container. With Serverless functions, you are charged  per the "Pay As You Go" Model (PAYG), i.e., you don't have to pay for idle resources. You only pay for each request when code is executed.

When to use Serverless Framework

Serverless functions are useful in scenarios when you want to reduce operational cost, deployment complexity, use benefits of Auto Scaling, and quick time to Market.

For example,

  1. You want to build a micro service that will generate a Usage Report on Request.
  2. You want to trigger a back-end / computational operation on a specific event, such as records inserted in Dynamo DB Table.
  3. You want to quickly develop and deploy a file processing service.

Refer AWS Documentation for More scenarios

** While Serverless functions are a good choice for stateless functions, one should make a conscious decision considering various business, technical parameters, and limitations of Serverless framework. Not all applications can be developed using Serverless Framework.

AWS Lambda and Programming Language Options

One of the most popular options available today for building Serverless functions is AWS Lambda. AWS Lambda was introduced in 2014 with support for Node.Js, Java and Python Programming language.

Last year in December 2016, AWS announced support for developing lambda functions using C# programming language on .NET Core 1.0 Runtime. This allows .NET developers to leverage their C# skills for building Serverless functions.

I will walk you through a simple event registration function developed using AWS Lambda and C#. But before getting started, let's understand programming model concepts of AWS Lambda.

Function Handler

Function Handler is an entry point to start execution of the lambda function. It takes input data as first parameter and lambda context as second parameter. If you have long running computation task you can take advantage of Async lambda functions. Refer AWS Lambda Developer Guide for more details.

Context Object

Context object is passed as second parameter to handler. Context object provides useful information about AWS Lambda run time. This could be used within function to control the execution of AWS function.

Logging

A properly designed function should have appropriate logging mechanism. AWS Lambda writes all logs to Cloud Watch. which could be used for analysis / troubleshoot if required. There are three ways to write logs in AWS function.

  1. Using Console.write or Console.writeline method.
  2. Using Log method of the Amazon.Lambda.Core.LambdaLogger class
  3. Using Context.Logger.Log method.

Exceptions

In the event of an un-handled error, an exception is sent back in Payload and logged to CloudWatch. You can look through exceptions logged by function in cloud watch.

Let's get started

Step 1

Install AWS Toolkit for Visual Studio. You can find AWS toolkit for Visual Studio at https://aws.amazon.com/visualstudio/

Step 2

Create new AWS Lambda Project (.NET Core) and choose Empty Function Blue Print. it will create project and include FunctionHandler in Function.cs.




Step 3

Install AWSSDK.DynamoDBV2 and AWSSDK.Lambda using NuGet Pacakage Manager or by editing Project.JSON File. 
  1. {  
  2.   "title""Title",  
  3.   "description""Description",  
  4.   "version""1.0.0-*",  
  5.   "buildOptions": {},  
  6.   "dependencies": {"Microsoft.NETCore.App": {"type""platform","version""1.0.0"},  
  7.     "Microsoft.Extensions.Configuration.Json""1.1.0",  
  8.     "Amazon.Lambda.Core""1.0.0*",  
  9.     "Amazon.Lambda.Serialization.Json""1.0.1",  
  10.     "Amazon.Lambda.Tools": {"type""build","version""1.2.1-preview1"},  
  11.     "AWSSDK.DynamoDBv2""3.3.2.1",  
  12.     "AWSSDK.Lambda""3.3.2.6"  
  13.   },  
  14.   "tools": {"Amazon.Lambda.Tools""1.2.1-preview1"},  
  15.   "frameworks": {"netcoreapp1.0": {"imports""dnxcore50"}  
  16.   }  
  17.   
  18. }  
Observe the below Assembly attribute created by Empty Function Template. It is self explanatory from the comment. it is basically required to serialize Input / Output parameter of Lambda Function.
  1. // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.  
  2. [assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]  
Step 4 Write Logic in FunctionHandler (i.e. Entry point for Lambda Function)

In the below example, I am creating a registration table in DynamoDB if it does not exist already. And then, inserting record. Basically, on first request to lambda function, a table will be created before inserting record and on every subsequent request, records will be inserted in table (In real world scenario, you may already have a table).

In order to establish a connection with DynamoDB, you need to specify accessKey, secretKey, and service URL. While developing .NET applications, we all maintain connection strings and other configurable information in configuration files so that we don't have to change code and we can point same code to Dev, Staging or Production.

AWS Lambda has got concept of Environment Variables. You can set all your configurable values in Environment Variables at the time of deployment and then access those variables using System.Environment.GetEnviornmentVariable method. It took me a while to figure out how to pass configurable values to C# Lambda Function. Initially I thought lambdaContext will hold configuratin information but later on discovered Environment variables are accessible through System.Environment. GetEnviornmentVariable method 
  1. private readonly string _accessKey;  
  2.       private readonly string _secretKey;  
  3.       private readonly string _serviceUrl;  
  4.       private const string TableName = "Registration";  
  5.   
  6.        public Function()  
  7.        {  
  8.            _accessKey = Environment.GetEnvironmentVariable("AccessKey");  
  9.            _secretKey = Environment.GetEnvironmentVariable("SecretKey");  
  10.            _serviceUrl = Environment.GetEnvironmentVariable("ServiceURL");  
  11.        }   
Below code is the function handler that accepts Customer POCO Object (having Name and EmailId Members) as first parameter and Lambda Object Context as second parameter. Earlier, I explained different ways to log to cloud watch. I have used all three methods in below code 
  1. //Function Handler is an entry point to start execution of Lambda Function.  
  2. //It takes Input Data as First Parameter and ObjectContext as Second  
  3. public async Task FunctionHandler(Customer customer, ILambdaContext context)  
  4. {  
  5.     //Write Log to Cloud Watch using Console.WriteLline.    
  6.     Console.WriteLine("Execution started for function -  {0} at {1}",   
  7.                         context.FunctionName , DateTime.Now);  
  8.   
  9.     // Create  dynamodb client  
  10.     var dynamoDbClient = new AmazonDynamoDBClient(  
  11.         new BasicAWSCredentials(_accessKey, _secretKey),  
  12.         new AmazonDynamoDBConfig { ServiceURL = _serviceUrl,  
  13.             RegionEndpoint  = RegionEndpoint.APSoutheast2});  
  14.       
  15.     //Create Table if it Does Not Exists  
  16.     await CreateTable(dynamoDbClient,TableName);  
  17.   
  18.    // Insert record in dynamodbtable  
  19.     LambdaLogger.Log("Insert record in the table");  
  20.     await dynamoDbClient.PutItemAsync(TableName, new Dictionary<string, AttributeValue>  
  21.     {  
  22.         { "Name"new AttributeValue(customer.Name) },  
  23.         { "EmailId"new AttributeValue(customer.EmailId) },  
  24.      });  
  25.   
  26.     //Write Log to cloud watch using context.Logger.Log Method  
  27.     context.Logger.Log(string.Format("Finished execution for function -- {0} at {1}",  
  28.                        context.FunctionName,DateTime.Now ));  
  29. }  
  1. //Create Table if it does not exists  
  2.       private async Task CreateTable(IAmazonDynamoDB amazonDynamoDBclient,string tableName)  
  3.       {  
  4.           //Write Log to Cloud Watch using LambdaLogger.Log Method  
  5.           LambdaLogger.Log(string.Format("Creating {0} Table", tableName));  
  6.   
  7.           var tableCollection = await amazonDynamoDBclient.ListTablesAsync();  
  8.   
  9.           if (!tableCollection.TableNames.Contains(tableName))  
  10.               await amazonDynamoDBclient.CreateTableAsync(new CreateTableRequest  
  11.               {  
  12.                   TableName = tableName,  
  13.                   KeySchema = new List<KeySchemaElement> {  
  14.                       { new KeySchemaElement { AttributeName="Name",  KeyType= KeyType.HASH }},  
  15.                       new KeySchemaElement { AttributeName="EmailId",  KeyType= KeyType.RANGE }  
  16.                   },  
  17.                   AttributeDefinitions = new List<AttributeDefinition> {  
  18.                       new AttributeDefinition { AttributeName="Name", AttributeType="S" },  
  19.                       new AttributeDefinition { AttributeName ="EmailId",AttributeType="S"}  
  20.                },  
  21.                   ProvisionedThroughput = new ProvisionedThroughput  
  22.                   {  
  23.                       ReadCapacityUnits = 5,  
  24.                       WriteCapacityUnits = 5  
  25.                   },  
  26.               });  
  27.       }  

Step 4 Deploy code to AWS Lambda Service.

There are two different ways to deploy C# Lambda function. One using AWS toolkit for Visual Studio and the second one is, using AWS Console. For the purpose of this demo, we will use AWS Toolkit.

Right click on project in solution explorer and click on Publish to AWS Lambda.

Ensure that you have entered Assembly Name,Type Name and Method Name correctly, otherwise you will get LambdaException at run time.

Configure Execution Memory, Timeout, VPC, Role, and Environment Variables. You can also encrypt Environment variables using KMS Key. Ensure account profile has appropriate access permission.

 

Invoke function from function View window. It allows you to configure environment variable and check log output. You can also look at detailed log in cloud watch logs.



That's it. The first Serverless function is deployed.

Reference

http://docs.aws.amazon.com/lambda/latest/dg/lambda-dg.pdf

Complete Source Code

You can find complete source code on my GitHub