repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1 { /// <summary> /// This class contains the results of validating the current state of all slot values. This is used to send information /// back to the user to fix bad slot values. /// </summary> public class ValidationResult { public static readonly ValidationResult VALID_RESULT = new ValidationResult(true, null, null); public ValidationResult(bool isValid, string violationSlot, string message) { this.IsValid = isValid; this.ViolationSlot = violationSlot; if (!string.IsNullOrEmpty(message)) { this.Message = new LexResponse.LexMessage { ContentType = "PlainText", Content = message }; } } /// <summary> /// If the slot values are currently correct. /// </summary> public bool IsValid { get; } /// <summary> /// Which slot value is invalid so the user can correct the value. /// </summary> public string ViolationSlot { get; } /// <summary> /// The message explaining to the user what is wrong with the slot value. /// </summary> public LexResponse.LexMessage Message { get; } } }
44
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.LexEvents; using Newtonsoft.Json; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public void StartBookACarEventTest() { var json = File.ReadAllText("start-book-a-car-event.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Delegate", response.DialogAction.Type); } [Fact] public void DriverAgeTooYoungEventTest() { var json = File.ReadAllText("driver-age-too-young.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("ElicitSlot", response.DialogAction.Type); Assert.Equal("DriverAge", response.DialogAction.SlotToElicit); Assert.Equal("PlainText", response.DialogAction.Message.ContentType); Assert.Equal("Your driver must be at least eighteen to rent a car. Can you provide the age of a different driver?", response.DialogAction.Message.Content); } [Fact] public void CommitBookACarEventTest() { var json = File.ReadAllText("commit-book-a-car.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Close", response.DialogAction.Type); Assert.Equal("Fulfilled", response.DialogAction.FulfillmentState); Assert.Equal("PlainText", response.DialogAction.Message.ContentType); Assert.Equal("Thanks, I have placed your reservation.", response.DialogAction.Message.Content); } } }
69
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.ApplicationLoadBalancerEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { /// <summary> /// Lambda function handler to respond to events coming from an Application Load Balancer. /// /// Note: If "Multi value headers" is disabled on the ELB Target Group then use the Headers and QueryStringParameters properties /// on the ApplicationLoadBalancerRequest and ApplicationLoadBalancerResponse objects. If "Multi value headers" is enabled then /// use MultiValueHeaders and MultiValueQueryStringParameters properties. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public ApplicationLoadBalancerResponse FunctionHandler(ApplicationLoadBalancerRequest request, ILambdaContext context) { var response = new ApplicationLoadBalancerResponse { StatusCode = 200, StatusDescription = "200 OK", IsBase64Encoded = false }; // If "Multi value headers" is enabled for the ELB Target Group then use the "response.MultiValueHeaders" property instead of "response.Headers". response.Headers = new Dictionary<string, string> { {"Content-Type", "text/html; charset=utf-8" } }; response.Body = @" <html> <head> <title>Hello World!</title> <style> html, body { margin: 0; padding: 0; font-family: arial; font-weight: 700; font-size: 3em; text-align: center; } </style> </head> <body> <p>Hello World from Lambda</p> </body> </html> "; return response; } } }
65
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.ApplicationLoadBalancerEvents; using Amazon.Lambda.TestUtilities; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public void TestSampleFunction() { var function = new Function(); var context = new TestLambdaContext(); var request = new ApplicationLoadBalancerRequest(); var response = function.FunctionHandler(request, context); Assert.Equal(200, response.StatusCode); Assert.Contains("Hello World from Lambda", response.Body); } } }
30
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; using Amazon.DynamoDBv2.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { context.Logger.LogLine($"Event ID: {record.EventID}"); context.Logger.LogLine($"Event Name: {record.EventName}"); // TODO: Add business logic processing the record.Dynamodb object. } context.Logger.LogLine("Stream processing complete."); } } }
31
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; using Amazon.Lambda.TestUtilities; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public void TestFunction() { DynamoDBEvent evnt = new DynamoDBEvent { Records = new List<DynamoDBEvent.DynamodbStreamRecord> { new DynamoDBEvent.DynamodbStreamRecord { AwsRegion = "us-west-2", Dynamodb = new StreamRecord { ApproximateCreationDateTime = DateTime.Now, Keys = new Dictionary<string, AttributeValue> { {"id", new AttributeValue { S = "MyId" } } }, NewImage = new Dictionary<string, AttributeValue> { { "field1", new AttributeValue { S = "NewValue" } }, { "field2", new AttributeValue { S = "AnotherNewValue" } } }, OldImage = new Dictionary<string, AttributeValue> { { "field1", new AttributeValue { S = "OldValue" } }, { "field2", new AttributeValue { S = "AnotherOldValue" } } }, StreamViewType = StreamViewType.NEW_AND_OLD_IMAGES } } } }; var context = new TestLambdaContext(); var function = new Function(); function.FunctionHandler(evnt, context); var testLogger = context.Logger as TestLambdaLogger; Assert.Contains("Stream processing complete", testLogger.Buffer.ToString()); } } }
54
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisFirehoseEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { public KinesisFirehoseResponse FunctionHandler(KinesisFirehoseEvent evnt, ILambdaContext context) { context.Logger.LogLine($"InvocationId: {evnt.InvocationId}"); context.Logger.LogLine($"DeliveryStreamArn: {evnt.DeliveryStreamArn}"); context.Logger.LogLine($"Region: {evnt.Region}"); var response = new KinesisFirehoseResponse { Records = new List<KinesisFirehoseResponse.FirehoseRecord>() }; foreach (var record in evnt.Records) { context.Logger.LogLine($"\tRecordId: {record.RecordId}"); context.Logger.LogLine($"\t\tApproximateArrivalEpoch: {record.ApproximateArrivalEpoch}"); context.Logger.LogLine($"\t\tApproximateArrivalTimestamp: {record.ApproximateArrivalTimestamp}"); context.Logger.LogLine($"\t\tData: {record.DecodeData()}"); // Transform data: For example ToUpper the data var transformedRecord = new KinesisFirehoseResponse.FirehoseRecord { RecordId = record.RecordId, Result = KinesisFirehoseResponse.TRANSFORMED_STATE_OK }; transformedRecord.EncodeData(record.DecodeData().ToUpperInvariant()); response.Records.Add(transformedRecord); } return response; } } }
49
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisFirehoseEvents; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public void TestKinesisFirehoseEvent() { var json = File.ReadAllText("sample-event.json"); var kinesisEvent = JsonConvert.DeserializeObject<KinesisFirehoseEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var kinesisResponse = function.FunctionHandler(kinesisEvent, context); Assert.Equal(1, kinesisResponse.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisResponse.Records[0].RecordId); Assert.Equal(KinesisFirehoseResponse.TRANSFORMED_STATE_OK, kinesisResponse.Records[0].Result); Assert.Equal("SEVMTE8gV09STEQ=", kinesisResponse.Records[0].Base64EncodedData); } } }
42
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { public void FunctionHandler(KinesisEvent kinesisEvent, ILambdaContext context) { context.Logger.LogLine($"Beginning to process {kinesisEvent.Records.Count} records..."); foreach (var record in kinesisEvent.Records) { context.Logger.LogLine($"Event ID: {record.EventId}"); context.Logger.LogLine($"Event Name: {record.EventName}"); string recordData = GetRecordContents(record.Kinesis); context.Logger.LogLine($"Record Data:"); context.Logger.LogLine(recordData); } context.Logger.LogLine("Stream processing complete."); } private string GetRecordContents(KinesisEvent.Record streamRecord) { using (var reader = new StreamReader(streamRecord.Data, Encoding.ASCII)) { return reader.ReadToEnd(); } } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using Amazon.Lambda.TestUtilities; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public void TestFunction() { KinesisEvent evnt = new KinesisEvent { Records = new List<KinesisEvent.KinesisEventRecord> { new KinesisEvent.KinesisEventRecord { AwsRegion = "us-west-2", Kinesis = new KinesisEvent.Record { ApproximateArrivalTimestamp = DateTime.Now, Data = new MemoryStream(Encoding.UTF8.GetBytes("Hello World Kinesis Record")) } } } }; var context = new TestLambdaContext(); var function = new Function(); function.FunctionHandler(evnt, context); var testLogger = context.Logger as TestLambdaLogger; Assert.Contains("Stream processing complete", testLogger.Buffer.ToString()); } } }
52
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using Amazon.S3.Util; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { IAmazonS3 S3Client { get; set; } /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { S3Client = new AmazonS3Client(); } /// <summary> /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment. /// </summary> /// <param name="s3Client"></param> public Function(IAmazonS3 s3Client) { this.S3Client = s3Client; } /// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context) { var s3Event = evnt.Records?[0].S3; if(s3Event == null) { return null; } try { var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key); return response.Headers.ContentType; } catch(Exception e) { context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogLine(e.Message); context.Logger.LogLine(e.StackTrace); throw; } } } }
69
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.S3Events; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public async Task TestS3EventLambdaFunction() { IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USWest2); var bucketName = "lambda-BlueprintBaseName.1-".ToLower() + DateTime.Now.Ticks; var key = "text.txt"; // Create a bucket an object to setup a test data. await s3Client.PutBucketAsync(bucketName); try { await s3Client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "sample data" }); // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = bucketName }, Object = new S3Event.S3ObjectEntity {Key = key } } } } }; // Invoke the lambda function and confirm the content type was returned. var function = new Function(s3Client); var contentType = await function.FunctionHandler(s3Event, null); Assert.Equal("text/plain", contentType); } finally { // Clean up the test data await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } } }
73
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using Amazon.S3.Util; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { IAmazonS3 S3Client { get; set; } /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { S3Client = new AmazonS3Client(); } /// <summary> /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment. /// </summary> /// <param name="s3Client"></param> public Function(IAmazonS3 s3Client) { this.S3Client = s3Client; } /// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context) { var s3Event = evnt.Records?[0].S3; if(s3Event == null) { return null; } try { var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key); return response.Headers.ContentType; } catch(Exception e) { context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogLine(e.Message); context.Logger.LogLine(e.StackTrace); throw; } } } }
69
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.S3Events; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public async Task TestS3EventLambdaFunction() { IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USWest2); var bucketName = "lambda-BlueprintBaseName.1-".ToLower() + DateTime.Now.Ticks; var key = "text.txt"; // Create a bucket an object to setup a test data. await s3Client.PutBucketAsync(bucketName); try { await s3Client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "sample data" }); // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = bucketName }, Object = new S3Event.S3ObjectEntity {Key = key } } } } }; // Invoke the lambda function and confirm the content type was returned. var function = new Function(s3Client); var contentType = await function.FunctionHandler(s3Event, null); Assert.Equal("text/plain", contentType); } finally { // Clean up the test data await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } } }
73
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SNS event object and can be used /// to respond to SNS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach(var record in evnt.Records) { await ProcessRecordAsync(record, context); } } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { context.Logger.LogLine($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } } }
52
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SNSEvents; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var snsEvent = new SNSEvent { Records = new List<SNSEvent.SNSRecord> { new SNSEvent.SNSRecord { Sns = new SNSEvent.SNSMessage() { Message = "foobar" } } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(snsEvent, context); Assert.Contains("Processed record foobar", logger.Buffer.ToString()); } } }
46
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used /// to respond to SQS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach(var message in evnt.Records) { await ProcessMessageAsync(message, context); } } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { context.Logger.LogLine($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } } }
52
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SQSEvents; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var sqsEvent = new SQSEvent { Records = new List<SQSEvent.SQSMessage> { new SQSEvent.SQSMessage { Body = "foobar" } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(sqsEvent, context); Assert.Contains("Processed message foobar", logger.Buffer.ToString()); } } }
43
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace BlueprintBaseName._1 { /// <summary> /// The state passed between the step function executions. /// </summary> public class State { /// <summary> /// Input value when starting the execution /// </summary> public string Name { get; set; } /// <summary> /// The message built through the step function execution. /// </summary> public string Message { get; set; } /// <summary> /// The number of seconds to wait between calling the Salutations task and Greeting task. /// </summary> public int WaitInSeconds { get; set; } } }
28
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; 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.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class StepFunctionTasks { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public StepFunctionTasks() { } public State Greeting(State state, ILambdaContext context) { state.Message = "Hello"; if(!string.IsNullOrEmpty(state.Name)) { state.Message += " " + state.Name; } // Tell Step Function to wait 5 seconds before calling state.WaitInSeconds = 5; return state; } public State Salutations(State state, ILambdaContext context) { state.Message += ", Goodbye"; if (!string.IsNullOrEmpty(state.Name)) { state.Message += " " + state.Name; } return state; } } }
53
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using BlueprintBaseName._1; namespace BlueprintBaseName._1.Tests { public class FunctionTest { public FunctionTest() { } [Fact] public void TestGreeting() { TestLambdaContext context = new TestLambdaContext(); StepFunctionTasks functions = new StepFunctionTasks(); var state = new State { Name = "MyStepFunctions" }; state = functions.Greeting(state, context); Assert.Equal(5, state.WaitInSeconds); Assert.Equal("Hello MyStepFunctions", state.Message); } } }
40
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using Amazon.Runtime; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.ApiGatewayManagementApi; using Amazon.ApiGatewayManagementApi.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1 { public class Functions { public const string ConnectionIdField = "connectionId"; /// <summary> /// DynamoDB table used to store the open connection ids. More advanced use cases could store logged on user map to their connection id to implement direct message chatting. /// </summary> string ConnectionMappingTable { get; } /// <summary> /// DynamoDB service client used to store and retieve connection information from the ConnectionMappingTable /// </summary> IAmazonDynamoDB DDBClient { get; } /// <summary> /// Factory func to create the AmazonApiGatewayManagementApiClient. This is needed to created per endpoint of the a connection. It is a factory to make it easy for tests /// to moq the creation. /// </summary> Func<string, IAmazonApiGatewayManagementApi> ApiGatewayManagementApiClientFactory { get; } /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { DDBClient = new AmazonDynamoDBClient(); // Grab the name of the DynamoDB from the environment variable setup in the CloudFormation template serverless.template ConnectionMappingTable = System.Environment.GetEnvironmentVariable("TABLE_NAME"); this.ApiGatewayManagementApiClientFactory = (Func<string, AmazonApiGatewayManagementApiClient>)((endpoint) => { return new AmazonApiGatewayManagementApiClient(new AmazonApiGatewayManagementApiConfig { ServiceURL = endpoint }); }); } /// <summary> /// Constructor used for testing allow tests to pass in moq versions of the service clients. /// </summary> /// <param name="ddbClient"></param> /// <param name="apiGatewayManagementApiClientFactory"></param> /// <param name="connectionMappingTable"></param> public Functions(IAmazonDynamoDB ddbClient, Func<string, IAmazonApiGatewayManagementApi> apiGatewayManagementApiClientFactory, string connectionMappingTable) { this.DDBClient = ddbClient; this.ApiGatewayManagementApiClientFactory = apiGatewayManagementApiClientFactory; this.ConnectionMappingTable = connectionMappingTable; } public async Task<APIGatewayProxyResponse> OnConnectHandler(APIGatewayProxyRequest request, ILambdaContext context) { try { var connectionId = request.RequestContext.ConnectionId; context.Logger.LogLine($"ConnectionId: {connectionId}"); var ddbRequest = new PutItemRequest { TableName = ConnectionMappingTable, Item = new Dictionary<string, AttributeValue> { {ConnectionIdField, new AttributeValue{ S = connectionId}} } }; await DDBClient.PutItemAsync(ddbRequest); return new APIGatewayProxyResponse { StatusCode = 200, Body = "Connected." }; } catch (Exception e) { context.Logger.LogLine("Error connecting: " + e.Message); context.Logger.LogLine(e.StackTrace); return new APIGatewayProxyResponse { StatusCode = 500, Body = $"Failed to connect: {e.Message}" }; } } public async Task<APIGatewayProxyResponse> SendMessageHandler(APIGatewayProxyRequest request, ILambdaContext context) { try { // Construct the API Gateway endpoint that incoming message will be broadcasted to. var domainName = request.RequestContext.DomainName; var stage = request.RequestContext.Stage; var endpoint = $"https://{domainName}/{stage}"; context.Logger.LogLine($"API Gateway management endpoint: {endpoint}"); // The body will look something like this: {"message":"sendmessage", "data":"What are you doing?"} JsonDocument message = JsonDocument.Parse(request.Body); // Grab the data from the JSON body which is the message to broadcasted. JsonElement dataProperty; if (!message.RootElement.TryGetProperty("data", out dataProperty)) { context.Logger.LogLine("Failed to find data element in JSON document"); return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest }; } var data = dataProperty.GetString(); var stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data)); // List all of the current connections. In a more advanced use case the table could be used to grab a group of connection ids for a chat group. var scanRequest = new ScanRequest { TableName = ConnectionMappingTable, ProjectionExpression = ConnectionIdField }; var scanResponse = await DDBClient.ScanAsync(scanRequest); // Construct the IAmazonApiGatewayManagementApi which will be used to send the message to. var apiClient = ApiGatewayManagementApiClientFactory(endpoint); // Loop through all of the connections and broadcast the message out to the connections. var count = 0; foreach (var item in scanResponse.Items) { var postConnectionRequest = new PostToConnectionRequest { ConnectionId = item[ConnectionIdField].S, Data = stream }; try { context.Logger.LogLine($"Post to connection {count}: {postConnectionRequest.ConnectionId}"); stream.Position = 0; await apiClient.PostToConnectionAsync(postConnectionRequest); count++; } catch (AmazonServiceException e) { // API Gateway returns a status of 410 GONE then the connection is no // longer available. If this happens, delete the identifier // from our DynamoDB table. if (e.StatusCode == HttpStatusCode.Gone) { var ddbDeleteRequest = new DeleteItemRequest { TableName = ConnectionMappingTable, Key = new Dictionary<string, AttributeValue> { {ConnectionIdField, new AttributeValue {S = postConnectionRequest.ConnectionId}} } }; context.Logger.LogLine($"Deleting gone connection: {postConnectionRequest.ConnectionId}"); await DDBClient.DeleteItemAsync(ddbDeleteRequest); } else { context.Logger.LogLine($"Error posting message to {postConnectionRequest.ConnectionId}: {e.Message}"); context.Logger.LogLine(e.StackTrace); } } } return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Data sent to " + count + " connection" + (count == 1 ? "" : "s") }; } catch (Exception e) { context.Logger.LogLine("Error disconnecting: " + e.Message); context.Logger.LogLine(e.StackTrace); return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.InternalServerError, Body = $"Failed to send message: {e.Message}" }; } } public async Task<APIGatewayProxyResponse> OnDisconnectHandler(APIGatewayProxyRequest request, ILambdaContext context) { try { var connectionId = request.RequestContext.ConnectionId; context.Logger.LogLine($"ConnectionId: {connectionId}"); var ddbRequest = new DeleteItemRequest { TableName = ConnectionMappingTable, Key = new Dictionary<string, AttributeValue> { {ConnectionIdField, new AttributeValue {S = connectionId}} } }; await DDBClient.DeleteItemAsync(ddbRequest); return new APIGatewayProxyResponse { StatusCode = 200, Body = "Disconnected." }; } catch (Exception e) { context.Logger.LogLine("Error disconnecting: " + e.Message); context.Logger.LogLine(e.StackTrace); return new APIGatewayProxyResponse { StatusCode = 500, Body = $"Failed to disconnect: {e.Message}" }; } } } }
252
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; using Moq; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.ApiGatewayManagementApi; using Amazon.ApiGatewayManagementApi.Model; namespace BlueprintBaseName._1.Tests { public class FunctionTest { public FunctionTest() { } [Fact] public async Task TestConnect() { Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>(); Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>(); string tableName = "mocktable"; string connectionId = "test-id"; _mockDDBClient.Setup(client => client.PutItemAsync(It.IsAny<PutItemRequest>(), It.IsAny<CancellationToken>())) .Callback<PutItemRequest, CancellationToken>((request, token) => { Assert.Equal(tableName, request.TableName); Assert.Equal(connectionId, request.Item[Functions.ConnectionIdField].S); }); var functions = new Functions(_mockDDBClient.Object, (endpoint) => _mockApiGatewayClient.Object, tableName); var lambdaContext = new TestLambdaContext(); var request = new APIGatewayProxyRequest { RequestContext = new APIGatewayProxyRequest.ProxyRequestContext { ConnectionId = connectionId } }; var response = await functions.OnConnectHandler(request, lambdaContext); Assert.Equal(200, response.StatusCode); } [Fact] public async Task TestDisconnect() { Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>(); Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>(); string tableName = "mocktable"; string connectionId = "test-id"; _mockDDBClient.Setup(client => client.DeleteItemAsync(It.IsAny<DeleteItemRequest>(), It.IsAny<CancellationToken>())) .Callback<DeleteItemRequest, CancellationToken>((request, token) => { Assert.Equal(tableName, request.TableName); Assert.Equal(connectionId, request.Key[Functions.ConnectionIdField].S); }); var functions = new Functions(_mockDDBClient.Object, (endpoint) => _mockApiGatewayClient.Object, tableName); var lambdaContext = new TestLambdaContext(); var request = new APIGatewayProxyRequest { RequestContext = new APIGatewayProxyRequest.ProxyRequestContext { ConnectionId = connectionId } }; var response = await functions.OnDisconnectHandler(request, lambdaContext); Assert.Equal(200, response.StatusCode); } [Fact] public async Task TestSendMessage() { Mock<IAmazonDynamoDB> _mockDDBClient = new Mock<IAmazonDynamoDB>(); Mock<IAmazonApiGatewayManagementApi> _mockApiGatewayClient = new Mock<IAmazonApiGatewayManagementApi>(); string tableName = "mocktable"; string connectionId = "test-id"; string message = "hello world"; _mockDDBClient.Setup(client => client.ScanAsync(It.IsAny<ScanRequest>(), It.IsAny<CancellationToken>())) .Callback<ScanRequest, CancellationToken>((request, token) => { Assert.Equal(tableName, request.TableName); Assert.Equal(Functions.ConnectionIdField, request.ProjectionExpression); }) .Returns((ScanRequest r, CancellationToken token) => { return Task.FromResult(new ScanResponse { Items = new List<Dictionary<string, AttributeValue>> { { new Dictionary<string, AttributeValue>{ {Functions.ConnectionIdField, new AttributeValue { S = connectionId } } } } } }); }); Func<string, IAmazonApiGatewayManagementApi> apiGatewayFactory = ((endpoint) => { Assert.Equal("https://test-domain/test-stage", endpoint); return _mockApiGatewayClient.Object; }); _mockApiGatewayClient.Setup(client => client.PostToConnectionAsync(It.IsAny<PostToConnectionRequest>(), It.IsAny<CancellationToken>())) .Callback<PostToConnectionRequest, CancellationToken>((request, token) => { var actualMessage = new StreamReader(request.Data).ReadToEnd(); Assert.Equal(message, actualMessage); }); var functions = new Functions(_mockDDBClient.Object, apiGatewayFactory, tableName); var lambdaContext = new TestLambdaContext(); var request = new APIGatewayProxyRequest { RequestContext = new APIGatewayProxyRequest.ProxyRequestContext { ConnectionId = connectionId, DomainName = "test-domain", Stage = "test-stage" }, Body = "{\"message\":\"sendmessage\", \"data\":\"" + message + "\"}" }; var response = await functions.SendMessageHandler(request, lambdaContext); Assert.Equal(200, response.StatusCode); } } }
147
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.Annotations; using Amazon.Lambda.Annotations.APIGateway; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; /// <summary> /// A collection of sample Lambda functions that provide a REST api for doing simple math calculations. /// </summary> public class Functions { /// <summary> /// Default constructor. /// </summary> public Functions() { } /// <summary> /// Root route that provides information about the other requests that can be made. /// </summary> /// <returns>API descriptions.</returns> [LambdaFunction()] [HttpApi(LambdaHttpMethod.Get, "/")] public string Default() { var docs = @"Lambda Calculator Home: You can make the following requests to invoke other Lambda functions perform calculator operations: /add/{x}/{y} /subtract/{x}/{y} /multiply/{x}/{y} /divide/{x}/{y} "; return docs; } /// <summary> /// Perform x + y /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Sum of x and y.</returns> [LambdaFunction()] [HttpApi(LambdaHttpMethod.Get, "/add/{x}/{y}")] public int Add(int x, int y, ILambdaContext context) { context.Logger.LogInformation($"{x} plus {y} is {x + y}"); return x + y; } /// <summary> /// Perform x - y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x subtract y</returns> [LambdaFunction()] [HttpApi(LambdaHttpMethod.Get, "/subtract/{x}/{y}")] public int Subtract(int x, int y, ILambdaContext context) { context.Logger.LogInformation($"{x} subtract {y} is {x - y}"); return x - y; } /// <summary> /// Perform x * y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x multiply y</returns> [LambdaFunction()] [HttpApi(LambdaHttpMethod.Get, "/multiply/{x}/{y}")] public int Multiply(int x, int y, ILambdaContext context) { context.Logger.LogInformation($"{x} multiply {y} is {x * y}"); return x * y; } /// <summary> /// Perform x / y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x divide y</returns> [LambdaFunction()] [HttpApi(LambdaHttpMethod.Get, "/divide/{x}/{y}")] public int Divide(int x, int y, ILambdaContext context) { context.Logger.LogInformation($"{x} divide {y} is {x / y}"); return x / y; } }
94
aws-lambda-dotnet
aws
C#
using Microsoft.Extensions.DependencyInjection; namespace BlueprintBaseName._1; [Amazon.Lambda.Annotations.LambdaStartup] public class Startup { /// <summary> /// Services for Lambda functions can be registered in the services dependency injection container in this method. /// /// The services can be injected into the Lambda function through the containing type's constructor or as a /// parameter in the Lambda function using the FromService attribute. Services injected for the constructor have /// the lifetime of the Lambda compute container. Services injected as parameters are created within the scope /// of the function invocation. /// </summary> public void ConfigureServices(IServiceCollection services) { //// Example of creating the IConfiguration object and //// adding it to the dependency injection container. //var builder = new ConfigurationBuilder() // .AddJsonFile("appsettings.json", true); //// Add AWS Systems Manager as a potential provider for the configuration. This is //// available with the Amazon.Extensions.Configuration.SystemsManager NuGet package. //builder.AddSystemsManager("/app/settings"); //var configuration = builder.Build(); //services.AddSingleton<IConfiguration>(configuration); //// Example of using the AWSSDK.Extensions.NETCore.Setup NuGet package to add //// the Amazon S3 service client to the dependency injection container. //services.AddAWSService<Amazon.S3.IAmazonS3>(); } }
35
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionsTest { public FunctionsTest() { } [Fact] public void TestAdd() { TestLambdaContext context = new TestLambdaContext(); var functions = new Functions(); Assert.Equal(12, functions.Add(3, 9, context)); } }
20
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// BlueprintBaseName.1::BlueprintBaseName.1.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer // will fail to convert the incoming request correctly into a valid ASP.NET Core request. // // API Gateway REST API -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction // Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction // // Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0 // will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class. Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } /// <summary> /// Use this override to customize the services registered with the IHostBuilder. /// /// It is recommended not to call ConfigureWebHostDefaults to configure the IWebHostBuilder inside this method. /// Instead customize the IWebHostBuilder in the Init(IWebHostBuilder) overload. /// </summary> /// <param name="builder"></param> protected override void Init(IHostBuilder builder) { } }
45
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver. /// </summary> public class LocalEntryPoint { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
19
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Welcome to running ASP.NET Core on AWS Lambda"); }); }); } }
41
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace BlueprintBaseName._1.Controllers; [Route("api/[controller]")] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } }
39
aws-lambda-dotnet
aws
C#
using System.Text.Json; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class ValuesControllerTests { [Fact] public async Task TestGet() { var lambdaFunction = new LambdaEntryPoint(); var requestStr = File.ReadAllText("./SampleRequests/ValuesController-Get.json"); var request = JsonSerializer.Deserialize<APIGatewayProxyRequest>(requestStr, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); var context = new TestLambdaContext(); var response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } }
35
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// BlueprintBaseName.1::BlueprintBaseName.1.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer // will fail to convert the incoming request correctly into a valid ASP.NET Core request. // // API Gateway REST API -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction // Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction // // Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0 // will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class. Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } /// <summary> /// Use this override to customize the services registered with the IHostBuilder. /// /// It is recommended not to call ConfigureWebHostDefaults to configure the IWebHostBuilder inside this method. /// Instead customize the IWebHostBuilder in the Init(IWebHostBuilder) overload. /// </summary> /// <param name="builder"></param> protected override void Init(IHostBuilder builder) { } }
45
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver. /// </summary> public class LocalEntryPoint { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
19
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Welcome to running ASP.NET Core on AWS Lambda"); }); }); } }
41
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace BlueprintBaseName._1.Controllers; [Route("api/[controller]")] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } }
39
aws-lambda-dotnet
aws
C#
using System.Text.Json; using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class ValuesControllerTests { [Fact] public async Task TestGet() { var lambdaFunction = new LambdaEntryPoint(); var requestStr = File.ReadAllText("./SampleRequests/ValuesController-Get.json"); var request = JsonSerializer.Deserialize<APIGatewayProxyRequest>(requestStr, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); var context = new TestLambdaContext(); var response = await lambdaFunction.FunctionHandlerAsync(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("[\"value1\",\"value2\"]", response.Body); Assert.True(response.MultiValueHeaders.ContainsKey("Content-Type")); Assert.Equal("application/json; charset=utf-8", response.MultiValueHeaders["Content-Type"][0]); } }
31
aws-lambda-dotnet
aws
C#
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Add AWS Lambda support. When application is run in Lambda Kestrel is swapped out as the web server with Amazon.Lambda.AspNetCoreServer. This // package will act as the webserver translating request and responses between the Lambda event source and ASP.NET Core. builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => "Welcome to running ASP.NET Core Minimal API on AWS Lambda"); app.Run();
20
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace BlueprintBaseName._1.Controllers; [ApiController] [Route("[controller]")] public class CalculatorController : ControllerBase { private readonly ILogger<CalculatorController> _logger; public CalculatorController(ILogger<CalculatorController> logger) { _logger = logger; } /// <summary> /// Perform x + y /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Sum of x and y.</returns> [HttpGet("add/{x}/{y}")] public int Add(int x, int y) { _logger.LogInformation($"{x} plus {y} is {x + y}"); return x + y; } /// <summary> /// Perform x - y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x subtract y</returns> [HttpGet("subtract/{x}/{y}")] public int Subtract(int x, int y) { _logger.LogInformation($"{x} subtract {y} is {x - y}"); return x - y; } /// <summary> /// Perform x * y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x multiply y</returns> [HttpGet("multiply/{x}/{y}")] public int Multiply(int x, int y) { _logger.LogInformation($"{x} multiply {y} is {x * y}"); return x * y; } /// <summary> /// Perform x / y. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x divide y</returns> [HttpGet("divide/{x}/{y}")] public int Divide(int x, int y) { _logger.LogInformation($"{x} divide {y} is {x / y}"); return x / y; } }
68
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// BlueprintBaseName.1::BlueprintBaseName.1.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer // will fail to convert the incoming request correctly into a valid ASP.NET Core request. // // API Gateway REST API -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction // Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction // // Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0 // will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class. Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } /// <summary> /// Use this override to customize the services registered with the IHostBuilder. /// /// It is recommended not to call ConfigureWebHostDefaults to configure the IWebHostBuilder inside this method. /// Instead customize the IWebHostBuilder in the Init(IWebHostBuilder) overload. /// </summary> /// <param name="builder"></param> protected override void Init(IHostBuilder builder) { } }
45
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
16
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }
45
aws-lambda-dotnet
aws
C#
using System.Diagnostics; using Microsoft.AspNetCore.Mvc.RazorPages; namespace BlueprintBaseName._1.Pages; public class ErrorModel : PageModel { public string? RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } }
16
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc.RazorPages; namespace BlueprintBaseName._1.Pages; public class HelpModel : PageModel { public void OnGet() { } }
11
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc.RazorPages; namespace BlueprintBaseName._1.Pages; public class IndexModel : PageModel { public void OnGet() { } }
11
aws-lambda-dotnet
aws
C#
using System.Text.Json; using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// Base class for intent processors. /// </summary> public abstract class AbstractIntentProcessor : IIntentProcessor { internal const string MESSAGE_CONTENT_TYPE = "PlainText"; /// <summary> /// Main method for proccessing the lex event for the intent. /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> public abstract LexResponse Process(LexEvent lexEvent, ILambdaContext context); protected string SerializeReservation(FlowerOrder order) { return JsonSerializer.Serialize(order, new JsonSerializerOptions { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }); } protected FlowerOrder DeserializeReservation(string json) { return JsonSerializer.Deserialize<FlowerOrder>(json) ?? new FlowerOrder() ; } protected LexResponse Close(IDictionary<string, string> sessionAttributes, string fulfillmentState, LexResponse.LexMessage message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "Close", FulfillmentState = fulfillmentState, Message = message } }; } protected LexResponse Delegate(IDictionary<string, string> sessionAttributes, IDictionary<string, string?> slots) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "Delegate", Slots = slots } }; } protected LexResponse ElicitSlot(IDictionary<string, string> sessionAttributes, string intentName, IDictionary<string, string?> slots, string? slotToElicit, LexResponse.LexMessage? message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "ElicitSlot", IntentName = intentName, Slots = slots, SlotToElicit = slotToElicit, Message = message } }; } protected LexResponse ConfirmIntent(IDictionary<string, string> sessionAttributes, string intentName, IDictionary<string, string?> slots, LexResponse.LexMessage? message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "ConfirmIntent", IntentName = intentName, Slots = slots, Message = message } }; } }
93
aws-lambda-dotnet
aws
C#
using System.Text.Json.Serialization; namespace BlueprintBaseName._1; /// <summary> /// A utility class to store all the current values from the intent's slots. /// </summary> public class FlowerOrder { public FlowerTypes? FlowerType { get; set; } public string? PickUpTime { get; set; } public string? PickUpDate { get; set; } [JsonIgnore] public bool HasRequiredFlowerFields { get { return !string.IsNullOrEmpty(PickUpDate) && !string.IsNullOrEmpty(PickUpTime) && !string.IsNullOrEmpty(FlowerType.ToString()); } } public enum FlowerTypes { Roses, Lilies, Tulips, Null } }
39
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.Serialization; using Amazon.Lambda.LexEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// Then entry point for the Lambda function that looks at the current intent and calls /// the appropriate intent process. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context) { IIntentProcessor process; if (lexEvent.CurrentIntent.Name == "OrderFlowers") { process = new OrderFlowersIntentProcessor(); } else { throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported"); } return process.Process(lexEvent, context); } }
37
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// Represents an intent processor that the Lambda function will invoke to process the event. /// </summary> public interface IIntentProcessor { /// <summary> /// Main method for processing the Lex event for the intent. /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> LexResponse Process(LexEvent lexEvent, ILambdaContext context); }
18
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; using static BlueprintBaseName._1.FlowerOrder; namespace BlueprintBaseName._1; public class OrderFlowersIntentProcessor : AbstractIntentProcessor { public const string TYPE_SLOT = "FlowerType"; public const string PICK_UP_DATE_SLOT = "PickupDate"; public const string PICK_UP_TIME_SLOT = "PickupTime"; public const string INVOCATION_SOURCE = "invocationSource"; FlowerTypes _chosenFlowerType = FlowerTypes.Null; /// <summary> /// Performs dialog management and fulfillment for ordering flowers. /// /// Beyond fulfillment, the implementation for this intent demonstrates the following: /// 1) Use of elicitSlot in slot validation and re-prompting /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> public override LexResponse Process(LexEvent lexEvent, ILambdaContext context) { IDictionary<string, string?> slots = lexEvent.CurrentIntent.Slots ?? new Dictionary<string, string>(); IDictionary<string, string> sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary<string, string>(); //if all the values in the slots are empty return the delegate, theres nothing to validate or do. if (slots.All(x => x.Value == null)) { return Delegate(sessionAttributes, slots); } //if the flower slot has a value, validate that it is contained within the enum list available. if (slots[TYPE_SLOT] != null) { var validateFlowerType = ValidateFlowerType(slots[TYPE_SLOT]); if (!validateFlowerType.IsValid) { slots[validateFlowerType.ViolationSlot!] = null; return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateFlowerType.ViolationSlot, validateFlowerType.Message); } } //now that enum has been parsed and validated, create the order FlowerOrder order = CreateOrder(slots); if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal)) { //validate the remaining slots. var validateResult = Validate(order); // If any slots are invalid, re-elicit for their value if (!validateResult.IsValid) { slots[validateResult.ViolationSlot!] = null; return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message); } // Pass the price of the flowers back through session attributes to be used in various prompts defined // on the bot model. if (order.FlowerType.HasValue && order.FlowerType.Value != FlowerTypes.Null) { sessionAttributes["Price"] = (order.FlowerType.Value.ToString().Length * 5).ToString(); } return Delegate(sessionAttributes, slots); } return Close( sessionAttributes, "Fulfilled", new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = String.Format("Thanks, your order for {0} has been placed and will be ready for pickup by {1} on {2}.", order.FlowerType.ToString(), order.PickUpTime, order.PickUpDate) } ); } private FlowerOrder CreateOrder(IDictionary<string, string?> slots) { FlowerOrder order = new FlowerOrder { FlowerType = _chosenFlowerType, PickUpDate = slots.ContainsKey(PICK_UP_DATE_SLOT) ? slots[PICK_UP_DATE_SLOT] : null, PickUpTime = slots.ContainsKey(PICK_UP_TIME_SLOT) ? slots[PICK_UP_TIME_SLOT] : null }; return order; } /// <summary> /// Verifies that any values for slots in the intent are valid. /// </summary> /// <param name="order"></param> /// <returns></returns> private ValidationResult Validate(FlowerOrder order) { if (!string.IsNullOrEmpty(order.PickUpDate)) { DateTime pickUpDate = DateTime.MinValue; if (!DateTime.TryParse(order.PickUpDate, out pickUpDate)) { return new ValidationResult(false, PICK_UP_DATE_SLOT, "I did not understand that, what date would you like to pick the flowers up?"); } if (pickUpDate < DateTime.Today) { return new ValidationResult(false, PICK_UP_DATE_SLOT, "You can pick up the flowers from tomorrow onwards. What day would you like to pick them up?"); } } if (!string.IsNullOrEmpty(order.PickUpTime)) { string[] timeComponents = order.PickUpTime.Split(":"); Double hour = Double.Parse(timeComponents[0]); Double minutes = Double.Parse(timeComponents[1]); if (Double.IsNaN(hour) || Double.IsNaN(minutes)) { return new ValidationResult(false, PICK_UP_TIME_SLOT, null); } if (hour < 10 || hour >= 17) { return new ValidationResult(false, PICK_UP_TIME_SLOT, "Our business hours are from ten a m. to five p m. Can you specify a time during this range?"); } } return ValidationResult.VALID_RESULT; } /// <summary> /// Verifies that any values for flower type slot in the intent is valid. /// </summary> /// <param name="flowertypeString"></param> /// <returns></returns> private ValidationResult ValidateFlowerType(string? flowerTypeString) { if(flowerTypeString == null) { return new ValidationResult(false, TYPE_SLOT, String.Format("We do not have {0}, would you like a different type of flower? Our most popular flowers are roses", flowerTypeString)); } bool isFlowerTypeValid = Enum.IsDefined(typeof(FlowerTypes), flowerTypeString.ToUpper()); if (Enum.TryParse(flowerTypeString, true, out FlowerTypes flowerType)) { _chosenFlowerType = flowerType; return ValidationResult.VALID_RESULT; } else { return new ValidationResult(false, TYPE_SLOT, String.Format("We do not have {0}, would you like a different type of flower? Our most popular flowers are roses", flowerTypeString)); } } }
172
aws-lambda-dotnet
aws
C#
using System.Collections.Immutable; namespace BlueprintBaseName._1; /// <summary> /// Stub implementation that validates input values. A real implementation would check a datastore. /// </summary> public static class TypeValidators { public static readonly ImmutableArray<string> VALID_CAR_TYPES = ImmutableArray.Create<string>(new string[] { "economy", "standard", "midsize", "full size", "minivan", "luxury" }); public static bool IsValidCarType(string carType) { return VALID_CAR_TYPES.Contains(carType.ToLower()); } public static readonly ImmutableArray<string> VALID_CITES = ImmutableArray.Create<string>(new string[]{"new york", "los angeles", "chicago", "houston", "philadelphia", "phoenix", "san antonio", "san diego", "dallas", "san jose", "austin", "jacksonville", "san francisco", "indianapolis", "columbus", "fort worth", "charlotte", "detroit", "el paso", "seattle", "denver", "washington dc", "memphis", "boston", "nashville", "baltimore", "portland" }); public static bool IsValidCity(string city) { return VALID_CITES.Contains(city.ToLower()); } public static readonly ImmutableArray<string> VALID_ROOM_TYPES = ImmutableArray.Create<string>(new string[] { "queen", "king", "deluxe" }); public static bool IsValidRoomType(string roomType) { return VALID_ROOM_TYPES.Contains(roomType.ToLower()); } }
33
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// This class contains the results of validating the current state of all slot values. This is used to send information /// back to the user to fix bad slot values. /// </summary> public class ValidationResult { public static readonly ValidationResult VALID_RESULT = new ValidationResult(true, null, null); public ValidationResult(bool isValid, string? violationSlot, string? message) { this.IsValid = isValid; this.ViolationSlot = violationSlot; if (!string.IsNullOrEmpty(message)) { this.Message = new LexResponse.LexMessage { ContentType = "PlainText", Content = message }; } } /// <summary> /// If the slot values are currently correct. /// </summary> public bool IsValid { get; } /// <summary> /// Which slot value is invalid so the user can correct the value. /// </summary> public string? ViolationSlot { get; } /// <summary> /// The message explaining to the user what is wrong with the slot value. /// </summary> public LexResponse.LexMessage? Message { get; } }
38
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.LexEvents; using Newtonsoft.Json; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void StartOrderingFlowersEventTest() { var json = File.ReadAllText("start-order-flowers-event.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Delegate", response.DialogAction.Type); } [Fact] public void CommitOrderingFlowersEventTest() { var json = File.ReadAllText("commit-order-flowers-event.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Close", response.DialogAction.Type); Assert.Equal("Fulfilled", response.DialogAction.FulfillmentState); Assert.Equal("PlainText", response.DialogAction.Message.ContentType); Assert.Contains("Thanks, your order for Roses has been placed", response.DialogAction.Message.Content); } }
42
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; namespace BlueprintBaseName._1; public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { Func<string, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); } /// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { return input.ToUpper(); } }
35
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestToUpperFunction() { // Invoke the lambda function and confirm the string was upper cased. var context = new TestLambdaContext(); var upperCase = Function.FunctionHandler("hello world", context); Assert.Equal("HELLO WORLD", upperCase); } }
20
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.Rekognition; using Amazon.Rekognition.Model; using Amazon.S3; using Amazon.S3.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// The default minimum confidence used for detecting labels. /// </summary> public const float DEFAULT_MIN_CONFIDENCE = 70f; /// <summary> /// The name of the environment variable to set which will override the default minimum confidence level. /// </summary> public const string MIN_CONFIDENCE_ENVIRONMENT_VARIABLE_NAME = "MinConfidence"; IAmazonS3 S3Client { get; } IAmazonRekognition RekognitionClient { get; } float MinConfidence { get; set; } = DEFAULT_MIN_CONFIDENCE; HashSet<string> SupportedImageTypes { get; } = new HashSet<string> { ".png", ".jpg", ".jpeg" }; /// <summary> /// Default constructor used by AWS Lambda to construct the function. Credentials and Region information will /// be set by the running Lambda environment. /// /// This constuctor will also search for the environment variable overriding the default minimum confidence level /// for label detection. /// </summary> public Function() { this.S3Client = new AmazonS3Client(); this.RekognitionClient = new AmazonRekognitionClient(); var environmentMinConfidence = System.Environment.GetEnvironmentVariable(MIN_CONFIDENCE_ENVIRONMENT_VARIABLE_NAME); if(!string.IsNullOrWhiteSpace(environmentMinConfidence)) { float value; if(float.TryParse(environmentMinConfidence, out value)) { this.MinConfidence = value; Console.WriteLine($"Setting minimum confidence to {this.MinConfidence}"); } else { Console.WriteLine($"Failed to parse value {environmentMinConfidence} for minimum confidence. Reverting back to default of {this.MinConfidence}"); } } else { Console.WriteLine($"Using default minimum confidence of {this.MinConfidence}"); } } /// <summary> /// Constructor used for testing which will pass in the already configured service clients. /// </summary> /// <param name="s3Client"></param> /// <param name="rekognitionClient"></param> /// <param name="minConfidence"></param> public Function(IAmazonS3 s3Client, IAmazonRekognition rekognitionClient, float minConfidence) { this.S3Client = s3Client; this.RekognitionClient = rekognitionClient; this.MinConfidence = minConfidence; } /// <summary> /// A function for responding to S3 create events. It will determine if the object is an image and use Amazon Rekognition /// to detect labels and add the labels as tags on the S3 object. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(S3Event input, ILambdaContext context) { foreach(var record in input.Records) { if(!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key))) { Console.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type"); continue; } Console.WriteLine($"Looking for labels in image {record.S3.Bucket.Name}:{record.S3.Object.Key}"); var detectResponses = await this.RekognitionClient.DetectLabelsAsync(new DetectLabelsRequest { MinConfidence = MinConfidence, Image = new Image { S3Object = new Amazon.Rekognition.Model.S3Object { Bucket = record.S3.Bucket.Name, Name = record.S3.Object.Key } } }); var tags = new List<Tag>(); foreach(var label in detectResponses.Labels) { if(tags.Count < 10) { Console.WriteLine($"\tFound Label {label.Name} with confidence {label.Confidence}"); tags.Add(new Tag { Key = label.Name, Value = label.Confidence.ToString() }); } else { Console.WriteLine($"\tSkipped label {label.Name} with confidence {label.Confidence} because the maximum number of tags has been reached"); } } await this.S3Client.PutObjectTaggingAsync(new PutObjectTaggingRequest { BucketName = record.S3.Bucket.Name, Key = record.S3.Object.Key, Tagging = new Tagging { TagSet = tags } }); } return; } }
139
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.Rekognition; using Amazon.Lambda.S3Events; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task IntegrationTest() { const string fileName = "sample-pic.jpg"; IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USWest2); IAmazonRekognition rekognitionClient = new AmazonRekognitionClient(RegionEndpoint.USWest2); var bucketName = "lambda-BlueprintBaseName.1-".ToLower() + DateTime.Now.Ticks; await s3Client.PutBucketAsync(bucketName); try { await s3Client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, FilePath = fileName }); // Setup the S3 event object that S3 notifications would create and send to the Lambda function if // the bucket was configured as an event source. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = bucketName }, Object = new S3Event.S3ObjectEntity {Key = fileName } } } } }; // Use test constructor for the function with the service clients created for the test var function = new Function(s3Client, rekognitionClient, Function.DEFAULT_MIN_CONFIDENCE); var context = new TestLambdaContext(); await function.FunctionHandler(s3Event, context); var getTagsResponse = await s3Client.GetObjectTaggingAsync(new GetObjectTaggingRequest { BucketName = bucketName, Key = fileName }); Assert.True(getTagsResponse.Tagging.Count > 0); } finally { // Clean up the test data await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } }
72
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.Rekognition; using Amazon.Rekognition.Model; using Amazon.S3; using Amazon.S3.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// The default minimum confidence used for detecting labels. /// </summary> public const float DEFAULT_MIN_CONFIDENCE = 70f; /// <summary> /// The name of the environment variable to set which will override the default minimum confidence level. /// </summary> public const string MIN_CONFIDENCE_ENVIRONMENT_VARIABLE_NAME = "MinConfidence"; IAmazonS3 S3Client { get; } IAmazonRekognition RekognitionClient { get; } float MinConfidence { get; set; } = DEFAULT_MIN_CONFIDENCE; HashSet<string> SupportedImageTypes { get; } = new HashSet<string> { ".png", ".jpg", ".jpeg" }; /// <summary> /// Default constructor used by AWS Lambda to construct the function. Credentials and Region information will /// be set by the running Lambda environment. /// /// This constuctor will also search for the environment variable overriding the default minimum confidence level /// for label detection. /// </summary> public Function() { this.S3Client = new AmazonS3Client(); this.RekognitionClient = new AmazonRekognitionClient(); var environmentMinConfidence = System.Environment.GetEnvironmentVariable(MIN_CONFIDENCE_ENVIRONMENT_VARIABLE_NAME); if(!string.IsNullOrWhiteSpace(environmentMinConfidence)) { float value; if(float.TryParse(environmentMinConfidence, out value)) { this.MinConfidence = value; Console.WriteLine($"Setting minimum confidence to {this.MinConfidence}"); } else { Console.WriteLine($"Failed to parse value {environmentMinConfidence} for minimum confidence. Reverting back to default of {this.MinConfidence}"); } } else { Console.WriteLine($"Using default minimum confidence of {this.MinConfidence}"); } } /// <summary> /// Constructor used for testing which will pass in the already configured service clients. /// </summary> /// <param name="s3Client"></param> /// <param name="rekognitionClient"></param> /// <param name="minConfidence"></param> public Function(IAmazonS3 s3Client, IAmazonRekognition rekognitionClient, float minConfidence) { this.S3Client = s3Client; this.RekognitionClient = rekognitionClient; this.MinConfidence = minConfidence; } /// <summary> /// A function for responding to S3 create events. It will determine if the object is an image and use Amazon Rekognition /// to detect labels and add the labels as tags on the S3 object. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(S3Event input, ILambdaContext context) { foreach(var record in input.Records) { if(!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key))) { Console.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type"); continue; } Console.WriteLine($"Looking for labels in image {record.S3.Bucket.Name}:{record.S3.Object.Key}"); var detectResponses = await this.RekognitionClient.DetectLabelsAsync(new DetectLabelsRequest { MinConfidence = MinConfidence, Image = new Image { S3Object = new Amazon.Rekognition.Model.S3Object { Bucket = record.S3.Bucket.Name, Name = record.S3.Object.Key } } }); var tags = new List<Tag>(); foreach(var label in detectResponses.Labels) { if(tags.Count < 10) { Console.WriteLine($"\tFound Label {label.Name} with confidence {label.Confidence}"); tags.Add(new Tag { Key = label.Name, Value = label.Confidence.ToString() }); } else { Console.WriteLine($"\tSkipped label {label.Name} with confidence {label.Confidence} because the maximum number of tags has been reached"); } } await this.S3Client.PutObjectTaggingAsync(new PutObjectTaggingRequest { BucketName = record.S3.Bucket.Name, Key = record.S3.Object.Key, Tagging = new Tagging { TagSet = tags } }); } return; } }
139
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.Rekognition; using Amazon.Lambda.S3Events; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task IntegrationTest() { const string fileName = "sample-pic.jpg"; IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USWest2); IAmazonRekognition rekognitionClient = new AmazonRekognitionClient(RegionEndpoint.USWest2); var bucketName = "lambda-BlueprintBaseName.1-".ToLower() + DateTime.Now.Ticks; await s3Client.PutBucketAsync(bucketName); try { await s3Client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, FilePath = fileName }); // Setup the S3 event object that S3 notifications would create and send to the Lambda function if // the bucket was configured as an event source. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = bucketName }, Object = new S3Event.S3ObjectEntity {Key = fileName } } } } }; // Use test constructor for the function with the service clients created for the test var function = new Function(s3Client, rekognitionClient, Function.DEFAULT_MIN_CONFIDENCE); var context = new TestLambdaContext(); await function.FunctionHandler(s3Event, context); var getTagsResponse = await s3Client.GetObjectTaggingAsync(new GetObjectTaggingRequest { BucketName = bucketName, Key = fileName }); Assert.True(getTagsResponse.Tagging.Count > 0); } finally { // Clean up the test data await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } }
72
aws-lambda-dotnet
aws
C#
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.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; 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(); } }
22
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.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); } }
21
aws-lambda-dotnet
aws
C#
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.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// A simple function that takes a string and returns both the upper and lower case version of the string. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public Casing FunctionHandler(string input, ILambdaContext context) { return new Casing(input.ToLower(), input.ToUpper()); } } public record Casing(string Lower, string Upper);
23
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.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 casing = function.FunctionHandler("hello world", context); Assert.Equal("hello world", casing.Lower); Assert.Equal("HELLO WORLD", casing.Upper); } }
21
aws-lambda-dotnet
aws
C#
using System.Net; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogInformation("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } }
38
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class FunctionTest { public FunctionTest() { } [Fact] public void TestGetMethod() { TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.Get(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello AWS Serverless", response.Body); } }
31
aws-lambda-dotnet
aws
C#
using System.Net; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogInformation("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } }
38
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class FunctionsTest { public FunctionsTest() { } [Fact] public void TetGetMethod() { TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.Get(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello AWS Serverless", response.Body); } }
31
aws-lambda-dotnet
aws
C#
using System.Text.Json; using System.Text.Json.Serialization; using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// Base class for intent processors. /// </summary> public abstract class AbstractIntentProcessor : IIntentProcessor { internal const string CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE = "currentReservationPrice"; internal const string CURRENT_RESERVATION_SESSION_ATTRIBUTE = "currentReservation"; internal const string LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE = "lastConfirmedReservation"; internal const string MESSAGE_CONTENT_TYPE = "PlainText"; /// <summary> /// Main method for proccessing the lex event for the intent. /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> public abstract LexResponse Process(LexEvent lexEvent, ILambdaContext context); protected string SerializeReservation(Reservation reservation) { return JsonSerializer.Serialize(reservation, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); } protected Reservation DeserializeReservation(string json) { return JsonSerializer.Deserialize<Reservation>(json) ?? new Reservation(); } protected LexResponse Close(IDictionary<string, string> sessionAttributes, string fulfillmentState, LexResponse.LexMessage message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "Close", FulfillmentState = fulfillmentState, Message = message } }; } protected LexResponse Delegate(IDictionary<string, string> sessionAttributes, IDictionary<string, string> slots) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "Delegate", Slots = slots } }; } protected LexResponse ElicitSlot(IDictionary<string, string> sessionAttributes, string intentName, IDictionary<string, string?> slots, string? slotToElicit, LexResponse.LexMessage? message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "ElicitSlot", IntentName = intentName, Slots = slots, SlotToElicit = slotToElicit, Message = message } }; } protected LexResponse ConfirmIntent(IDictionary<string, string> sessionAttributes, string intentName, IDictionary<string, string?> slots, LexResponse.LexMessage? message) { return new LexResponse { SessionAttributes = sessionAttributes, DialogAction = new LexResponse.LexDialogAction { Type = "ConfirmIntent", IntentName = intentName, Slots = slots, Message = message } }; } }
98
aws-lambda-dotnet
aws
C#
using System.Globalization; using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; public class BookCarIntentProcessor : AbstractIntentProcessor { public const string PICK_UP_CITY_SLOT = "PickUpCity"; public const string PICK_UP_DATE_SLOT = "PickUpDate"; public const string RETURN_DATE_SLOT = "ReturnDate"; public const string DRIVER_AGE_SLOT = "DriverAge"; public const string CAR_TYPE_SLOT = "CarType"; /// <summary> /// Performs dialog management and fulfillment for booking a car. /// /// Beyond fulfillment, the implementation for this intent demonstrates the following: /// 1) Use of elicitSlot in slot validation and re-prompting /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation /// </summary> /// <param name="lexEvent"></param> /// <returns></returns> public override LexResponse Process(LexEvent lexEvent, ILambdaContext context) { var slots = lexEvent.CurrentIntent.Slots; var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary<string, string>(); Reservation reservation = new Reservation { ReservationType = "Car", PickUpCity = slots.ContainsKey(PICK_UP_CITY_SLOT) ? slots[PICK_UP_CITY_SLOT] : null, PickUpDate = slots.ContainsKey(PICK_UP_DATE_SLOT) ? slots[PICK_UP_DATE_SLOT] : null, ReturnDate = slots.ContainsKey(RETURN_DATE_SLOT) ? slots[RETURN_DATE_SLOT] : null, DriverAge = slots.ContainsKey(DRIVER_AGE_SLOT) ? slots[DRIVER_AGE_SLOT] : null, CarType = slots.ContainsKey(CAR_TYPE_SLOT) ? slots[CAR_TYPE_SLOT] : null, }; string confirmationStaus = lexEvent.CurrentIntent.ConfirmationStatus; Reservation? lastConfirmedReservation = null; if (slots.ContainsKey(LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE)) { lastConfirmedReservation = DeserializeReservation(slots[LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE]); } string? confirmationContext = sessionAttributes.ContainsKey("confirmationContext") ? sessionAttributes["confirmationContext"] : null; sessionAttributes[CURRENT_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); var validateResult = Validate(reservation); context.Logger.LogInformation($"Has required fields: {reservation.HasRequiredCarFields}, Has valid values {validateResult.IsValid}"); if(!validateResult.IsValid) { context.Logger.LogInformation($"Slot {validateResult.ViolationSlot} is invalid: {validateResult.Message?.Content}"); } if (reservation.HasRequiredCarFields && validateResult.IsValid) { var price = GeneratePrice(reservation); context.Logger.LogInformation($"Generated price: {price}"); sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE] = price.ToString(CultureInfo.InvariantCulture); } else { sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); } if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal)) { // If any slots are invalid, re-elicit for their value if (!validateResult.IsValid) { slots[validateResult.ViolationSlot] = null; return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message); } // Determine if the intent (and current slot settings) have been denied. The messaging will be different // if the user is denying a reservation they initiated or an auto-populated suggestion. if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "Denied", StringComparison.Ordinal)) { sessionAttributes.Remove("confirmationContext"); sessionAttributes.Remove(CURRENT_RESERVATION_SESSION_ATTRIBUTE); if (string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, new Dictionary<string, string?> { {PICK_UP_CITY_SLOT, null }, {PICK_UP_DATE_SLOT, null }, {RETURN_DATE_SLOT, null }, {DRIVER_AGE_SLOT, null }, {CAR_TYPE_SLOT, null } }, PICK_UP_CITY_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "Where would you like to make your car reservation?" } ); } return Delegate(sessionAttributes, slots); } if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "None", StringComparison.Ordinal)) { // If we are currently auto-populating but have not gotten confirmation, keep requesting for confirmation. if ((!string.IsNullOrEmpty(reservation.PickUpCity) && !string.IsNullOrEmpty(reservation.PickUpDate) && !string.IsNullOrEmpty(reservation.ReturnDate) && !string.IsNullOrEmpty(reservation.DriverAge) && !string.IsNullOrEmpty(reservation.CarType)) || string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { if (lastConfirmedReservation != null && string.Equals(lastConfirmedReservation.ReservationType, "Hotel", StringComparison.Ordinal)) { // If the user's previous reservation was a hotel - prompt for a rental with // auto-populated values to match this reservation. sessionAttributes["confirmationContext"] = "AutoPopulate"; return ConfirmIntent( sessionAttributes, lexEvent.CurrentIntent.Name, new Dictionary<string, string?> { {PICK_UP_CITY_SLOT, lastConfirmedReservation.PickUpCity }, {PICK_UP_DATE_SLOT, lastConfirmedReservation.CheckInDate }, {RETURN_DATE_SLOT, DateTime.Parse(lastConfirmedReservation.CheckInDate!).AddDays(int.Parse(lastConfirmedReservation.Nights!)).ToUniversalTime().ToString(CultureInfo.InvariantCulture) }, {CAR_TYPE_SLOT, null }, {DRIVER_AGE_SLOT, null }, }, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = $"Is this car rental for your {lastConfirmedReservation.Nights} night stay in {lastConfirmedReservation.Location} on {lastConfirmedReservation.CheckInDate}?" } ); } } // Otherwise, let native DM rules determine how to elicit for slots and/or drive confirmation. return Delegate(sessionAttributes, slots); } // If confirmation has occurred, continue filling any unfilled slot values or pass to fulfillment. if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "Confirmed", StringComparison.Ordinal)) { // Remove confirmationContext from sessionAttributes so it does not confuse future requests sessionAttributes.Remove("confirmationContext"); if (string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(reservation.DriverAge)) { return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, DRIVER_AGE_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "How old is the driver of this car rental?" } ); } else if (string.IsNullOrEmpty(reservation.CarType)) { return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, CAR_TYPE_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "What type of car would you like? Popular models are economy, midsize, and luxury." } ); } } return Delegate(sessionAttributes, slots); } } context.Logger.LogInformation($"Book car at = {SerializeReservation(reservation)}"); if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE)) { context.Logger.LogInformation($"Book car price = {sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE]}"); } sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); sessionAttributes.Remove(CURRENT_RESERVATION_SESSION_ATTRIBUTE); sessionAttributes[LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); return Close( sessionAttributes, "Fulfilled", new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "Thanks, I have placed your reservation." } ); } /// <summary> /// Verifies that any values for slots in the intent are valid. /// </summary> /// <param name="reservation"></param> /// <returns></returns> private ValidationResult Validate(Reservation reservation) { if (!string.IsNullOrEmpty(reservation.PickUpCity) && !TypeValidators.IsValidCity(reservation.PickUpCity)) { return new ValidationResult(false, PICK_UP_CITY_SLOT, $"We currently do not support {reservation.PickUpCity} as a valid destination. Can you try a different city?"); } DateTime pickupDate = DateTime.MinValue; if (!string.IsNullOrEmpty(reservation.PickUpDate)) { if (!DateTime.TryParse(reservation.PickUpDate, out pickupDate)) { return new ValidationResult(false, PICK_UP_DATE_SLOT, "I did not understand your departure date. When would you like to pick up your car rental?"); } if (pickupDate < DateTime.Today) { return new ValidationResult(false, PICK_UP_DATE_SLOT, "Your pick up date is in the past! Can you try a different date?"); } } DateTime returnDate = DateTime.MinValue; if (!string.IsNullOrEmpty(reservation.ReturnDate)) { if (!DateTime.TryParse(reservation.ReturnDate, out returnDate)) { return new ValidationResult(false, RETURN_DATE_SLOT, "I did not understand your return date. When would you like to return your car rental?"); } } if (pickupDate != DateTime.MinValue && returnDate != DateTime.MinValue) { if (returnDate <= pickupDate) { return new ValidationResult(false, RETURN_DATE_SLOT, "Your return date must be after your pick up date. Can you try a different return date?"); } var ts = returnDate.Date - pickupDate.Date; if (ts.Days > 30) { return new ValidationResult(false, RETURN_DATE_SLOT, "You can reserve a car for up to thirty days. Can you try a different return date?"); } } int age = 0; if (!string.IsNullOrEmpty(reservation.DriverAge)) { if (!int.TryParse(reservation.DriverAge, out age)) { return new ValidationResult(false, DRIVER_AGE_SLOT, "I did not understand the driver's age. Can you enter the driver's age again?"); } if (age < 18) { return new ValidationResult(false, DRIVER_AGE_SLOT, "Your driver must be at least eighteen to rent a car. Can you provide the age of a different driver?"); } } if (!string.IsNullOrEmpty(reservation.CarType) && !TypeValidators.IsValidCarType(reservation.CarType)) { return new ValidationResult(false, CAR_TYPE_SLOT, "I did not recognize that model. What type of car would you like to rent? " + "Popular cars are economy, midsize, or luxury"); } return ValidationResult.VALID_RESULT; } /// <summary> /// Generates a number within a reasonable range that might be expected for a flight. /// The price is fixed for a given pair of locations. /// </summary> /// <param name="reservation"></param> /// <returns></returns> private double GeneratePrice(Reservation reservation) { double baseLocationCost = 0; foreach (char c in reservation.PickUpCity!) { baseLocationCost += (c - 97); } double ageMultiplier; if(int.TryParse(reservation.DriverAge, out var age) && age < 25) { ageMultiplier = 1.1; } else { ageMultiplier = 1.0; } var carTypeIndex = 0; for (int i = 0; i < TypeValidators.VALID_CAR_TYPES.Length; i++) { if (string.Equals(TypeValidators.VALID_CAR_TYPES[i], reservation.CarType, StringComparison.Ordinal)) { carTypeIndex = i + 1; break; } } int days = (DateTime.Parse(reservation.ReturnDate!).Date - DateTime.Parse(reservation.PickUpDate!).Date).Days; return days * ((100 + baseLocationCost) + ((carTypeIndex * 50) * ageMultiplier)); } }
332
aws-lambda-dotnet
aws
C#
using System.Globalization; using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; public class BookHotelIntentProcessor : AbstractIntentProcessor { public const string LOCATION_SLOT = "Location"; public const string CHECK_IN_DATE_SLOT = "CheckInDate"; public const string NIGHTS_SLOT = "Nights"; public const string ROOM_TYPE_SLOT = "RoomType"; /// <summary> /// Performs dialog management and fulfillment for booking a hotel. /// /// Beyond fulfillment, the implementation for this intent demonstrates the following: /// 1) Use of elicitSlot in slot validation and re-prompting /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> public override LexResponse Process(LexEvent lexEvent, ILambdaContext context) { var slots = lexEvent.CurrentIntent.Slots; var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary<string, string>(); Reservation reservation = new Reservation { ReservationType = "Hotel", Location = slots.ContainsKey(LOCATION_SLOT) ? slots[LOCATION_SLOT] : null, CheckInDate = slots.ContainsKey(CHECK_IN_DATE_SLOT) ? slots[CHECK_IN_DATE_SLOT] : null, Nights = slots.ContainsKey(NIGHTS_SLOT) ? slots[NIGHTS_SLOT] : null, RoomType = slots.ContainsKey(ROOM_TYPE_SLOT) ? slots[ROOM_TYPE_SLOT] : null }; sessionAttributes[CURRENT_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal)) { var validateResult = Validate(reservation); // If any slots are invalid, re-elicit for their value if (!validateResult.IsValid) { slots[validateResult.ViolationSlot] = null; return ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message); } // Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price // back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes. if (reservation.HasRequiredHotelFields && validateResult.IsValid) { var price = GeneratePrice(reservation); context.Logger.LogInformation($"Generated price: {price}"); sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE] = price.ToString(CultureInfo.InvariantCulture); } else { sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); } return Delegate(sessionAttributes, slots); } // Booking the hotel. In a real application, this would likely involve a call to a backend service. context.Logger.LogInformation($"Book hotel at = {SerializeReservation(reservation)}"); if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE)) { context.Logger.LogInformation($"Book hotel price = {sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE]}"); } sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); sessionAttributes.Remove(CURRENT_RESERVATION_SESSION_ATTRIBUTE); sessionAttributes[LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); return Close( sessionAttributes, "Fulfilled", new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "Thanks, I have placed your hotel reservation." } ); } /// <summary> /// Verifies that any values for slots in the intent are valid. /// </summary> /// <param name="reservation"></param> /// <returns></returns> private ValidationResult Validate(Reservation reservation) { if (!string.IsNullOrEmpty(reservation.Location) && !TypeValidators.IsValidCity(reservation.Location)) { return new ValidationResult(false, LOCATION_SLOT, $"We currently do not support {reservation.Location} as a valid destination. Can you try a different city?"); } if (!string.IsNullOrEmpty(reservation.CheckInDate)) { DateTime checkinDate = DateTime.MinValue; if (!DateTime.TryParse(reservation.CheckInDate, out checkinDate)) { return new ValidationResult(false, CHECK_IN_DATE_SLOT, "I did not understand your check in date. When would you like to check in?"); } if (checkinDate < DateTime.Today) { return new ValidationResult(false, CHECK_IN_DATE_SLOT, "Reservations must be scheduled at least one day in advance. Can you try a different date?"); } } if (!string.IsNullOrEmpty(reservation.Nights)) { int nights; if (!int.TryParse(reservation.Nights, out nights)) { return new ValidationResult(false, NIGHTS_SLOT, "I did not understand the number of nights. Can you enter the number of nights again again?"); } if (nights < 1 || nights > 30) { return new ValidationResult(false, NIGHTS_SLOT, "You can make a reservations for from one to thirty nights. How many nights would you like to stay for?"); } } return ValidationResult.VALID_RESULT; } /// <summary> /// Generates a number within a reasonable range that might be expected for a hotel. /// The price is fixed for a pair of location and roomType. /// </summary> /// <param name="reservation"></param> /// <returns></returns> private double GeneratePrice(Reservation reservation) { double costOfLiving = 0; foreach (char c in reservation.Location!) { costOfLiving += (c - 97); } int roomTypeIndex = 0; for (int i = 0; i < TypeValidators.VALID_ROOM_TYPES.Length; i++) { if (string.Equals(TypeValidators.VALID_ROOM_TYPES[i], reservation.CarType, StringComparison.Ordinal)) { roomTypeIndex = i + 1; break; } } return int.Parse(reservation.Nights!, CultureInfo.InvariantCulture) * (100 + costOfLiving + (100 + roomTypeIndex)); } }
166
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.Serialization; using Amazon.Lambda.LexEvents; using System.IO; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// Then entry point for the Lambda function that looks at the current intent and calls /// the appropriate intent process. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public LexResponse FunctionHandler(LexEvent lexEvent, ILambdaContext context) { IIntentProcessor process; switch (lexEvent.CurrentIntent.Name) { case "BookHotel": process = new BookHotelIntentProcessor(); break; case "BookCar": process = new BookCarIntentProcessor(); break; default: throw new Exception($"Intent with name {lexEvent.CurrentIntent.Name} not supported"); } return process.Process(lexEvent, context); } }
42
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// Represents an intent processor that the Lambda function will invoke to process the event. /// </summary> public interface IIntentProcessor { /// <summary> /// Main method for processing the Lex event for the intent. /// </summary> /// <param name="lexEvent"></param> /// <param name="context"></param> /// <returns></returns> LexResponse Process(LexEvent lexEvent, ILambdaContext context); }
18
aws-lambda-dotnet
aws
C#
using System.Text.Json.Serialization; namespace BlueprintBaseName._1; /// <summary> /// A utility class to store all the current values from the intent's slots. /// </summary> public class Reservation { public string? ReservationType { get; set; } #region Car Reservation Fields public string? PickUpCity { get; set; } public string? PickUpDate { get; set; } public string? ReturnDate { get; set; } public string? CarType { get; set; } public string? DriverAge { get; set; } [JsonIgnore] public bool HasRequiredCarFields { get { return !string.IsNullOrEmpty(PickUpCity) && !string.IsNullOrEmpty(PickUpDate) && !string.IsNullOrEmpty(ReturnDate) && !string.IsNullOrEmpty(CarType) && !string.IsNullOrEmpty(DriverAge); } } #endregion #region Hotel Resevation Fields public string? CheckInDate { get; set; } public string? Location { get; set; } public string? Nights { get; set; } public string? RoomType { get; set; } [JsonIgnore] public bool HasRequiredHotelFields { get { return !string.IsNullOrEmpty(CheckInDate) && !string.IsNullOrEmpty(Location) && !string.IsNullOrEmpty(Nights) && !string.IsNullOrEmpty(RoomType); } } #endregion }
54
aws-lambda-dotnet
aws
C#
using System.Collections.Immutable; namespace BlueprintBaseName._1; /// <summary> /// Stub implementation that validates input values. A real implementation would check a datastore. /// </summary> public static class TypeValidators { public static readonly ImmutableArray<string> VALID_CAR_TYPES = ImmutableArray.Create<string>(new string[] { "economy", "standard", "midsize", "full size", "minivan", "luxury" }); public static bool IsValidCarType(string carType) { return VALID_CAR_TYPES.Contains(carType.ToLower()); } public static readonly ImmutableArray<string> VALID_CITES = ImmutableArray.Create<string>(new string[]{"new york", "los angeles", "chicago", "houston", "philadelphia", "phoenix", "san antonio", "san diego", "dallas", "san jose", "austin", "jacksonville", "san francisco", "indianapolis", "columbus", "fort worth", "charlotte", "detroit", "el paso", "seattle", "denver", "washington dc", "memphis", "boston", "nashville", "baltimore", "portland" }); public static bool IsValidCity(string city) { return VALID_CITES.Contains(city.ToLower()); } public static readonly ImmutableArray<string> VALID_ROOM_TYPES = ImmutableArray.Create<string>(new string[] { "queen", "king", "deluxe" }); public static bool IsValidRoomType(string roomType) { return VALID_ROOM_TYPES.Contains(roomType.ToLower()); } }
33
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.LexEvents; namespace BlueprintBaseName._1; /// <summary> /// This class contains the results of validating the current state of all slot values. This is used to send information /// back to the user to fix bad slot values. /// </summary> public class ValidationResult { public static readonly ValidationResult VALID_RESULT = new ValidationResult(true, null, null); public ValidationResult(bool isValid, string? violationSlot, string? message) { this.IsValid = isValid; this.ViolationSlot = violationSlot; if (!string.IsNullOrEmpty(message)) { this.Message = new LexResponse.LexMessage { ContentType = "PlainText", Content = message }; } } /// <summary> /// If the slot values are currently correct. /// </summary> public bool IsValid { get; } /// <summary> /// Which slot value is invalid so the user can correct the value. /// </summary> public string? ViolationSlot { get; } /// <summary> /// The message explaining to the user what is wrong with the slot value. /// </summary> public LexResponse.LexMessage? Message { get; } }
38
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.LexEvents; using Newtonsoft.Json; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void StartBookACarEventTest() { var json = File.ReadAllText("start-book-a-car-event.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Delegate", response.DialogAction.Type); } [Fact] public void DriverAgeTooYoungEventTest() { var json = File.ReadAllText("driver-age-too-young.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("ElicitSlot", response.DialogAction.Type); Assert.Equal("DriverAge", response.DialogAction.SlotToElicit); Assert.Equal("PlainText", response.DialogAction.Message.ContentType); Assert.Equal("Your driver must be at least eighteen to rent a car. Can you provide the age of a different driver?", response.DialogAction.Message.Content); } [Fact] public void CommitBookACarEventTest() { var json = File.ReadAllText("commit-book-a-car.json"); var lexEvent = JsonConvert.DeserializeObject<LexEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var response = function.FunctionHandler(lexEvent, context); Assert.Equal("Close", response.DialogAction.Type); Assert.Equal("Fulfilled", response.DialogAction.FulfillmentState); Assert.Equal("PlainText", response.DialogAction.Message.ContentType); Assert.Equal("Thanks, I have placed your reservation.", response.DialogAction.Message.Content); } }
59
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using System.Text.Json.Serialization; namespace BlueprintBaseName._1; public class Function { /// <summary> /// The main entry point for the Lambda function. The main function is called once during the Lambda init phase. It /// initializes the .NET Lambda runtime client passing in the function handler to invoke for each Lambda event and /// the JSON serializer to use for converting Lambda JSON format to the .NET types. /// </summary> private static async Task Main() { Func<string, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<LambdaFunctionJsonSerializerContext>()) .Build() .RunAsync(); } /// <summary> /// A simple function that takes a string and does a ToUpper. /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. When the event type /// is changed, the handler type registered in the main method needs to be updated and the LambdaFunctionJsonSerializerContext /// defined below will need the JsonSerializable updated. If the return type and event type are different then the /// LambdaFunctionJsonSerializerContext must have two JsonSerializable attributes, one for each type. /// // When using Native AOT extra testing with the deployed Lambda functions is required to ensure // the libraries used in the Lambda function work correctly with Native AOT. If a runtime // error occurs about missing types or methods the most likely solution will be to remove references to trim-unsafe // code or configure trimming options. This sample defaults to partial TrimMode because currently the AWS // SDK for .NET does not support trimming. This will result in a larger executable size, and still does not // guarantee runtime trimming errors won't be hit. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { return input.ToUpper(); } } /// <summary> /// This class is used to register the input event and return type for the FunctionHandler method with the System.Text.Json source generator. /// There must be a JsonSerializable attribute for each type used as the input and return type or a runtime error will occur /// from the JSON serializer unable to find the serialization information for unknown types. /// </summary> [JsonSerializable(typeof(string))] public partial class LambdaFunctionJsonSerializerContext : JsonSerializerContext { // By using this partial class derived from JsonSerializerContext, we can generate reflection free JSON Serializer code at compile time // which can deserialize our class and properties. However, we must attribute this class to tell it what types to generate serialization code for. // See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-source-generation }
60
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestToUpperFunction() { // Invoke the lambda function and confirm the string was upper cased. var context = new TestLambdaContext(); var upperCase = Function.FunctionHandler("hello world", context); Assert.Equal("HELLO WORLD", upperCase); } }
18
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using Amazon.Lambda.APIGatewayEvents; using System.Text.Json.Serialization; using System.Net; namespace BlueprintBaseName._1; public class Functions { /// <summary> /// The main entry point for the Lambda function. The main function is called once during the Lambda init phase. It /// initializes the .NET Lambda runtime client passing in the function handler to invoke for each Lambda event and /// the JSON serializer to use for converting Lambda JSON format to the .NET types. /// </summary> private static async Task Main() { // The "_HANDLER" environment variable is set by the Lambda runtime to the configured value for the function // handler property. var configuredFunctionHandler = Environment.GetEnvironmentVariable("_HANDLER"); // Native AOT Lambda functions are deployed as a native executable using the provided.al2 Lambda runtime. // The provided.al2 runtime ignores the function handler field and always looks for an executable called "bootstrap". // // As a convention this project template checks the value for the function handler field set in the // serverless template to determine which method should be registered with the Lambda runtime client // to respond to incoming Lambda events. This allows multiple Lambda functions be defined in the // same .NET project using the provided.al2 runtime. Func<APIGatewayProxyRequest, ILambdaContext, APIGatewayProxyResponse> handler = configuredFunctionHandler switch { nameof(GetFunctionHandler) => new Functions().GetFunctionHandler, nameof(PutFunctionHandler) => new Functions().PutFunctionHandler, _ => throw new Exception($"Unknown method to call for handler value {configuredFunctionHandler}") }; await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<LambdaFunctionJsonSerializerContext>()) .Build() .RunAsync(); } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway. /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the input parameter to the desired event type. When the event type /// is changed, the handler type registered in the main method needs to be updated and the LambdaFunctionJsonSerializerContext /// defined below will need the JsonSerializable updated. If the return type and event type are different then the /// LambdaFunctionJsonSerializerContext must have two JsonSerializable attributes, one for each type. /// // When using Native AOT extra testing with the deployed Lambda functions is required to ensure // the libraries used in the Lambda function work correctly with Native AOT. If a runtime // error occurs about missing types or methods the most likely solution will be to remove references to trim-unsafe // code or configure trimming options. This sample defaults to partial TrimMode because currently the AWS // SDK for .NET does not support trimming. This will result in a larger executable size, and still does not // guarantee runtime trimming errors won't be hit. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public APIGatewayProxyResponse GetFunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogInformation("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } /// <summary> /// A Lambda function to respond to HTTP PUT methods from API Gateway /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the input parameter to the desired event type. When the event type /// is changed the handler type registered in the main needs to be updated and the LambdaFunctionJsonSerializerContext /// defined below will need the JsonSerializable updated. If the return type and event type are different then the /// LambdaFunctionJsonSerializerContext must have two JsonSerializable attributes, one for each type. /// // When using Native AOT extra testing with the deployed Lambda functions is required to ensure // the libraries used in the Lambda function work correctly with Native AOT. If a runtime // error occurs about missing types or methods the most likely solution will be to remove references to trim-unsafe // code or configure trimming options. This sample defaults to partial TrimMode because currently the AWS // SDK for .NET does not support trimming. This will result in a larger executable size, and still does not // guarantee runtime trimming errors won't be hit. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public APIGatewayProxyResponse PutFunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogInformation("Put Request"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Processed PUT request", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } /// <summary> /// This class is used to register the input event and return type for the FunctionHandler method with the System.Text.Json source generator. /// There must be a JsonSerializable attribute for each type used as the input and return type or a runtime error will occur /// from the JSON serializer unable to find the serialization information for unknown types. /// </summary> [JsonSerializable(typeof(APIGatewayProxyRequest))] [JsonSerializable(typeof(APIGatewayProxyResponse))] public partial class LambdaFunctionJsonSerializerContext : JsonSerializerContext { // By using this partial class derived from JsonSerializerContext, we can generate reflection free JSON Serializer code at compile time // which can deserialize our class and properties. However, we must attribute this class to tell it what types to generate serialization code for. // See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-source-generation }
123
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class FunctionsTest { [Fact] public void TestGetMethod() { TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.GetFunctionHandler(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello AWS Serverless", response.Body); } }
27
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using AWS.Lambda.Powertools.Logging; using AWS.Lambda.Powertools.Metrics; using AWS.Lambda.Powertools.Tracing; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; /// <summary> /// Learn more about Powertools for AWS Lambda (.NET) at https://awslabs.github.io/aws-lambda-powertools-dotnet/ /// Powertools for AWS Lambda (.NET) Logging: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/logging/ /// Powertools for AWS Lambda (.NET) Tracing: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/tracing/ /// Powertools for AWS Lambda (.NET) Metrics: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/metrics/ /// Metrics Namespace and Service can be defined through Environment Variables https://awslabs.github.io/aws-lambda-powertools-dotnet/core/metrics/#getting-started /// </summary> 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> [Logging(LogEvent = true)] [Tracing] public string FunctionHandler(string input, ILambdaContext context) { var upperCaseString = UpperCaseString(input); Logger.LogInformation($"Uppercase of '{input}' is {upperCaseString}"); return upperCaseString; } [Metrics(CaptureColdStart = true)] [Tracing(SegmentName = "UpperCaseString Method")] private static string UpperCaseString(string input) { try { Metrics.AddMetric("UpperCaseString_Invocations", 1, MetricUnit.Count); return input.ToUpper(); } catch (Exception ex) { Logger.LogError(ex); throw; } } }
55
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestToUpperFunction() { Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE", "AWSLambdaPowertools"); // 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); } }
22
aws-lambda-dotnet
aws
C#
using System.Net; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using AWS.Lambda.Powertools.Logging; using AWS.Lambda.Powertools.Metrics; using AWS.Lambda.Powertools.Tracing; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; /// <summary> /// Learn more about Powertools for AWS Lambda (.NET) at https://awslabs.github.io/aws-lambda-powertools-dotnet/ /// Powertools for AWS Lambda (.NET) Logging: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/logging/ /// Powertools for AWS Lambda (.NET) Tracing: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/tracing/ /// Powertools for AWS Lambda (.NET) Metrics: https://awslabs.github.io/aws-lambda-powertools-dotnet/core/metrics/ /// </summary> public class Functions { /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> [Logging(LogEvent = true, CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest)] [Metrics(CaptureColdStart = true)] [Tracing(CaptureMode = TracingCaptureMode.ResponseAndError)] public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { Logger.LogInformation("Get Request"); var greeting = GetGreeting(); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = greeting, Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } [Tracing(SegmentName = "GetGreeting Method")] private static string GetGreeting() { Metrics.AddMetric("GetGreeting_Invocations", 1, MetricUnit.Count); return "Hello Powertools for AWS Lambda (.NET)"; } }
52
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.APIGatewayEvents; namespace BlueprintBaseName._1.Tests; public class FunctionTest { public FunctionTest() { } [Fact] public void TestGetMethod() { Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE", "AWSLambdaPowertools"); TestLambdaContext context; APIGatewayProxyRequest request; APIGatewayProxyResponse response; Functions functions = new Functions(); request = new APIGatewayProxyRequest(); context = new TestLambdaContext(); response = functions.Get(request, context); Assert.Equal(200, response.StatusCode); Assert.Equal("Hello Powertools for AWS Lambda (.NET)", response.Body); } }
32
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.ApplicationLoadBalancerEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// Lambda function handler to respond to events coming from an Application Load Balancer. /// /// Note: If "Multi value headers" is disabled on the ELB Target Group then use the Headers and QueryStringParameters properties /// on the ApplicationLoadBalancerRequest and ApplicationLoadBalancerResponse objects. If "Multi value headers" is enabled then /// use MultiValueHeaders and MultiValueQueryStringParameters properties. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public ApplicationLoadBalancerResponse FunctionHandler(ApplicationLoadBalancerRequest request, ILambdaContext context) { var response = new ApplicationLoadBalancerResponse { StatusCode = 200, StatusDescription = "200 OK", IsBase64Encoded = false }; // If "Multi value headers" is enabled for the ELB Target Group then use the "response.MultiValueHeaders" property instead of "response.Headers". response.Headers = new Dictionary<string, string> { {"Content-Type", "text/html; charset=utf-8" } }; response.Body = @" <html> <head> <title>Hello World!</title> <style> html, body { margin: 0; padding: 0; font-family: arial; font-weight: 700; font-size: 3em; text-align: center; } </style> </head> <body> <p>Hello World from Lambda</p> </body> </html> "; return response; } }
58
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.Core; using Amazon.Lambda.ApplicationLoadBalancerEvents; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestSampleFunction() { var function = new Function(); var context = new TestLambdaContext(); var request = new ApplicationLoadBalancerRequest(); var response = function.FunctionHandler(request, context); Assert.Equal(200, response.StatusCode); Assert.Contains("Hello World from Lambda", response.Body); } }
21
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; using Amazon.DynamoDBv2.Model; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records..."); foreach (var record in dynamoEvent.Records) { context.Logger.LogInformation($"Event ID: {record.EventID}"); context.Logger.LogInformation($"Event Name: {record.EventName}"); // TODO: Add business logic processing the record.Dynamodb object. } context.Logger.LogInformation("Stream processing complete."); } }
26
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.DynamoDBEvents; using Amazon.Lambda.TestUtilities; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestFunction() { DynamoDBEvent evnt = new DynamoDBEvent { Records = new List<DynamoDBEvent.DynamodbStreamRecord> { new DynamoDBEvent.DynamodbStreamRecord { AwsRegion = "us-west-2", Dynamodb = new StreamRecord { ApproximateCreationDateTime = DateTime.Now, Keys = new Dictionary<string, AttributeValue> { {"id", new AttributeValue { S = "MyId" } } }, NewImage = new Dictionary<string, AttributeValue> { { "field1", new AttributeValue { S = "NewValue" } }, { "field2", new AttributeValue { S = "AnotherNewValue" } } }, OldImage = new Dictionary<string, AttributeValue> { { "field1", new AttributeValue { S = "OldValue" } }, { "field2", new AttributeValue { S = "AnotherOldValue" } } }, StreamViewType = StreamViewType.NEW_AND_OLD_IMAGES } } } }; var context = new TestLambdaContext(); var function = new Function(); function.FunctionHandler(evnt, context); var testLogger = context.Logger as TestLambdaLogger; Assert.Contains("Stream processing complete", testLogger?.Buffer.ToString()); } }
47
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.KinesisFirehoseEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { public KinesisFirehoseResponse FunctionHandler(KinesisFirehoseEvent evnt, ILambdaContext context) { context.Logger.LogInformation($"InvocationId: {evnt.InvocationId}"); context.Logger.LogInformation($"DeliveryStreamArn: {evnt.DeliveryStreamArn}"); context.Logger.LogInformation($"Region: {evnt.Region}"); var response = new KinesisFirehoseResponse { Records = new List<KinesisFirehoseResponse.FirehoseRecord>() }; foreach (var record in evnt.Records) { context.Logger.LogInformation($"\tRecordId: {record.RecordId}"); context.Logger.LogInformation($"\t\tApproximateArrivalEpoch: {record.ApproximateArrivalEpoch}"); context.Logger.LogInformation($"\t\tApproximateArrivalTimestamp: {record.ApproximateArrivalTimestamp}"); context.Logger.LogInformation($"\t\tData: {record.DecodeData()}"); // Transform data: For example ToUpper the data var transformedRecord = new KinesisFirehoseResponse.FirehoseRecord { RecordId = record.RecordId, Result = KinesisFirehoseResponse.TRANSFORMED_STATE_OK }; transformedRecord.EncodeData(record.DecodeData().ToUpperInvariant()); response.Records.Add(transformedRecord); } return response; } }
43
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisFirehoseEvents; using Amazon.Lambda.TestUtilities; using Newtonsoft.Json; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestKinesisFirehoseEvent() { var json = File.ReadAllText("sample-event.json"); var kinesisEvent = JsonConvert.DeserializeObject<KinesisFirehoseEvent>(json); var function = new Function(); var context = new TestLambdaContext(); var kinesisResponse = function.FunctionHandler(kinesisEvent, context); Assert.Equal(1, kinesisResponse.Records.Count); Assert.Equal("49572672223665514422805246926656954630972486059535892482", kinesisResponse.Records[0].RecordId); Assert.Equal(KinesisFirehoseResponse.TRANSFORMED_STATE_OK, kinesisResponse.Records[0].Result); Assert.Equal("SEVMTE8gV09STEQ=", kinesisResponse.Records[0].Base64EncodedData); } }
33
aws-lambda-dotnet
aws
C#
using System.Text; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { public void FunctionHandler(KinesisEvent kinesisEvent, ILambdaContext context) { context.Logger.LogInformation($"Beginning to process {kinesisEvent.Records.Count} records..."); foreach (var record in kinesisEvent.Records) { context.Logger.LogInformation($"Event ID: {record.EventId}"); context.Logger.LogInformation($"Event Name: {record.EventName}"); string recordData = GetRecordContents(record.Kinesis); context.Logger.LogInformation($"Record Data:"); context.Logger.LogInformation(recordData); } context.Logger.LogInformation("Stream processing complete."); } private string GetRecordContents(KinesisEvent.Record streamRecord) { using (var reader = new StreamReader(streamRecord.Data, Encoding.ASCII)) { return reader.ReadToEnd(); } } }
37
aws-lambda-dotnet
aws
C#
using System.Text; using Xunit; using Amazon; using Amazon.Lambda.Core; using Amazon.Lambda.KinesisEvents; using Amazon.Lambda.TestUtilities; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public void TestFunction() { KinesisEvent evnt = new KinesisEvent { Records = new List<KinesisEvent.KinesisEventRecord> { new KinesisEvent.KinesisEventRecord { AwsRegion = "us-west-2", Kinesis = new KinesisEvent.Record { ApproximateArrivalTimestamp = DateTime.Now, Data = new MemoryStream(Encoding.UTF8.GetBytes("Hello World Kinesis Record")) } } } }; var context = new TestLambdaContext(); var function = new Function(); function.FunctionHandler(evnt, context); var testLogger = context.Logger as TestLambdaLogger; Assert.Contains("Stream processing complete", testLogger!.Buffer.ToString()); } }
42
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using Amazon.S3.Util; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { IAmazonS3 S3Client { get; set; } /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { S3Client = new AmazonS3Client(); } /// <summary> /// Constructs an instance with a preconfigured S3 client. This can be used for testing outside of the Lambda environment. /// </summary> /// <param name="s3Client"></param> public Function(IAmazonS3 s3Client) { this.S3Client = s3Client; } /// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(S3Event evnt, ILambdaContext context) { var eventRecords = evnt.Records ?? new List<S3Event.S3EventNotificationRecord>(); foreach (var record in eventRecords) { var s3Event = record.S3; if (s3Event == null) { continue; } try { var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key); context.Logger.LogInformation(response.Headers.ContentType); } catch (Exception e) { context.Logger.LogError($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogError(e.Message); context.Logger.LogError(e.StackTrace); throw; } } } }
66
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.Lambda.TestUtilities; using Amazon.S3; using Amazon.S3.Model; using Moq; using Xunit; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task TestS3EventLambdaFunction() { var mockS3Client = new Mock<IAmazonS3>(); var getObjectMetadataResponse = new GetObjectMetadataResponse(); getObjectMetadataResponse.Headers.ContentType = "text/plain"; mockS3Client .Setup(x => x.GetObjectMetadataAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(getObjectMetadataResponse)); // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = "s3-bucket" }, Object = new S3Event.S3ObjectEntity {Key = "text.txt" } } } } }; // Invoke the lambda function and confirm the content type was returned. ILambdaLogger testLambdaLogger = new TestLambdaLogger(); var testLambdaContext = new TestLambdaContext { Logger = testLambdaLogger }; var function = new Function(mockS3Client.Object); await function.FunctionHandler(s3Event, testLambdaContext); Assert.Equal("text/plain", ((TestLambdaLogger)testLambdaLogger).Buffer.ToString().Trim()); } }
52
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.S3Events; using Amazon.S3; using Amazon.S3.Util; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { IAmazonS3 S3Client { get; set; } /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { S3Client = new AmazonS3Client(); } /// <summary> /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment. /// </summary> /// <param name="s3Client"></param> public Function(IAmazonS3 s3Client) { this.S3Client = s3Client; } /// <summary> /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task<string?> FunctionHandler(S3Event evnt, ILambdaContext context) { var s3Event = evnt.Records?[0].S3; if(s3Event == null) { return null; } try { var response = await this.S3Client.GetObjectMetadataAsync(s3Event.Bucket.Name, s3Event.Object.Key); return response.Headers.ContentType; } catch(Exception e) { context.Logger.LogInformation($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function."); context.Logger.LogInformation(e.Message); context.Logger.LogInformation(e.StackTrace); throw; } } }
62
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda; using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.S3Events; using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System.Collections.Generic; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task TestS3EventLambdaFunction() { IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USWest2); var bucketName = "lambda-BlueprintBaseName.1-".ToLower() + DateTime.Now.Ticks; var key = "text.txt"; // Create a bucket an object to setup a test data. await s3Client.PutBucketAsync(bucketName); try { await s3Client.PutObjectAsync(new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "sample data" }); // Setup the S3 event object that S3 notifications would create with the fields used by the Lambda function. var s3Event = new S3Event { Records = new List<S3Event.S3EventNotificationRecord> { new S3Event.S3EventNotificationRecord { S3 = new S3Event.S3Entity { Bucket = new S3Event.S3BucketEntity {Name = bucketName }, Object = new S3Event.S3ObjectEntity {Key = key } } } } }; // Invoke the lambda function and confirm the content type was returned. var function = new Function(s3Client); var contentType = await function.FunctionHandler(s3Event,new TestLambdaContext()); Assert.Equal("text/plain", contentType); } finally { // Clean up the test data await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } }
65
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SNS event object and can be used /// to respond to SNS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach(var record in evnt.Records) { await ProcessRecordAsync(record, context); } } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }
45
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SNSEvents; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var snsEvent = new SNSEvent { Records = new List<SNSEvent.SNSRecord> { new SNSEvent.SNSRecord { Sns = new SNSEvent.SNSMessage() { Message = "foobar" } } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(snsEvent, context); Assert.Contains("Processed record foobar", logger.Buffer.ToString()); } }
37
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace BlueprintBaseName._1; public class Function { /// <summary> /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the /// region the Lambda function is executed in. /// </summary> public Function() { } /// <summary> /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used /// to respond to SQS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach(var message in evnt.Records) { await ProcessMessageAsync(message, context); } } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } }
45
aws-lambda-dotnet
aws
C#
using Xunit; using Amazon.Lambda.TestUtilities; using Amazon.Lambda.SQSEvents; namespace BlueprintBaseName._1.Tests; public class FunctionTest { [Fact] public async Task TestSQSEventLambdaFunction() { var sqsEvent = new SQSEvent { Records = new List<SQSEvent.SQSMessage> { new SQSEvent.SQSMessage { Body = "foobar" } } }; var logger = new TestLambdaLogger(); var context = new TestLambdaContext { Logger = logger }; var function = new Function(); await function.FunctionHandler(sqsEvent, context); Assert.Contains("Processed message foobar", logger.Buffer.ToString()); } }
34
aws-lambda-dotnet
aws
C#
namespace BlueprintBaseName._1; /// <summary> /// The state passed between the step function executions. /// </summary> public class State { /// <summary> /// Input value when starting the execution /// </summary> public string? Name { get; set; } /// <summary> /// The message built through the step function execution. /// </summary> public string? Message { get; set; } /// <summary> /// The number of seconds to wait between calling the Salutations task and Greeting task. /// </summary> public int WaitInSeconds { get; set; } }
22