AWS - Lambda Functions for dotnet developer (Part 1)
Tags: aws, lambda, csharp
Published: 2021-08-31 18:20:24

I this article be starting our journey in exploring AWS. On this episode we will explore and dig deep into AWS Lambda functions.

You can watch the full video on YouTube 
{% youtube EpEsjJzCakE %}

And you can find the source code on GitHub:
https://github.com/mohamadlawand087/v42-aws-lambda


So what we will cover today:  

- Serverless Cloud Computing
- Traditional Vs Serverless
- What are AWS Lambda?
- Why do we need it?
- Digging Deep
- How to build AWS Lambda
- Ingredients
- Code

As always please comment your questions, clarifications and suggestions in the comments down below. Please like, share and subscribe if you like the video. It will really help the channel

### Serverless Cloud Computing

Serverless computing hosts and runs code in the cloud. It is “serverless” in the sense that you do not need to install or maintain servers to run code. Which means No Infrastructure Headache. The infrastructure is already setup and its already configured for us to utilise

Serverless computing eliminates this infrastructure barrier for developers. It eliminates the complexity of managing a server. 

### Traditional Deployment vs Serverless Computing

When doing a traditional deployment we need to do the following steps

- Get the correct server and configure it
- Add all of the required configuation, install the dependencies and runtime
- Deploy our code
- Configure our code on the server
- Add  and configure security to our server

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fagum2mccsi87t3z92u.png)

But the work doesnt finish after deployment, the list of work that needs to be done after the deployment is as follow 

- Server Management
- Security Monitoring
- Keeping the Server Updated
- Resolve any configuration issues
- Requires some experience in handling the servers
- There are many different types of servers
- Difficult application scaling

The difference comes when we want to utilise Lambda functions for deployment:

- Create the Lambda Function on AWS and configure it
- Upload our code

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7h0nufnun2cm9ntaviu.png)

The work that needs to be done after Lambda Functions 

- No server management
- No server security worries
- Auto Scaling

### What is AWS Lambda

a serverless compute service which let us run code, without managing or provisioning any servers. Maintaining event integrations  and managing runtimes.

AWS lambda is amazon response the Microsoft Azure functions and to serverless compute services that allows us to run code with 0 administrations of the infrastructure require to run it.

Once we upload the code, AWS will automatically run the code and configure the services.

Lambda is a serverless compute service provided by AWS, when using serveless features we do not have to worry about managing infrastructure, scaling all of these are handled by AWS. All we have to do is provide the code.

### Why do we need it

- **No server to manage**: AWS Lambda automatically runs your code without requiring you to provision or manage infrastructure. Just write the code and upload it to Lambda either as a ZIP file or container image.
- **Continuous scaling**: AWS Lambda automatically scales your application by running code in response to each event. Your code runs in parallel and processes each trigger individually, scaling precisely with the size of the workload, from a few requests per day, to hundreds of thousands per second.
- **Cost optimized with millisecond metering**: With AWS Lambda, you only pay for the compute time you consume, so you’re never paying for over-provisioned infrastructure. You are charged for every millisecond your code executes and the number of times your code is triggered.
- **Consistent performance at any scale**: With AWS Lambda, you can optimize your code execution time by choosing the right memory size for your function. You can also keep your functions initialized and hyper-ready to respond within double digit milliseconds by enabling Provisioned Concurrency.
- Variety of programing languages: C# - Java - F# - node.js - PHP - Python
- **AWS Service integrations**: It can integrate with different AWS services so the potentials are limitless

### Invoking Lambda Functions

Lambda Functions is “event-driven.” This attribute refers to how the code being executed by Lambda Functions starts. A function will start via an event.  Invoking this event will be responsible for executing an Lambda function, and there are dozens of invocation to choose from. Examples of trigger events include:

- **HTTP Invoke**: Receiving an HTTP request, like interacting with an **[API](https://www.ibm.com/cloud/learn/api)** to retrieve the application’s information.
- **Amazon SQS Queue**: when ever there is a message on the queue the lambda funciton is invoked
- **AWS Lambda**: Lambda functions can invoke other lambda functions in a chain of invocations.

### AWS Lambda with other services

Lambda Functions is a service that consists of various services. When running, a function can connect to other AWS services. To do that, a function requires a **binding**.
A binding is code that “links” one AWS service to another and has a direction (in or out). That binding direction refers to how the “linked” AWS service sends or receives information from the function.

Examples of bindings include:

- **Dynamo Db**: a NoSQL db used for saving records to a table.
- **Kafka**: send data for operational monitoring data. This involves aggregating statistics from distributed applications to produce centralized feeds of operational data.
- Amazon SQS: send messages to Amazon SQS messaging service on cloud used to connect any applications, devices, and services running in the cloud to any other applications or services

### Ingredients

Prerequisit an 

- AWS account
- Homebrew (for Mac)
- Docker
- SAM CLI
- VS code
- VS code extension

### Dev Setup

1- We will start by installing We need to install homebrew on mac by visiting this link: [https://brew.sh](https://brew.sh/) and following the steps there.

2- Then we need to download configure docker, the reason we are doing that is the SAM cli might require some containers to be downloaded to utilise all of its features, so its better to install it from now.

3- Now we can focus SAM CLI for reference you can check the following link [https://aws.amazon.com/serverless/sam/](https://aws.amazon.com/serverless/sam/) in this link you will see how to install SAM on all different OS. We will follow the Mac steps

```bash
brew tap aws/tap
brew install aws-sam-cli
brew install awscli
```

4- download VS Code from [https://code.visualstudio.com](https://code.visualstudio.com/) and install it



### AWS CLI

- Open terminal
- Configure AWS with

```bash
aws configure
```

- Install Lambda functions templates for .Net ([https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html))

```bash
dotnet new -i Amazon.Lambda.Templates
```

- Create a lambda function from CLI

```bash
dotnet new lambda.EmptyFunction --name MyLambdaFunction
```

- Deploy function

```bash
dotnet tool install -g Amazon.Lambda.Tools
dotnet tool install --global Amazon.Lambda.TestTool-3.1

#dotnet lambda deploy-function MyLambdaFunction --function-role role
```

- Now let us run it and see the output

```bash
dotnet build
dotnet lambda-test-tool-3.1
```

### Coding time

After creating our application let us open it and update the code inside

```csharp
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(WeatherDto data, ILambdaContext context)
    {
        var output = $"The name is {data.CityName}"  ;
        return output?.ToUpper();
    }

    public class WeatherDto
    {
        public int CityName { get; set; }
    }
}
```

- Now let us run it and see the output

```bash
dotnet build
dotnet lambda-test-tool-3.1
```