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.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
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;
}
}
}
| 22 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlueprintBaseName._1.Pages
{
public class HelpModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
}
}
}
| 19 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlueprintBaseName._1.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
| 18 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
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 JsonConvert.SerializeObject(order, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
}
protected FlowerOrder DeserializeReservation(string json)
{
return JsonConvert.DeserializeObject<FlowerOrder>(json);
}
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
}
};
}
}
}
| 99 |
aws-lambda-dotnet | aws | C# | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
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
}
}
}
| 44 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization;
using Amazon.Lambda.LexEvents;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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.Json.JsonSerializer))]
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);
}
}
}
| 49 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
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);
}
}
| 23 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
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;
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.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)
{
bool isFlowerTypeValid = Enum.IsDefined(typeof(FlowerTypes), flowerTypeString.ToUpper());
if (Enum.TryParse(typeof(FlowerTypes), flowerTypeString, true, out object flowerType))
{
_chosenFlowerType = (FlowerTypes)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));
}
}
}
}
| 174 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
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());
}
}
}
| 38 |
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 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);
}
}
}
| 52 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.Json;
using System;
using System.Threading.Tasks;
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> func = FunctionHandler;
using(var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new JsonSerializer()))
using(var bootstrap = new LambdaBootstrap(handlerWrapper))
{
await bootstrap.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();
}
}
}
| 41 |
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
{
[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);
}
}
}
| 28 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
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.Json.JsonSerializer))]
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;
}
}
}
| 147 |
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 Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.Rekognition;
using BlueprintBaseName._1;
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);
}
}
}
}
| 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
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.Json.JsonSerializer))]
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;
}
}
}
| 147 |
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 Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.Rekognition;
using BlueprintBaseName._1;
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);
}
}
}
}
| 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
namespace BlueprintBaseName._1
{
public class Blog
{
[DynamoDBHashKey]
public string Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public DateTime CreatedTimestamp { get; set; }
}
}
| 18 |
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;
using Amazon.Lambda.APIGatewayEvents;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Newtonsoft.Json;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace BlueprintBaseName._1
{
public class Functions
{
// This const is the name of the environment variable that the serverless.template will use to set
// the name of the DynamoDB table used to store blog posts.
const string TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP = "BlogTable";
public const string ID_QUERY_STRING_NAME = "Id";
IDynamoDBContext DDBContext { get; set; }
/// <summary>
/// Default constructor that Lambda will invoke.
/// </summary>
public Functions()
{
// Check to see if a table name was passed in through environment variables and if so
// add the table mapping.
var tableName = System.Environment.GetEnvironmentVariable(TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP);
if(!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Blog)] = new Amazon.Util.TypeMapping(typeof(Blog), tableName);
}
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
this.DDBContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}
/// <summary>
/// Constructor used for testing passing in a preconfigured DynamoDB client.
/// </summary>
/// <param name="ddbClient"></param>
/// <param name="tableName"></param>
public Functions(IAmazonDynamoDB ddbClient, string tableName)
{
if (!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Blog)] = new Amazon.Util.TypeMapping(typeof(Blog), tableName);
}
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
this.DDBContext = new DynamoDBContext(ddbClient, config);
}
/// <summary>
/// A Lambda function that returns back a page worth of blog posts.
/// </summary>
/// <param name="request"></param>
/// <returns>The list of blogs</returns>
public async Task<APIGatewayProxyResponse> GetBlogsAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
context.Logger.LogLine("Getting blogs");
var search = this.DDBContext.ScanAsync<Blog>(null);
var page = await search.GetNextSetAsync();
context.Logger.LogLine($"Found {page.Count} blogs");
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(page),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;
}
/// <summary>
/// A Lambda function that returns the blog identified by blogId
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<APIGatewayProxyResponse> GetBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
string blogId = null;
if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.PathParameters[ID_QUERY_STRING_NAME];
else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
if (string.IsNullOrEmpty(blogId))
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.BadRequest,
Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
};
}
context.Logger.LogLine($"Getting blog {blogId}");
var blog = await DDBContext.LoadAsync<Blog>(blogId);
context.Logger.LogLine($"Found blog: {blog != null}");
if (blog == null)
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.NotFound
};
}
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(blog),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;
}
/// <summary>
/// A Lambda function that adds a blog post.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<APIGatewayProxyResponse> AddBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
var blog = JsonConvert.DeserializeObject<Blog>(request?.Body);
blog.Id = Guid.NewGuid().ToString();
blog.CreatedTimestamp = DateTime.Now;
context.Logger.LogLine($"Saving blog with id {blog.Id}");
await DDBContext.SaveAsync<Blog>(blog);
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = blog.Id.ToString(),
Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
};
return response;
}
/// <summary>
/// A Lambda function that removes a blog post from the DynamoDB table.
/// </summary>
/// <param name="request"></param>
public async Task<APIGatewayProxyResponse> RemoveBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
string blogId = null;
if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.PathParameters[ID_QUERY_STRING_NAME];
else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
if (string.IsNullOrEmpty(blogId))
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.BadRequest,
Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
};
}
context.Logger.LogLine($"Deleting blog with id {blogId}");
await this.DDBContext.DeleteAsync<Blog>(blogId);
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK
};
}
}
}
| 182 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Newtonsoft.Json;
using Xunit;
namespace BlueprintBaseName._1.Tests
{
public class FunctionTest : IDisposable
{
string TableName { get; }
IAmazonDynamoDB DDBClient { get; }
public FunctionTest()
{
this.TableName = "BlueprintBaseName-Blogs-" + DateTime.Now.Ticks;
this.DDBClient = new AmazonDynamoDBClient(RegionEndpoint.USWest2);
SetupTableAsync().Wait();
}
[Fact]
public async Task BlogTestAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new blog post
Blog myBlog = new Blog();
myBlog.Name = "The awesome post";
myBlog.Content = "Content for the awesome blog";
request = new APIGatewayProxyRequest
{
Body = JsonConvert.SerializeObject(myBlog)
};
context = new TestLambdaContext();
response = await functions.AddBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
var blogId = response.Body;
// Confirm we can get the blog post back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.GetBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
Blog readBlog = JsonConvert.DeserializeObject<Blog>(response.Body);
Assert.Equal(myBlog.Name, readBlog.Name);
Assert.Equal(myBlog.Content, readBlog.Content);
// List the blog posts
request = new APIGatewayProxyRequest
{
};
context = new TestLambdaContext();
response = await functions.GetBlogsAsync(request, context);
Assert.Equal(200, response.StatusCode);
Blog[] blogPosts = JsonConvert.DeserializeObject<Blog[]>(response.Body);
Assert.Single(blogPosts);
Assert.Equal(myBlog.Name, blogPosts[0].Name);
Assert.Equal(myBlog.Content, blogPosts[0].Content);
// Delete the blog post
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.RemoveBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
// Make sure the post was deleted.
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.GetBlogAsync(request, context);
Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
}
/// <summary>
/// Create the DynamoDB table for testing. This table is deleted as part of the object dispose method.
/// </summary>
/// <returns></returns>
private async Task SetupTableAsync()
{
CreateTableRequest request = new CreateTableRequest
{
TableName = this.TableName,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 2,
WriteCapacityUnits = 2
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
KeyType = KeyType.HASH,
AttributeName = Functions.ID_QUERY_STRING_NAME
}
},
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = Functions.ID_QUERY_STRING_NAME,
AttributeType = ScalarAttributeType.S
}
}
};
await this.DDBClient.CreateTableAsync(request);
var describeRequest = new DescribeTableRequest { TableName = this.TableName };
DescribeTableResponse response = null;
do
{
Thread.Sleep(1000);
response = await this.DDBClient.DescribeTableAsync(describeRequest);
} while (response.Table.TableStatus != TableStatus.ACTIVE);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.DDBClient.DeleteTableAsync(this.TableName).Wait();
this.DDBClient.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 179 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace 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();
}
}
}
| 28 |
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
{
[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);
}
}
}
| 29 |
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;
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.Json.JsonSerializer))]
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.LogLine("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;
}
}
}
| 45 |
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 Amazon.Lambda.APIGatewayEvents;
using BlueprintBaseName._1;
namespace BlueprintBaseName._1.Tests
{
public class FunctionTest
{
public FunctionTest()
{
}
[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);
}
}
}
| 39 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
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 JsonConvert.SerializeObject(reservation, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
}
protected Reservation DeserializeReservation(string json)
{
return JsonConvert.DeserializeObject<Reservation>(json);
}
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
}
};
}
}
}
| 102 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
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.LogLine($"Has required fields: {reservation.HasRequiredCarFields}, Has valid values {validateResult.IsValid}");
if(!validateResult.IsValid)
{
context.Logger.LogLine($"Slot {validateResult.ViolationSlot} is invalid: {validateResult.Message?.Content}");
}
if (reservation.HasRequiredCarFields && validateResult.IsValid)
{
var price = GeneratePrice(reservation);
context.Logger.LogLine($"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.LogLine($"Book car at = {SerializeReservation(reservation)}");
if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE))
{
context.Logger.LogLine($"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 = int.Parse(reservation.DriverAge) < 25 ? 1.1 : 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));
}
}
}
| 330 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
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.LogLine($"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.LogLine($"Book hotel at = {SerializeReservation(reservation)}");
if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE))
{
context.Logger.LogLine($"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));
}
}
}
| 172 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization;
using Amazon.Lambda.LexEvents;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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.Json.JsonSerializer))]
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);
}
}
}
| 52 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
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);
}
}
| 23 |
aws-lambda-dotnet | aws | C# | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
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
}
}
| 59 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
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());
}
}
}
| 38 |
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.Json.JsonSerializer))]
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 Newtonsoft.Json;
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.Json.JsonSerializer))]
namespace BlueprintBaseName._1
{
public class Function
{
private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();
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}");
string streamRecordJson = SerializeStreamRecord(record.Dynamodb);
context.Logger.LogLine($"DynamoDB Record:");
context.Logger.LogLine(streamRecordJson );
}
context.Logger.LogLine("Stream processing complete.");
}
private string SerializeStreamRecord(StreamRecord streamRecord)
{
using (var writer = new StringWriter())
{
_jsonSerializer.Serialize(writer, streamRecord);
return writer.ToString();
}
}
}
} | 46 |
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Json.JsonSerializer))]
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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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)
{
}
}
}
| 53 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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>();
});
}
}
| 27 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BlueprintBaseName._1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; private set; }
// 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");
});
});
}
}
}
| 57 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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)
{
}
}
}
| 45 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
using Amazon.Lambda.Core;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using BlueprintBaseName._1;
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]);
}
}
}
| 44 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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)
{
}
}
}
| 53 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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>();
});
}
}
| 27 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BlueprintBaseName._1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration { get; private set; }
// 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");
});
});
}
}
}
| 57 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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)
{
}
}
}
| 45 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
using Amazon.Lambda.Core;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using BlueprintBaseName._1;
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]);
}
}
}
| 44 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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)
{
}
}
}
| 53 |
aws-lambda-dotnet | aws | C# | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
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>();
});
}
}
| 24 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
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();
});
}
}
}
| 59 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
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;
}
}
}
| 22 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlueprintBaseName._1.Pages
{
public class HelpModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
}
}
}
| 19 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlueprintBaseName._1.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}
| 18 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
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
{
IgnoreNullValues = true
});
}
protected FlowerOrder DeserializeReservation(string json)
{
return JsonSerializer.Deserialize<FlowerOrder>(json);
}
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
}
};
}
}
}
| 99 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
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
}
}
}
| 44 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
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;
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);
}
}
}
| 47 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
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);
}
}
| 23 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
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;
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.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)
{
bool isFlowerTypeValid = Enum.IsDefined(typeof(FlowerTypes), flowerTypeString.ToUpper());
if (Enum.TryParse(typeof(FlowerTypes), flowerTypeString, true, out object flowerType))
{
_chosenFlowerType = (FlowerTypes)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));
}
}
}
}
| 174 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
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());
}
}
}
| 38 |
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 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);
}
}
}
| 52 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
using System;
using System.Threading.Tasks;
// This project specifies the serializer used to convert Lambda event into .NET classes in the project's main
// main function. This assembly register a serializer for use when the project is being debugged using the
// AWS .NET Mock Lambda Test Tool.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
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> func = FunctionHandler;
using(var handlerWrapper = HandlerWrapper.GetHandlerWrapper(func, new DefaultLambdaJsonSerializer()))
using(var bootstrap = new LambdaBootstrap(handlerWrapper))
{
await bootstrap.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();
}
}
}
| 46 |
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
{
[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);
}
}
}
| 28 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
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;
}
}
}
| 147 |
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 Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.Rekognition;
using BlueprintBaseName._1;
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);
}
}
}
}
| 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
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;
}
}
}
| 147 |
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 Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;
using Amazon.Rekognition;
using BlueprintBaseName._1;
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);
}
}
}
}
| 80 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
namespace BlueprintBaseName._1
{
public class Blog
{
[DynamoDBHashKey]
public string Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public DateTime CreatedTimestamp { get; set; }
}
}
| 18 |
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;
using Amazon.Lambda.APIGatewayEvents;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Newtonsoft.Json;
// 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
{
// This const is the name of the environment variable that the serverless.template will use to set
// the name of the DynamoDB table used to store blog posts.
const string TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP = "BlogTable";
public const string ID_QUERY_STRING_NAME = "Id";
IDynamoDBContext DDBContext { get; set; }
/// <summary>
/// Default constructor that Lambda will invoke.
/// </summary>
public Functions()
{
// Check to see if a table name was passed in through environment variables and if so
// add the table mapping.
var tableName = System.Environment.GetEnvironmentVariable(TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP);
if(!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Blog)] = new Amazon.Util.TypeMapping(typeof(Blog), tableName);
}
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
this.DDBContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}
/// <summary>
/// Constructor used for testing passing in a preconfigured DynamoDB client.
/// </summary>
/// <param name="ddbClient"></param>
/// <param name="tableName"></param>
public Functions(IAmazonDynamoDB ddbClient, string tableName)
{
if (!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Blog)] = new Amazon.Util.TypeMapping(typeof(Blog), tableName);
}
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
this.DDBContext = new DynamoDBContext(ddbClient, config);
}
/// <summary>
/// A Lambda function that returns back a page worth of blog posts.
/// </summary>
/// <param name="request"></param>
/// <returns>The list of blogs</returns>
public async Task<APIGatewayProxyResponse> GetBlogsAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
context.Logger.LogLine("Getting blogs");
var search = this.DDBContext.ScanAsync<Blog>(null);
var page = await search.GetNextSetAsync();
context.Logger.LogLine($"Found {page.Count} blogs");
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(page),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;
}
/// <summary>
/// A Lambda function that returns the blog identified by blogId
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<APIGatewayProxyResponse> GetBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
string blogId = null;
if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.PathParameters[ID_QUERY_STRING_NAME];
else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
if (string.IsNullOrEmpty(blogId))
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.BadRequest,
Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
};
}
context.Logger.LogLine($"Getting blog {blogId}");
var blog = await DDBContext.LoadAsync<Blog>(blogId);
context.Logger.LogLine($"Found blog: {blog != null}");
if (blog == null)
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.NotFound
};
}
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(blog),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;
}
/// <summary>
/// A Lambda function that adds a blog post.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<APIGatewayProxyResponse> AddBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
var blog = JsonConvert.DeserializeObject<Blog>(request?.Body);
blog.Id = Guid.NewGuid().ToString();
blog.CreatedTimestamp = DateTime.Now;
context.Logger.LogLine($"Saving blog with id {blog.Id}");
await DDBContext.SaveAsync<Blog>(blog);
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = blog.Id.ToString(),
Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
};
return response;
}
/// <summary>
/// A Lambda function that removes a blog post from the DynamoDB table.
/// </summary>
/// <param name="request"></param>
public async Task<APIGatewayProxyResponse> RemoveBlogAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
string blogId = null;
if (request.PathParameters != null && request.PathParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.PathParameters[ID_QUERY_STRING_NAME];
else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(ID_QUERY_STRING_NAME))
blogId = request.QueryStringParameters[ID_QUERY_STRING_NAME];
if (string.IsNullOrEmpty(blogId))
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.BadRequest,
Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
};
}
context.Logger.LogLine($"Deleting blog with id {blogId}");
await this.DDBContext.DeleteAsync<Blog>(blogId);
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK
};
}
}
}
| 182 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.TestUtilities;
using Amazon.Lambda.APIGatewayEvents;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Newtonsoft.Json;
using Xunit;
namespace BlueprintBaseName._1.Tests
{
public class FunctionTest : IDisposable
{
string TableName { get; }
IAmazonDynamoDB DDBClient { get; }
public FunctionTest()
{
this.TableName = "BlueprintBaseName-Blogs-" + DateTime.Now.Ticks;
this.DDBClient = new AmazonDynamoDBClient(RegionEndpoint.USWest2);
SetupTableAsync().Wait();
}
[Fact]
public async Task BlogTestAsync()
{
TestLambdaContext context;
APIGatewayProxyRequest request;
APIGatewayProxyResponse response;
Functions functions = new Functions(this.DDBClient, this.TableName);
// Add a new blog post
Blog myBlog = new Blog();
myBlog.Name = "The awesome post";
myBlog.Content = "Content for the awesome blog";
request = new APIGatewayProxyRequest
{
Body = JsonConvert.SerializeObject(myBlog)
};
context = new TestLambdaContext();
response = await functions.AddBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
var blogId = response.Body;
// Confirm we can get the blog post back out
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.GetBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
Blog readBlog = JsonConvert.DeserializeObject<Blog>(response.Body);
Assert.Equal(myBlog.Name, readBlog.Name);
Assert.Equal(myBlog.Content, readBlog.Content);
// List the blog posts
request = new APIGatewayProxyRequest
{
};
context = new TestLambdaContext();
response = await functions.GetBlogsAsync(request, context);
Assert.Equal(200, response.StatusCode);
Blog[] blogPosts = JsonConvert.DeserializeObject<Blog[]>(response.Body);
Assert.Single(blogPosts);
Assert.Equal(myBlog.Name, blogPosts[0].Name);
Assert.Equal(myBlog.Content, blogPosts[0].Content);
// Delete the blog post
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.RemoveBlogAsync(request, context);
Assert.Equal(200, response.StatusCode);
// Make sure the post was deleted.
request = new APIGatewayProxyRequest
{
PathParameters = new Dictionary<string, string> { { Functions.ID_QUERY_STRING_NAME, blogId } }
};
context = new TestLambdaContext();
response = await functions.GetBlogAsync(request, context);
Assert.Equal((int)HttpStatusCode.NotFound, response.StatusCode);
}
/// <summary>
/// Create the DynamoDB table for testing. This table is deleted as part of the object dispose method.
/// </summary>
/// <returns></returns>
private async Task SetupTableAsync()
{
CreateTableRequest request = new CreateTableRequest
{
TableName = this.TableName,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 2,
WriteCapacityUnits = 2
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
KeyType = KeyType.HASH,
AttributeName = Functions.ID_QUERY_STRING_NAME
}
},
AttributeDefinitions = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = Functions.ID_QUERY_STRING_NAME,
AttributeType = ScalarAttributeType.S
}
}
};
await this.DDBClient.CreateTableAsync(request);
var describeRequest = new DescribeTableRequest { TableName = this.TableName };
DescribeTableResponse response = null;
do
{
Thread.Sleep(1000);
response = await this.DDBClient.DescribeTableAsync(describeRequest);
} while (response.Table.TableStatus != TableStatus.ACTIVE);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.DDBClient.DeleteTableAsync(this.TableName).Wait();
this.DDBClient.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 179 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.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();
}
}
}
| 28 |
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
{
[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);
}
}
}
| 29 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.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);
}
| 30 |
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
{
[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);
}
}
}
| 30 |
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;
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.LogLine("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;
}
}
}
| 45 |
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 Amazon.Lambda.APIGatewayEvents;
using BlueprintBaseName._1;
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);
}
}
}
| 39 |
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;
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.LogLine("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;
}
}
}
| 45 |
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 Amazon.Lambda.APIGatewayEvents;
using BlueprintBaseName._1;
namespace BlueprintBaseName._1.Tests
{
public class FunctionTest
{
public FunctionTest()
{
}
[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);
}
}
}
| 39 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
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 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
{
IgnoreNullValues = true
});
}
protected Reservation DeserializeReservation(string json)
{
return JsonSerializer.Deserialize<Reservation>(json);
}
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
}
};
}
}
}
| 103 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
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.LogLine($"Has required fields: {reservation.HasRequiredCarFields}, Has valid values {validateResult.IsValid}");
if(!validateResult.IsValid)
{
context.Logger.LogLine($"Slot {validateResult.ViolationSlot} is invalid: {validateResult.Message?.Content}");
}
if (reservation.HasRequiredCarFields && validateResult.IsValid)
{
var price = GeneratePrice(reservation);
context.Logger.LogLine($"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.LogLine($"Book car at = {SerializeReservation(reservation)}");
if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE))
{
context.Logger.LogLine($"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 = int.Parse(reservation.DriverAge) < 25 ? 1.1 : 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));
}
}
}
| 330 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
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.LogLine($"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.LogLine($"Book hotel at = {SerializeReservation(reservation)}");
if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE))
{
context.Logger.LogLine($"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));
}
}
}
| 172 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
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);
}
}
}
| 50 |
aws-lambda-dotnet | aws | C# | using Amazon.Lambda.Core;
using Amazon.Lambda.LexEvents;
using System;
using System.Collections.Generic;
using System.Text;
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);
}
}
| 23 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Text;
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
}
}
| 59 |
aws-lambda-dotnet | aws | C# | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
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());
}
}
}
| 38 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.