Skip to content

Commit bb4aae9

Browse files
authored
Merge pull request #478 from awsdocs/csharp-handler-example
Add C# receipt handler example in example-csharp
2 parents 9474a9d + c5d6eb7 commit bb4aae9

File tree

6 files changed

+189
-0
lines changed

6 files changed

+189
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net8.0</TargetFramework>
4+
<ImplicitUsings>enable</ImplicitUsings>
5+
<Nullable>enable</Nullable>
6+
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
7+
<AWSProjectType>Lambda</AWSProjectType>
8+
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
9+
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
10+
<!-- Generate ready to run images during publishing to improve cold start time. -->
11+
<PublishReadyToRun>true</PublishReadyToRun>
12+
</PropertyGroup>
13+
<ItemGroup>
14+
<PackageReference Include="Amazon.Lambda.Core" Version="2.5.0" />
15+
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.4" />
16+
<PackageReference Include="AWSSDK.S3" Version="3.7.415.5" />
17+
</ItemGroup>
18+
</Project>
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
using System;
2+
using System.Text;
3+
using System.Threading.Tasks;
4+
using Amazon.Lambda.Core;
5+
using Amazon.S3;
6+
using Amazon.S3.Model;
7+
8+
// Assembly attribute to enable Lambda function logging
9+
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
10+
11+
namespace ExampleLambda;
12+
13+
public class Order
14+
{
15+
public string OrderId { get; set; } = string.Empty;
16+
public double Amount { get; set; }
17+
public string Item { get; set; } = string.Empty;
18+
}
19+
20+
public class OrderHandler
21+
{
22+
private static readonly AmazonS3Client s3Client = new();
23+
24+
public async Task<string> HandleRequest(Order order, ILambdaContext context)
25+
{
26+
try
27+
{
28+
string? bucketName = Environment.GetEnvironmentVariable("RECEIPT_BUCKET");
29+
if (string.IsNullOrWhiteSpace(bucketName))
30+
{
31+
throw new ArgumentException("RECEIPT_BUCKET environment variable is not set");
32+
}
33+
34+
string receiptContent = $"OrderID: {order.OrderId}\nAmount: ${order.Amount:F2}\nItem: {order.Item}";
35+
string key = $"receipts/{order.OrderId}.txt";
36+
37+
await UploadReceiptToS3(bucketName, key, receiptContent);
38+
39+
context.Logger.LogInformation($"Successfully processed order {order.OrderId} and stored receipt in S3 bucket {bucketName}");
40+
return "Success";
41+
}
42+
catch (Exception ex)
43+
{
44+
context.Logger.LogError($"Failed to process order: {ex.Message}");
45+
throw;
46+
}
47+
}
48+
49+
private async Task UploadReceiptToS3(string bucketName, string key, string receiptContent)
50+
{
51+
try
52+
{
53+
var putRequest = new PutObjectRequest
54+
{
55+
BucketName = bucketName,
56+
Key = key,
57+
ContentBody = receiptContent,
58+
ContentType = "text/plain"
59+
};
60+
61+
await s3Client.PutObjectAsync(putRequest);
62+
}
63+
catch (AmazonS3Exception ex)
64+
{
65+
throw new Exception($"Failed to upload receipt to S3: {ex.Message}", ex);
66+
}
67+
}
68+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# AWS Lambda Empty Function Project
2+
3+
This starter project consists of:
4+
* Function.cs - class file containing a class with a single function handler method
5+
* aws-lambda-tools-defaults.json - default argument settings for use with Visual Studio and command line deployment tools for AWS
6+
7+
You may also have a test project depending on the options selected.
8+
9+
The generated function handler is a simple method accepting a string argument that returns the uppercase equivalent of the input string. Replace the body of this method, and parameters, to suit your needs.
10+
11+
## Here are some steps to follow from Visual Studio:
12+
13+
To deploy your function to AWS Lambda, right click the project in Solution Explorer and select *Publish to AWS Lambda*.
14+
15+
To view your deployed function open its Function View window by double-clicking the function name shown beneath the AWS Lambda node in the AWS Explorer tree.
16+
17+
To perform testing against your deployed function use the Test Invoke tab in the opened Function View window.
18+
19+
To configure event sources for your deployed function, for example to have your function invoked when an object is created in an Amazon S3 bucket, use the Event Sources tab in the opened Function View window.
20+
21+
To update the runtime configuration of your deployed function use the Configuration tab in the opened Function View window.
22+
23+
To view execution logs of invocations of your function use the Logs tab in the opened Function View window.
24+
25+
## Here are some steps to follow to get started from the command line:
26+
27+
Once you have edited your template and code you can deploy your application using the [Amazon.Lambda.Tools Global Tool](https://github.com/aws/aws-extensions-for-dotnet-cli#aws-lambda-amazonlambdatools) from the command line.
28+
29+
Install Amazon.Lambda.Tools Global Tools if not already installed.
30+
```
31+
dotnet tool install -g Amazon.Lambda.Tools
32+
```
33+
34+
If already installed check if new version is available.
35+
```
36+
dotnet tool update -g Amazon.Lambda.Tools
37+
```
38+
39+
Execute unit tests
40+
```
41+
cd "ExampleCS/test/ExampleCS.Tests"
42+
dotnet test
43+
```
44+
45+
Deploy function to AWS Lambda
46+
```
47+
cd "ExampleCS/src/ExampleCS"
48+
dotnet lambda deploy-function
49+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"Information": [
3+
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
4+
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
5+
"dotnet lambda help",
6+
"All the command line options for the Lambda command can be specified in this file."
7+
],
8+
"profile": "default",
9+
"region": "us-east-1",
10+
"configuration": "Release",
11+
"function-architecture": "x86_64",
12+
"function-runtime": "dotnet8",
13+
"function-memory-size": 512,
14+
"function-timeout": 30,
15+
"function-handler": "ExampleCS::ExampleLambda.OrderHandler::HandleRequest"
16+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net8.0</TargetFramework>
4+
<ImplicitUsings>enable</ImplicitUsings>
5+
<Nullable>enable</Nullable>
6+
<IsTestProject>true</IsTestProject>
7+
</PropertyGroup>
8+
<ItemGroup>
9+
<PackageReference Include="Amazon.Lambda.Core" Version="2.5.0" />
10+
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" />
11+
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
12+
<PackageReference Include="xunit" Version="2.9.2" />
13+
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
14+
</ItemGroup>
15+
<ItemGroup>
16+
<ProjectReference Include="..\..\src\ExampleCS\ExampleCS.csproj" />
17+
</ItemGroup>
18+
</Project>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using Xunit;
2+
using Amazon.Lambda.Core;
3+
using Amazon.Lambda.TestUtilities;
4+
5+
namespace ExampleCS.Tests;
6+
7+
public class FunctionTest
8+
{
9+
[Fact]
10+
public void TestToUpperFunction()
11+
{
12+
13+
// Invoke the lambda function and confirm the string was upper cased.
14+
var function = new Function();
15+
var context = new TestLambdaContext();
16+
var upperCase = function.FunctionHandler("hello world", context);
17+
18+
Assert.Equal("HELLO WORLD", upperCase);
19+
}
20+
}

0 commit comments

Comments
 (0)