Skip to content

Commit

Permalink
fix: revert compiled lang templates
Browse files Browse the repository at this point in the history
  • Loading branch information
heitorlessa committed Jan 7, 2019
1 parent 89f2e40 commit 8340bb5
Show file tree
Hide file tree
Showing 26 changed files with 567 additions and 442 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[[source]]

url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

cookiecutter = "*"
pytest-cookies = "*"
pytest = "*"
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
# Cookiecutter DotNet Core Hello-world for SAM based Serverless App
# Cookiecutter SAM for dotNet based Lambda functions

A cookiecutter template to create a DotNet Core Hello world boilerplate using [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model).
This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and dotnet 2.0.

It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly.

## Requirements

* [AWS SAM CLI](https://github.com/awslabs/aws-sam-cli)
Install `cookiecutter` command line:

**Pip users**:

* `pip install cookiecutter`

**Homebrew users**:

* `brew install cookiecutter`

**Windows or Pipenv users**:

* `pipenv install cookiecutter`

**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen.

## Usage

Generate a boilerplate template in your current project directory using the following syntax:
Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-dotnet`.

* **DotNet Core 2.1**: `sam init --runtime dotnetcore2.1`
* **DotNet Core 2.0**: `sam init --runtime dotnetcore2.0`
You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input.

> **NOTE**: ``--name`` allows you to specify a different project folder name (`sam-app` is the default)
**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS.


# Credits

* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter)


License
-------

This project is licensed under the terms of the [MIT License with no attribution](/LICENSE)
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Tests cookiecutter baking process and rendered content
"""


def test_project_tree(cookies):
result = cookies.bake(extra_context={
'project_name': 'hello sam'
})
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == 'hello sam'
assert result.project.isdir()
assert result.project.join('.gitignore').isfile()
assert result.project.join('template.yaml').isfile()
assert result.project.join('README.md').isfile()
assert result.project.join('src').isdir()
assert result.project.join('test').isdir()
assert result.project.join('src', 'HelloWorld').isdir()
assert result.project.join(
'src', 'HelloWorld', 'HelloWorld.csproj').isfile()
assert result.project.join('src', 'HelloWorld', 'Program.cs').isfile()
assert result.project.join(
'src', 'HelloWorld', 'aws-lambda-tools-defaults.json').isfile()
assert result.project.join(
'test', 'HelloWorld.Test', 'FunctionTest.cs').isfile()
assert result.project.join(
'test', 'HelloWorld.Test', 'HelloWorld.Tests.csproj').isfile()


def test_app_content(cookies):
result = cookies.bake(extra_context={'project_name': 'my_lambda'})
app_file = result.project.join('src', 'HelloWorld', 'Program.cs')
app_content = app_file.readlines()
app_content = ''.join(app_content)

contents = (
"GetCallingIP",
"GetStringAsync",
"location",
"message",
"hello world",
"StatusCode"
)

for content in contents:
assert content in app_content
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

This is a sample template for {{ cookiecutter.project_name }}


## Requirements

* AWS CLI already configured with Administrator permission
Expand Down Expand Up @@ -35,12 +34,6 @@ build.ps1 --target=Package

### Local development

**Invoking function locally using a local sample payload**

```bash
sam local invoke HelloWorldFunction --event event.json
```

**Invoking function locally through local API Gateway**

```bash
Expand All @@ -53,7 +46,7 @@ sam local start-api
...
Events:
HelloWorldFunction:
Type: Api # More info about API Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template.html#serverless-sam-template-api
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Expand Down Expand Up @@ -84,6 +77,7 @@ Next, run the following command to package our Lambda function to S3:

```bash
sam package \
--template-file template.yaml \
--output-template-file packaged.yaml \
--s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME
```
Expand All @@ -97,19 +91,26 @@ sam deploy \
--capabilities CAPABILITY_IAM
```

> **See [Serverless Application Model (SAM) HOWTO Guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html) for more details in how to get started.**
> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.**

After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL:

```bash
aws cloudformation describe-stacks \
--stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \
--query 'Stacks[].Outputs[?OutputKey==`HelloWorldApi`]' \
--output table
--query 'Stacks[].Outputs'
```

## Testing

For testing our code, we use XUnit and you can use `dotnet test` to run tests defined under `test/`

```bash
dotnet test test/HelloWorld.Test
```

Alternatively, you can use Cake. It discovers and executes all the tests.

### Linux & macOS

```bash
Expand All @@ -124,52 +125,48 @@ build.ps1 --target=Test

# Appendix

## Bringing to the next level

Here are a few things you can try to get more acquainted with building serverless applications using SAM:
## AWS CLI commands

### Create an additional API resource
AWS CLI commands to package, deploy and describe outputs defined within the AWS CloudFormation stack:

* Create a catch all resource (e.g. /hello/{proxy+}) and return the name requested through this new path
* Update tests
```bash
aws cloudformation package \
--template-file template.yaml \
--output-template-file packaged.yaml \
--s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME
### Step-through debugging
aws cloudformation deploy \
--template-file packaged.yaml \
--stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \
--capabilities CAPABILITY_IAM \
--parameter-overrides MyParameterSample=MySampleValue
* **[Enable step-through debugging docs for supported runtimes](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-debugging.html)**
aws cloudformation describe-stacks \
--stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs'
```

Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
## Next Steps

## SAM and AWS CLI commands
Create your own .NET Core solution template to use with SAM CLI. [Cookiecutter for AWS SAM and .NET](https://github.com/aws-samples/cookiecutter-aws-sam-dotnet) provides you with a sample implementation how to use cookiecutter templating library to standardise how you initialise your Serverless projects.

All commands used throughout this document
``` bash
sam init --location gh:aws-samples/cookiecutter-aws-sam-dotnet
```

```bash
# Invoke function locally with event.json as an input
sam local invoke HelloWorldFunction --event event.json
For more information and examples of how to use `sam init` run

# Run API Gateway locally
sam local start-api
``` bash
sam init --help
```

# Create S3 bucket
aws s3 mb s3://BUCKET_NAME
## Bringing to the next level

# Package Lambda function defined locally and upload to S3 as an artifact
sam package \
--output-template-file packaged.yaml \
--s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME
Here are a few ideas that you can use to get more acquainted as to how this overall process works:

# Deploy SAM template as a CloudFormation stack
sam deploy \
--template-file packaged.yaml \
--stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \
--capabilities CAPABILITY_IAM
* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path
* Update unit test to capture that
* Package & Deploy

# Describe Output section of CloudFormation stack previously created
aws cloudformation describe-stacks \
--stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \
--query 'Stacks[].Outputs[?OutputKey==`HelloWorldApi`]' \
--output table
Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications:

# Tail Lambda function Logs using Logical name defined in SAM Template
sam logs -n HelloWorldFunction --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --tail
```
* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/)

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

using Amazon.Lambda.Core;
Expand All @@ -16,12 +18,27 @@ namespace HelloWorld
public class Function
{

private static readonly HttpClient client = new HttpClient();

private static async Task<string> GetCallingIP()
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");

var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false);

var msg = await stringTask;
return msg.Replace("\n","");
}

public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
{

string location = GetCallingIP().Result;
Dictionary<string, string> body = new Dictionary<string, string>
{
{ "message", "hello world" }
{ "message", "hello world" },
{ "location", location },
};

return new APIGatewayProxyResponse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Globals:
Resources:

HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template.html#serverless-sam-template-function
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: ./artifacts/HelloWorld.zip
Handler: HelloWorld::HelloWorld.Function::FunctionHandler
Expand All @@ -21,18 +21,18 @@ Resources:
{%- elif cookiecutter.runtime == 'dotnetcore2.1' or cookiecutter.runtime == 'dotnet' %}
Runtime: dotnetcore2.1
{%- endif %}
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template.html#serverless-sam-template-api
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get

Outputs:

# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
Expand Down
Loading

0 comments on commit 8340bb5

Please sign in to comment.