Click here to Skip to main content
13,143,614 members (30,974 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

12.6K views
7 bookmarked
Posted 24 Feb 2017

write serverless functions using aws lambda and c#

, 25 Feb 2017
Rate this:
Please Sign up or sign in to vote.
write serverless functions using aws lambda and c#

What is Serverless Framework?

Serverless Framework refers to building stateless function that does not have dependency on base operating system 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 as per 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 reduce operational cost, deployment complexity, Use benefits of Auto Scaling, 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 good choice for state less 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 Run time. 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.

{
  "title": "Title",
  "description": "Description",
  "version": "1.0.0-*",
  "buildOptions": {},
  "dependencies": {"Microsoft.NETCore.App": {"type": "platform","version": "1.0.0"},
    "Microsoft.Extensions.Configuration.Json": "1.1.0",
    "Amazon.Lambda.Core": "1.0.0*",
    "Amazon.Lambda.Serialization.Json": "1.0.1",
    "Amazon.Lambda.Tools": {"type": "build","version": "1.2.1-preview1"},
    "AWSSDK.DynamoDBv2": "3.3.2.1",
    "AWSSDK.Lambda": "3.3.2.6"
  },
  "tools": {"Amazon.Lambda.Tools": "1.2.1-preview1"},
  "frameworks": {"netcoreapp1.0": {"imports": "dnxcore50"}
  }

}

Observe 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

Step 4 - Write Logic in FunctionHandler (i.e. Entry point for Lambda Function)

 

In below example I am creating a registration table in DynamoDB if it does not exists. And then insert 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 maintained 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.GetEnviornmentVariablemethod. 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 letter on discovered Environment variables are accessible through System.Environment. GetEnviornmentVariable method

public Function()
{
   _accessKey = Environment.GetEnvironmentVariable("AccessKey");
   _secretKey = Environment.GetEnvironmentVariable("SecretKey");
   _serviceUrl = Environment.GetEnvironmentVariable("ServiceURL");
}

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

//Function Handler is an entry point to start execution of Lambda Function.
//It takes Input Data as First Parameter and ObjectContext as Second
public async Task FunctionHandler(Customer customer, ILambdaContext context)
{
   //Write Log to Cloud Watch using Console.WriteLline.  
    Console.WriteLine("Execution started for function -  {0} at {1}", 
                        context.FunctionName , DateTime.Now);

   // Create  dynamodb client
   var dynamoDbClient = new AmazonDynamoDBClient(
   new BasicAWSCredentials(_accessKey, _secretKey),
   new AmazonDynamoDBConfig { ServiceURL = _serviceUrl,
       RegionEndpoint  = RegionEndpoint.APSoutheast2});
            
   //Create Table if it Does Not Exists
   await CreateTable(dynamoDbClient,TableName);

   // Insert record in dynamodbtable
   LambdaLogger.Log("Insert record in the table");
   await dynamoDbClient.PutItemAsync(TableName, new Dictionary<string, AttributeValue>
   {
        { "Name", new AttributeValue(customer.Name) },
        { "EmailId", new AttributeValue(customer.EmailId) },
   });
   
    //Write Log to cloud watch using context.Logger.Log Method
    context.Logger.Log(string.Format("Finished execution for function -- {0} at {1}",
                       context.FunctionName,DateTime.Now ));
}

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 Second 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 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, 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vipul_Poojara
Architect
Australia Australia
Vipul is a senior .NET Developer with 14 years of experience in Requirement elicitation, Web Application Development, project execution using SCRUM methodology

Vipul is proficient in architecting and hands on with web applications development by applying various Design Patterns and SOLID principles using Microsoft Programming Languages and technology stack.
Over the years he has gained solid experience in building enterprise application with highest level of quality and customer satisfaction

You may also be interested in...

Pro
Pro

Comments and Discussions

 
PraiseMy Vote of 5 Pin
vighnu20-Jul-17 20:55
membervighnu20-Jul-17 20:55 
QuestionKinesis Stream Pin
marri.prasad20-Apr-17 20:30
membermarri.prasad20-Apr-17 20:30 
QuestionConsumers Pin
DumpsterJuice27-Feb-17 6:28
memberDumpsterJuice27-Feb-17 6:28 
AnswerRe: Consumers Pin
Vipul_Poojara27-Feb-17 19:08
memberVipul_Poojara27-Feb-17 19:08 
SuggestionSuggestion Pin
Afzaal Ahmad Zeeshan25-Feb-17 11:37
mvpAfzaal Ahmad Zeeshan25-Feb-17 11:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 26 Feb 2017
Article Copyright 2017 by Vipul_Poojara
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid