From ec93a352968ca77fc33c7a70cd1062cbfd5adc46 Mon Sep 17 00:00:00 2001 From: andonov77 Date: Thu, 12 Dec 2019 11:08:13 +0000 Subject: [PATCH] feat: c# project with a c# lambda function handler (#202) There is no clear guidance at the moment on how to use C# lambda function handler within a CDK project. Adding an example here for customers to discover or for us to direct them. aws/aws-cdk#5340 is a customer question on this. --- csharp/capitalize-string/.gitignore | 342 ++++++++++++++++++ .../CapitalizeStringHandler.csproj | 11 + .../src/CapitalizeStringHandler/Function.cs | 27 ++ .../aws-lambda-tools-defaults.json | 19 + .../CapitalizeStringHandler.Tests.csproj | 15 + .../FunctionTest.cs | 28 ++ csharp/capitalize-string/README.md | 109 ++++++ csharp/capitalize-string/cdk.json | 3 + .../src/CapitalizeString.sln | 34 ++ .../CapitalizeString/CapitalizeString.csproj | 15 + .../CapitalizeString/CapitalizeStringStack.cs | 18 + .../CapitalizeString/GlobalSuppressions.cs | 1 + .../src/CapitalizeString/Program.cs | 17 + 13 files changed, 639 insertions(+) create mode 100644 csharp/capitalize-string/.gitignore create mode 100644 csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/CapitalizeStringHandler.csproj create mode 100644 csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/Function.cs create mode 100644 csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/aws-lambda-tools-defaults.json create mode 100644 csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/CapitalizeStringHandler.Tests.csproj create mode 100644 csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/FunctionTest.cs create mode 100644 csharp/capitalize-string/README.md create mode 100644 csharp/capitalize-string/cdk.json create mode 100644 csharp/capitalize-string/src/CapitalizeString.sln create mode 100644 csharp/capitalize-string/src/CapitalizeString/CapitalizeString.csproj create mode 100644 csharp/capitalize-string/src/CapitalizeString/CapitalizeStringStack.cs create mode 100644 csharp/capitalize-string/src/CapitalizeString/GlobalSuppressions.cs create mode 100644 csharp/capitalize-string/src/CapitalizeString/Program.cs diff --git a/csharp/capitalize-string/.gitignore b/csharp/capitalize-string/.gitignore new file mode 100644 index 0000000..c04667e --- /dev/null +++ b/csharp/capitalize-string/.gitignore @@ -0,0 +1,342 @@ +# CDK asset staging directory +.cdk.staging +cdk.out + +# Created by https://www.gitignore.io/api/csharp + +### Csharp ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + + +# End of https://www.gitignore.io/api/csharp diff --git a/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/CapitalizeStringHandler.csproj b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/CapitalizeStringHandler.csproj new file mode 100644 index 0000000..a206d83 --- /dev/null +++ b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/CapitalizeStringHandler.csproj @@ -0,0 +1,11 @@ + + + netcoreapp2.1 + true + Lambda + + + + + + \ No newline at end of file diff --git a/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/Function.cs b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/Function.cs new file mode 100644 index 0000000..bb5093e --- /dev/null +++ b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/Function.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Amazon.Lambda.Core; + +// 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 CapitalizeStringHandler +{ + public class Function + { + + /// + /// A simple function that takes a string and does a ToUpper + /// + /// + /// + /// + public string FunctionHandler(string input, ILambdaContext context) + { + return input?.ToUpper(); + } + } +} diff --git a/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/aws-lambda-tools-defaults.json b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/aws-lambda-tools-defaults.json new file mode 100644 index 0000000..f584235 --- /dev/null +++ b/csharp/capitalize-string/CapitalizeStringHandler/src/CapitalizeStringHandler/aws-lambda-tools-defaults.json @@ -0,0 +1,19 @@ +{ + "Information" : [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "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.", + + "dotnet lambda help", + + "All the command line options for the Lambda command can be specified in this file." + ], + + "profile":"", + "region" : "", + "configuration" : "Release", + "framework" : "netcoreapp2.1", + "function-runtime":"dotnetcore2.1", + "function-memory-size" : 256, + "function-timeout" : 30, + "function-handler" : "CapitalizeStringHandler::CapitalizeStringHandler.Function::FunctionHandler" +} diff --git a/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/CapitalizeStringHandler.Tests.csproj b/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/CapitalizeStringHandler.Tests.csproj new file mode 100644 index 0000000..036f4ef --- /dev/null +++ b/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/CapitalizeStringHandler.Tests.csproj @@ -0,0 +1,15 @@ + + + netcoreapp2.1 + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/FunctionTest.cs b/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/FunctionTest.cs new file mode 100644 index 0000000..4528a8a --- /dev/null +++ b/csharp/capitalize-string/CapitalizeStringHandler/test/CapitalizeStringHandler.Tests/FunctionTest.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Xunit; +using Amazon.Lambda.Core; +using Amazon.Lambda.TestUtilities; + +using CapitalizeStringHandler; + +namespace CapitalizeStringHandler.Tests +{ + public class FunctionTest + { + [Fact] + public void TestToUpperFunction() + { + + // Invoke the lambda function and confirm the string was upper cased. + var function = new Function(); + var context = new TestLambdaContext(); + var upperCase = function.FunctionHandler("hello world", context); + + Assert.Equal("HELLO WORLD", upperCase); + } + } +} diff --git a/csharp/capitalize-string/README.md b/csharp/capitalize-string/README.md new file mode 100644 index 0000000..d3a885a --- /dev/null +++ b/csharp/capitalize-string/README.md @@ -0,0 +1,109 @@ +This package is an example on how to use AWS CDK to deploy a Lambda function handler. +Both the CDK app and the Lambda handler are written in C# and built using the `dotnet` CLI. + +# This project + +## Structure + +In this project, `Program.cs` is the main entry point of the CDK app and the CDK construct +for the lambda function is configured in `CapitalizeStringStack.cs`. + +The lambda function is another csharp project residing within the `CapitalizeStringHandler` +folder. + +## Build & Deploy + +Build - + +```shell +cd CapitalizeStringHandler/src/CapitalizeStringHandler +dotnet build +dotnet tool install -g Amazon.Lambda.Tools # if not already +dotnet lambda package +cd ../../../ +dotnet build src +``` + +Deploy & Test - + +```shell +cdk deploy +dotnet lambda invoke-function --payload "hello world" +``` + +# How to do this yourself? + +## Pre-requisites + +If you're unfamiliar with AWS Lambda functions in C#, read this first - +https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model.html + +## Steps + +1. Create the CDK app project folder - + + ```shell + mkdir && cd + cdk init -l=csharp + ``` + +2. Modify the `.csproj` file to include the latest versions of the following NuGet packages - + + ``` + Amazon.CDK + Amazon.CDK.AWS.Lambda + Amazon.Jsii.Analyzers + ``` + +3. Use the `dotnet` CLI to generate a c# project to manage the Lambda function handler - + + ```shell + dotnet new -i Amazon.Lambda.Templates + dotnet new lambda.EmptyFunction --name + ``` + + This should create a new folder with the same name as the project. + For more details, see https://docs.aws.amazon.com/lambda/latest/dg/lambda-dotnet-coreclr-deployment-package.html + +4. Look for the `.cs` file within the `src/` folder of the now created project folder. + This is the entry point for your lambda function code. Modify the code as you see fit. + +5. Now build and package the lambda function handler package - + + ```shell + cd /src/ + dotnet build + dotnet tool install -g Amazon.Lambda.Tools # if not already + dotnet lambda package + ``` + + This should have created a folder `bin/Release/netcoreapp2.1/publish/` which is the package + that needs to be deployed to AWS Lambda as the function code. + +6. In the CDK project, create an instance of `Function` class from the Lambda module. + + Specify the `Runtime` to be one of the `DOTNET_CORE` runtimes available and set the correct + handler value based on the name of your lambda function project, namespaces and class name. + + Specify an `Asset` against the `Code` property, pointing to the location of the Lambda project + on local disk. This must be the path to the `publish/` folder generated in the previous step, + i.e., the relative path of the `publish/` folder from the CDK project root. + + See `LambdaCdkCsharpStack.cs` file in this project to see how this is done. + See the lambda guide for more details - + https://docs.aws.amazon.com/lambda/latest/dg/dotnet-programming-model-handler-types.html#dotnet-programming-model-handler-signatures + +7. Build the CDK application and deploy - + + ```shell + cd + dotnet build src/ + cdk deploy + ``` + +8. Invoke the lambda function using the `dotnet` CLI. The payload specified below works for the + Lambda function configured in this project. Modify it per your lambda function. + + ```shell + dotnet lambda invoke-function --payload "hello world" + ``` diff --git a/csharp/capitalize-string/cdk.json b/csharp/capitalize-string/cdk.json new file mode 100644 index 0000000..8effe13 --- /dev/null +++ b/csharp/capitalize-string/cdk.json @@ -0,0 +1,3 @@ +{ + "app": "dotnet run -p src/CapitalizeString/CapitalizeString.csproj" +} diff --git a/csharp/capitalize-string/src/CapitalizeString.sln b/csharp/capitalize-string/src/CapitalizeString.sln new file mode 100644 index 0000000..0d3769b --- /dev/null +++ b/csharp/capitalize-string/src/CapitalizeString.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CapitalizeString", "CapitalizeString\CapitalizeString.csproj", "{B30C7A56-671A-4689-960A-001C7B1380B2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|x64.ActiveCfg = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|x64.Build.0 = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|x86.ActiveCfg = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Debug|x86.Build.0 = Debug|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|Any CPU.Build.0 = Release|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|x64.ActiveCfg = Release|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|x64.Build.0 = Release|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|x86.ActiveCfg = Release|Any CPU + {B30C7A56-671A-4689-960A-001C7B1380B2}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/csharp/capitalize-string/src/CapitalizeString/CapitalizeString.csproj b/csharp/capitalize-string/src/CapitalizeString/CapitalizeString.csproj new file mode 100644 index 0000000..e012b21 --- /dev/null +++ b/csharp/capitalize-string/src/CapitalizeString/CapitalizeString.csproj @@ -0,0 +1,15 @@ + + + + Exe + netcoreapp3.0 + + + + + + + + + + diff --git a/csharp/capitalize-string/src/CapitalizeString/CapitalizeStringStack.cs b/csharp/capitalize-string/src/CapitalizeString/CapitalizeStringStack.cs new file mode 100644 index 0000000..be88b4e --- /dev/null +++ b/csharp/capitalize-string/src/CapitalizeString/CapitalizeStringStack.cs @@ -0,0 +1,18 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; + +namespace CapitalizeString +{ + public class CapitalizeStringStack : Stack + { + internal CapitalizeStringStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + Function fn = new Function(this, "capitalizestring", new FunctionProps + { + Runtime = Runtime.DOTNET_CORE_2_1, + Code = Code.FromAsset("./CapitalizeStringHandler/src/CapitalizeStringHandler/bin/Release/netcoreapp2.1/publish"), + Handler = "CapitalizeStringHandler::CapitalizeStringHandler.Function::FunctionHandler" + }); + } + } +} diff --git a/csharp/capitalize-string/src/CapitalizeString/GlobalSuppressions.cs b/csharp/capitalize-string/src/CapitalizeString/GlobalSuppressions.cs new file mode 100644 index 0000000..26233fc --- /dev/null +++ b/csharp/capitalize-string/src/CapitalizeString/GlobalSuppressions.cs @@ -0,0 +1 @@ +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")] diff --git a/csharp/capitalize-string/src/CapitalizeString/Program.cs b/csharp/capitalize-string/src/CapitalizeString/Program.cs new file mode 100644 index 0000000..96e71f1 --- /dev/null +++ b/csharp/capitalize-string/src/CapitalizeString/Program.cs @@ -0,0 +1,17 @@ +using Amazon.CDK; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CapitalizeString +{ + sealed class Program + { + public static void Main(string[] args) + { + var app = new App(); + new CapitalizeStringStack(app, "CapitalizeStringStack"); + app.Synth(); + } + } +}