Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: c# project with a c# lambda function handler #202

Merged
merged 2 commits into from
Dec 12, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
342 changes: 342 additions & 0 deletions csharp/capitalize-string/.gitignore
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="1.1.0" />
<PackageReference Include="Amazon.Lambda.Serialization.Json" Version="1.7.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -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
{

/// <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(string input, ILambdaContext context)
{
return input?.ToUpper();
}
}
}
Original file line number Diff line number Diff line change
@@ -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"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="1.1.0" />
<PackageReference Include="Amazon.Lambda.TestUtilities" Version="1.1.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\CapitalizeStringHandler\CapitalizeStringHandler.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
109 changes: 109 additions & 0 deletions csharp/capitalize-string/README.md
Original file line number Diff line number Diff line change
@@ -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 <function-name> --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 <cdk-project-folder> && cd <cdk-project-folder>
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 <handler-project-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 <handler-project-name>/src/<handler-project-name>
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 <cdk-project-folder>
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 <function-name> --payload "hello world"
```
3 changes: 3 additions & 0 deletions csharp/capitalize-string/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "dotnet run -p src/CapitalizeString/CapitalizeString.csproj"
}
34 changes: 34 additions & 0 deletions csharp/capitalize-string/src/CapitalizeString.sln
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<!-- CDK Construct Library dependencies -->
<PackageReference Include="Amazon.CDK" Version="1.18.0" />
<PackageReference Include="Amazon.CDK.AWS.Lambda" Version="1.18.0" />
<PackageReference Include="Amazon.Jsii.Analyzers" Version="*" PrivateAssets="all" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -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"
});
}
}
}
Original file line number Diff line number Diff line change
@@ -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")]
17 changes: 17 additions & 0 deletions csharp/capitalize-string/src/CapitalizeString/Program.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
}