DEV Community

yogini16
yogini16

Posted on

AWS Lambda and Azure Function

Azure Functions is a serverless, event-driven computing service provided by Microsoft Azure. This makes it easy to build and run small, single-purpose functions in the cloud.
An Azure Function is a serverless compute service that enables you to run small pieces of code (called "functions") without having to provision and manage infrastructure. Azure Functions allows you to build event-driven, scalable, and fault-tolerant applications using a variety of programming languages, including C#, F#, JavaScript, Java, and Python. It can be triggered by events from Azure services such as Azure Event Grid, Azure Event Hubs, and Azure Storage Queues, or it can be scheduled to run at specific intervals. Azure Functions can also be integrated with other Azure services, such as Azure Cosmos DB, Azure Event Hubs, and Azure Service Bus.

Here's an example of an Azure Function written in C# that takes a JSON payload as input and returns a response:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = data?.name;

    if (name == null)
    {
        return new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
    else
    {
        return new OkObjectResult($"Hello, {name}");
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the function is triggered by an HTTP request, and it uses the HttpRequest object to read the request body, which is expected to be in JSON format. The function then parses the JSON and retrieves the value of the "name" property. If the "name" property is not present, the function returns a "Bad Request" response. Otherwise, it returns an "OK" response with a message that includes the value of the "name" property.

You can find more examples of Azure function samples in different languages in the Azure documentation here

AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying infrastructure.

You can use Lambda to run your code in response to a variety of events, such as changes to data in an S3 bucket or a new line of data in a Kinesis stream. You can also use it to build custom logic for services such as Alexa Skills Kit and IoT, and to process streaming data using AWS Lambda and Kinesis Data Streams.

One of the main benefits of using Lambda is that it automatically scales your application based on incoming request traffic. It also eliminates the need for provisioning and managing servers, which can save you time and money.

AWS Lambda supports several programming languages including Node.js, Python, Java, C# and Go. You can use any of these languages to write your Lambda function code and use the AWS Lambda service to run and scale your code.

AWS Lambda also integrates with many other AWS services, such as S3, SNS, DynamoDB, and CloudWatch, allowing you to build powerful and highly available applications and services.

Below is an example of a simple AWS Lambda function written in C# that takes in a JSON input, parses it, and returns a string message:

using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Newtonsoft.Json;

// 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 HelloWorld
{
    public class Function
    {
        public async Task<string> FunctionHandler(Stream input, ILambdaContext context)
        {
            using (var reader = new StreamReader(input))
            {
                var json = await reader.ReadToEndAsync();
                var data = JsonConvert.DeserializeObject<InputData>(json);
                return $"Hello, {data.Name}!";
            }
        }

        public class InputData
        {
            public string Name { get; set; }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

This function can be triggered by various AWS services such as S3, SNS, Kinesis, CloudFormation, CloudWatch, and more.
To test this function you can use the TestLambdaContext class which is included in the AWSSDK.Lambda.TestUtilities package. This will allow you to test your function locally before deploying it to AWS.

using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.Json;
using Amazon.Lambda.TestUtilities;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace HelloWorld.Tests
{
    public class FunctionTest
    {
        [Fact]
        public async Task TestFunction()
        {
            var function = new Function();
            var context = new TestLambdaContext();

            var input = new MemoryStream();
            var inputData = new Function.InputData { Name = "John" };
            var inputJson = JsonConvert.SerializeObject(inputData);

            var inputWriter = new StreamWriter(input);
            inputWriter.Write(inputJson);
            inputWriter.Flush();
            input.Position = 0;

            var output = await function.FunctionHandler(input, context);

            Assert.Equal("Hello, John!", output);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

This code will execute the function and assert that the output is "Hello, John!" and it is expected output.

It is important to note that you will need to include the AWS SDK for .NET package in your project. You can do this by using the NuGet package manager.

Top comments (0)