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 Xunit; namespace TestServerlessApp.IntegrationTests { [CollectionDefinition("Integration Tests")] public class IntegrationTestContextFixtureCollection : ICollectionFixture<IntegrationTestContextFixture> { } }
9
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace TestServerlessApp.IntegrationTests { [Collection("Integration Tests")] public class SimpleCalculator { private readonly IntegrationTestContextFixture _fixture; public SimpleCalculator(IntegrationTestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task Add_FromQuery_ReturnsIntAsString() { var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Add?x=2&y=4"); response.EnsureSuccessStatusCode(); Assert.Equal("6", await response.Content.ReadAsStringAsync()); } [Fact] public async Task Subtract_FromHeader_ReturnsIntAsString() { var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Subtract"), Headers = {{ "x", "10" }, {"y", "2"}} }; var response = await _fixture.HttpClient.SendAsync(httpRequestMessage); response.EnsureSuccessStatusCode(); Assert.Equal("8", await response.Content.ReadAsStringAsync()); } [Fact] public async Task Multiply_FromPath_ReturnsIntAsString() { var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Multiply/2/10"); response.EnsureSuccessStatusCode(); Assert.Equal("20", await response.Content.ReadAsStringAsync()); } [Fact] public async Task DivideAsync_FromPath_ReturnsIntAsString() { var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/DivideAsync/50/5"); response.EnsureSuccessStatusCode(); Assert.Equal("10", await response.Content.ReadAsStringAsync()); } [Fact] public async Task Pi_NoPayload_ReturnsDoubleAsString() { var lambdaFunctionName = _fixture.LambdaFunctions.FirstOrDefault(x => string.Equals(x.LogicalId, "PI"))?.Name; Assert.False(string.IsNullOrEmpty(lambdaFunctionName)); var invokeResponse = await _fixture.LambdaHelper.InvokeFunctionAsync(lambdaFunctionName); Assert.Equal(200, invokeResponse.StatusCode); var responsePayload = await new StreamReader(invokeResponse.Payload).ReadToEndAsync(); Assert.Equal("3.141592653589793", responsePayload); } [Fact] public async Task Random_IntAsStringPayload_ReturnsRandomIntLessThanPayload() { var lambdaFunctionName = _fixture.LambdaFunctions.FirstOrDefault(x => string.Equals(x.LogicalId, "Random"))?.Name; Assert.False(string.IsNullOrEmpty(lambdaFunctionName)); var invokeResponse = await _fixture.LambdaHelper.InvokeFunctionAsync(lambdaFunctionName, "1000"); Assert.Equal(200, invokeResponse.StatusCode); var responsePayload = await new StreamReader(invokeResponse.Payload).ReadToEndAsync(); Assert.True(int.TryParse(responsePayload, out var result)); Assert.True(result < 1000); } [Fact] public async Task Randoms_JsonPayload_ReturnsListOfInt() { var lambdaFunctionName = _fixture.LambdaFunctions.FirstOrDefault(x => string.Equals(x.LogicalId, "Randoms"))?.Name; Assert.False(string.IsNullOrEmpty(lambdaFunctionName)); var invokeResponse = await _fixture.LambdaHelper.InvokeFunctionAsync(lambdaFunctionName, "{\"count\": 5, \"maxValue\": 1000}"); Assert.Equal(200, invokeResponse.StatusCode); var responsePayload = await new StreamReader(invokeResponse.Payload).ReadToEndAsync(); var responseArray = responsePayload.Trim(new[] {'[', ']'}).Split(',').Select(int.Parse).ToList(); Assert.Equal(5, responseArray.Count); Assert.True(responseArray.All(x => x < 1000)); } } }
94
aws-lambda-dotnet
aws
C#
using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; namespace TestServerlessApp.IntegrationTests.Helpers { public class CloudFormationHelper { private readonly IAmazonCloudFormation _cloudFormationClient; public CloudFormationHelper(IAmazonCloudFormation cloudFormationClient) { _cloudFormationClient = cloudFormationClient; } public async Task<StackStatus> GetStackStatusAsync(string stackName) { var stack = await GetStackAsync(stackName); return stack?.StackStatus; } public async Task<bool> IsDeletedAsync(string stackName) { var attemptCount = 0; const int maxAttempts = 5; while (attemptCount < maxAttempts) { attemptCount += 1; if (! await StackExistsAsync(stackName)) return true; await Task.Delay(StaticHelpers.GetWaitTime(attemptCount)); } return false; } public async Task DeleteStackAsync(string stackName) { if (!await StackExistsAsync(stackName)) return; await _cloudFormationClient.DeleteStackAsync(new DeleteStackRequest {StackName = stackName}); } public async Task<string> GetOutputValueAsync(string stackName, string outputKey) { var stack = await GetStackAsync(stackName); return stack?.Outputs.FirstOrDefault(x => string.Equals(x.OutputKey, outputKey))?.OutputValue; } private async Task<Stack> GetStackAsync(string stackName) { if (!await StackExistsAsync(stackName)) return null; var response = await _cloudFormationClient.DescribeStacksAsync(new DescribeStacksRequest {StackName = stackName}); return response.Stacks.Count == 0 ? null : response.Stacks[0]; } private async Task<bool> StackExistsAsync(string stackName) { try { await _cloudFormationClient.DescribeStacksAsync(new DescribeStacksRequest {StackName = stackName}); } catch (AmazonCloudFormationException exception) when (exception.ErrorCode.Equals("ValidationError") && exception.Message.Equals($"Stack with id {stackName} does not exist")) { return false; } return true; } } }
75
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; namespace TestServerlessApp.IntegrationTests.Helpers { public class CloudWatchHelper { private readonly IAmazonCloudWatchLogs _cloudWatchlogsClient; public CloudWatchHelper(IAmazonCloudWatchLogs cloudWatchlogsClient) { _cloudWatchlogsClient = cloudWatchlogsClient; } public string GetLogGroupName(string lambdaFunctionName) => $"/aws/lambda/{lambdaFunctionName}"; public async Task<bool> MessageExistsInRecentLogEventsAsync(string message, string logGroupName, string logGroupNamePrefix) { var attemptCount = 0; const int maxAttempts = 5; while (attemptCount < maxAttempts) { attemptCount += 1; var recentLogEvents = await GetRecentLogEventsAsync(logGroupName, logGroupNamePrefix); if (recentLogEvents.Any(x => x.Message.Contains(message))) return true; await Task.Delay(StaticHelpers.GetWaitTime(attemptCount)); } return false; } private async Task<List<OutputLogEvent>> GetRecentLogEventsAsync(string logGroupName, string logGroupNamePrefix) { var latestLogStreamName = await GetLatestLogStreamNameAsync(logGroupName, logGroupNamePrefix); var logEvents = await GetLogEventsAsync(logGroupName, latestLogStreamName); return logEvents; } private async Task<string> GetLatestLogStreamNameAsync(string logGroupName, string logGroupNamePrefix) { var attemptCount = 0; const int maxAttempts = 5; while (attemptCount < maxAttempts) { attemptCount += 1; if (await LogGroupExistsAsync(logGroupName, logGroupNamePrefix)) break; await Task.Delay(StaticHelpers.GetWaitTime(attemptCount)); } var response = await _cloudWatchlogsClient.DescribeLogStreamsAsync( new DescribeLogStreamsRequest { LogGroupName = logGroupName, Descending = true, Limit = 1 }); return response.LogStreams.FirstOrDefault()?.LogStreamName; } private async Task<List<OutputLogEvent>> GetLogEventsAsync(string logGroupName, string logStreamName) { var response = await _cloudWatchlogsClient.GetLogEventsAsync( new GetLogEventsRequest { LogGroupName = logGroupName, LogStreamName = logStreamName, Limit = 10 }); return response.Events; } private async Task<bool> LogGroupExistsAsync(string logGroupName, string logGroupNamePrefix) { var response = await _cloudWatchlogsClient.DescribeLogGroupsAsync(new DescribeLogGroupsRequest{LogGroupNamePrefix = logGroupNamePrefix}); return response.LogGroups.Any(x => string.Equals(x.LogGroupName, logGroupName)); } } }
87
aws-lambda-dotnet
aws
C#
#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TestServerlessApp.IntegrationTests.Helpers { public static class CommandLineWrapper { public static async Task RunAsync(string command, string workingDirectory = "", bool redirectIo = true, CancellationToken cancelToken = default) { var processStartInfo = new ProcessStartInfo { FileName = GetSystemShell(), Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/c {command}" : $"-c \"{command}\"", RedirectStandardInput = redirectIo, RedirectStandardOutput = redirectIo, RedirectStandardError = redirectIo, UseShellExecute = false, CreateNoWindow = redirectIo, WorkingDirectory = workingDirectory }; var process = Process.Start(processStartInfo); if (null == process) throw new Exception("Process.Start failed to return a non-null process"); var sb = new StringBuilder(); DataReceivedEventHandler callback = (object sender, DataReceivedEventArgs e) => { sb.AppendLine(e.Data); Console.WriteLine(e.Data); }; if (redirectIo) { process.OutputDataReceived += callback; process.ErrorDataReceived += callback; process.BeginOutputReadLine(); process.BeginErrorReadLine(); } await process.WaitForExitAsync(cancelToken); var log = sb.ToString(); } private static string GetSystemShell() { if (TryGetEnvironmentVariable("COMSPEC", out var comspec)) return comspec!; if (TryGetEnvironmentVariable("SHELL", out var shell)) return shell!; // fall back to defaults return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/sh"; } private static bool TryGetEnvironmentVariable(string variable, out string? value) { value = Environment.GetEnvironmentVariable(variable); return !string.IsNullOrEmpty(value); } } }
71
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Lambda; using Amazon.Lambda.Model; namespace TestServerlessApp.IntegrationTests.Helpers { public class LambdaHelper { private readonly IAmazonLambda _lambdaClient; public LambdaHelper(IAmazonLambda lambdaClient) { _lambdaClient = lambdaClient; } public async Task<List<LambdaFunction>> FilterByCloudFormationStackAsync(string stackName) { const string stackNameKey = "aws:cloudformation:stack-name"; const string logicalIdKey = "aws:cloudformation:logical-id"; var lambdaFunctions = new List<LambdaFunction>(); var paginator = _lambdaClient.Paginators.ListFunctions(new ListFunctionsRequest()); await foreach (var function in paginator.Functions) { var tags = (await _lambdaClient.ListTagsAsync(new ListTagsRequest {Resource = function.FunctionArn})).Tags; if (tags.ContainsKey(stackNameKey) && string.Equals(tags[stackNameKey], stackName)) { var lambdaFunction = new LambdaFunction { LogicalId = tags[logicalIdKey], Name = function.FunctionName }; lambdaFunctions.Add(lambdaFunction); } } return lambdaFunctions; } public async Task<InvokeResponse> InvokeFunctionAsync(string functionName, string payload = null) { var request = new InvokeRequest {FunctionName = functionName}; if (!string.IsNullOrEmpty(payload)) request.Payload = payload; return await _lambdaClient.InvokeAsync(request); } public async Task WaitTillNotPending(List<string> functions) { foreach(var function in functions) { while(true) { var response = await _lambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest {FunctionName = function }); if(response.State == State.Pending) { await Task.Delay(1000); } else { break; } } } } } public class LambdaFunction { public string LogicalId { get; set; } public string Name { get; set; } } }
74
aws-lambda-dotnet
aws
C#
using System.Linq; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; namespace TestServerlessApp.IntegrationTests.Helpers { public class S3Helper { private readonly IAmazonS3 _s3Client; public S3Helper(IAmazonS3 s3Client) { _s3Client = s3Client; } public async Task DeleteBucketAsync(string bucketName) { if (!await BucketExistsAsync(bucketName)) return; var response = await _s3Client.ListObjectsAsync(new ListObjectsRequest{BucketName = bucketName}); foreach (var s3Object in response.S3Objects) { await _s3Client.DeleteObjectAsync(new DeleteObjectRequest {BucketName = bucketName, Key = s3Object.Key}); } await _s3Client.DeleteBucketAsync(new DeleteBucketRequest {BucketName = bucketName}); } public async Task<bool> BucketExistsAsync(string bucketName) { var response = await _s3Client.ListBucketsAsync(new ListBucketsRequest()); return response.Buckets.Any(x => x.BucketName.Equals(bucketName)); } } }
37
aws-lambda-dotnet
aws
C#
using System; namespace TestServerlessApp.IntegrationTests.Helpers { public static class StaticHelpers { public static TimeSpan GetWaitTime(int attemptCount) { var waitTime = Math.Pow(2, attemptCount) * 5; return TimeSpan.FromSeconds(waitTime); } } }
13
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer; namespace TestWebApp { public class ALBLambdaFunction : ApplicationLoadBalancerFunction<Startup> { } }
9
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer; namespace TestWebApp { public class ApiGatewayLambdaFunction : APIGatewayProxyFunction<Startup> { } }
9
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; #if !NETCOREAPP_2_1 namespace TestWebApp { public interface IMethodsCalled { bool InitHostBuilder { get; set; } bool InitHostWebBuilder { get; set; } } public class HostBuilderUsingGenericClass : APIGatewayProxyFunction<Startup>, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override void Init(IWebHostBuilder builder) { base.Init(builder); InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { base.Init(builder); InitHostBuilder = true; } } public class HostBuilderOverridingInit : APIGatewayProxyFunction, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override void Init(IWebHostBuilder builder) { builder.UseStartup<Startup>(); InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { base.Init(builder); InitHostBuilder = true; } } public class HostBuilderOverridingCreateWebHostBuilder : APIGatewayProxyFunction, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override IWebHostBuilder CreateWebHostBuilder() { return base.CreateWebHostBuilder(); } protected override void Init(IWebHostBuilder builder) { builder.UseStartup<Startup>(); InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { base.Init(builder); InitHostBuilder = true; } } public class HostBuilderOverridingCreateHostBuilder : APIGatewayProxyFunction, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override IHostBuilder CreateHostBuilder() { return base.CreateHostBuilder(); } protected override void Init(IWebHostBuilder builder) { builder.UseStartup<Startup>(); InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { base.Init(builder); InitHostBuilder = true; } } public class HostBuilderOverridingInitHostBuilderAndCallsConfigureWebHostDefaults : APIGatewayProxyFunction, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override void Init(IWebHostBuilder builder) { InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { InitHostBuilder = true; builder .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } public class HostBuilderOverridingInitHostBuilderAndCallsConfigureWebHostLambdaDefaults : APIGatewayProxyFunction, IMethodsCalled { public bool InitHostBuilder { get; set; } public bool InitHostWebBuilder { get; set; } protected override void Init(IWebHostBuilder builder) { InitHostWebBuilder = true; } protected override void Init(IHostBuilder builder) { InitHostBuilder = true; builder .ConfigureWebHostLambdaDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } } #endif
144
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.AspNetCoreServer; namespace TestWebApp { public class HttpV2LambdaFunction : APIGatewayHttpApiV2ProxyFunction<Startup> { } }
7
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace TestWebApp { public class Middleware { private readonly RequestDelegate _next; public Middleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { LambdaLogger.Log("Middleware Invoked"); context.Response.OnStarting(x => { var lambdaContext = context.Items["LambdaContext"] as ILambdaContext; lambdaContext?.Logger.LogLine("OnStarting Called"); return Task.FromResult(0); }, context); await _next(context); } } }
35
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; namespace TestWebApp { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
26
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.ResponseCompression; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Runtime.Serialization.Json; using System.IO; using Microsoft.AspNetCore.Http.Features; #if NETCOREAPP_2_1 using Newtonsoft.Json.Linq; using Swashbuckle.AspNetCore.Swagger; #else using System.Text.Json; #endif namespace TestWebApp { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy("YouAreSpecial", policy => policy.RequireClaim("you_are_special")); }); services.AddResponseCompression((options) => { options.Providers.Add<GzipCompressionProvider>(); options.EnableForHttps = true; options.MimeTypes = new string[] { "application/json-compress" }; }); #if NETCOREAPP_2_1 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); #elif NETCOREAPP_3_1 services.AddControllers(); #endif } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMiddleware<Middleware>(); app.UseResponseCompression(); #if NETCOREAPP_3_1 app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); #else app.UseSwagger(); app.UseMvc(); #endif app.Run(async (context) => { var rawTarget = context.Features.Get<IHttpRequestFeature>()?.RawTarget; #if NETCOREAPP_2_1 var root = new JObject(); root["Path"] = new JValue(context.Request.Path); root["PathBase"] = new JValue(context.Request.PathBase); root["RawTarget"] = new JValue(rawTarget); var query = new JObject(); foreach(var queryKey in context.Request.Query.Keys) { var variables = new JArray(); foreach(var v in context.Request.Query[queryKey]) { variables.Add(new JValue(v)); } query[queryKey] = variables; } root["QueryVariables"] = query; var body = root.ToString(); #else var stream = new MemoryStream(); var writer = new Utf8JsonWriter(stream); writer.WriteStartObject(); writer.WriteString("Path", context.Request.Path); writer.WriteString("PathBase", context.Request.PathBase); writer.WriteString("RawTarget", rawTarget); writer.WriteStartObject("QueryVariables"); foreach (var queryKey in context.Request.Query.Keys) { writer.WriteStartArray(queryKey); foreach (var v in context.Request.Query[queryKey]) { writer.WriteStringValue(v); } writer.WriteEndArray(); } writer.WriteEndObject(); writer.WriteEndObject(); writer.Dispose(); stream.Position = 0; var body = new StreamReader(stream).ReadToEnd(); #endif context.Response.Headers["Content-Type"] = "application/json"; await context.Response.WriteAsync(body); }); } } }
142
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace TestWebApp.Controllers { [Route("api/[controller]")] public class AuthTestController : Controller { // GET: api/<controller> [HttpGet] [Authorize(Policy = "YouAreSpecial")] public string Get() { return "You Have Access"; } } }
24
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; using System.IO; using static System.Net.Mime.MediaTypeNames; namespace TestWebApp.Controllers { [Route("api/binary")] public class BinaryContentController : Controller { [HttpGet] public IActionResult Get([FromQuery] string firstName, [FromQuery] string lastName) { var bytes = new byte[byte.MaxValue]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; return base.File(bytes, Application.Octet); } [HttpPut] public string Put() { using (var reader = new StreamReader(this.HttpContext.Request.Body)) { return reader.ReadToEnd(); } } } }
31
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class BodyTestsController : Controller { [HttpPut] public string PutBody([FromBody] Person body) { return $"{body.LastName}, {body.FirstName}"; } public class Person { public string FirstName { get; set; } public string LastName { get; set; } } } }
26
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class CompressResponseController : ControllerBase { [HttpGet] public IActionResult Get() { var response = "[\"value1\",\"value2\"]"; return Content(response, "application/json-compress"); } } }
16
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class CookieTestsController : Controller { [HttpGet] public string Get() { var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(5) }; Response.Cookies.Append("TestCookie", "TestValue", cookieOptions); return String.Empty; } [HttpGet("multiple")] public string GetMulti() { var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(5) }; Response.Cookies.Append("TestCookie1", "TestValue1", cookieOptions); Response.Cookies.Append("TestCookie2", "TestValue2", cookieOptions); return String.Empty; } [HttpGet("{id}")] public string Get(string id) { return Request.Cookies.FirstOrDefault(c => c.Key == id).Value; } } }
43
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Reflection; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class ErrorTestsController { [HttpGet] public string Get([FromQuery]string id) { if (id == "typeload-test") { var fnfEx = new FileNotFoundException("Couldn't find file", "System.String.dll"); throw new ReflectionTypeLoadException(new[] { typeof(String) }, new[] { fnfEx }); } var ex = new Exception("Unit test exception, for test conditions."); if (id == "aggregate-test") { throw new AggregateException(ex); } else { throw ex; } } } }
32
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class MTlsTestController : Controller { // GET: api/<controller> [HttpGet] public string Get() { return Request.HttpContext.Connection.ClientCertificate?.Subject; } } }
15
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class QueryStringController : Controller { [HttpGet] public string Get([FromQuery] string firstName, [FromQuery] string lastName) { if (HttpContext.Request.Query.TryGetValue("mv-test", out var values)) { return string.Join(",", values); } return $"{firstName}, {lastName}"; } } }
24
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class RawQueryStringController : Controller { [HttpGet] public string Get() { return this.Request.QueryString.ToString(); } [HttpGet] [Route("json")] public Results Get([FromQuery] string url, [FromQuery] DateTimeOffset testDateTimeOffset) { return new Results { Url = url, TestDateTimeOffset = testDateTimeOffset }; } public class Results { public string Url { get; set; } public DateTimeOffset TestDateTimeOffset { get;set;} } } }
36
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class RedirectTestController : Controller { // GET api/values [HttpGet] public ActionResult Get() { return this.Redirect("redirecttarget"); } } [Route("api/[controller]")] public class RedirectTargetController : Controller { // GET api/values [HttpGet] public string Get() { return "You have been redirected"; } } }
34
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class RequestServicesExampleController : ControllerBase { [HttpGet] public string Get() { return this.HttpContext.RequestServices?.GetType().FullName; } } }
19
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class ResourcePathController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(string id) { return "value=" + id; } [Route("/api/[controller]/string/{*value}")] [HttpGet] public string GetString(string value) { var path = this.HttpContext.Request.Path; return "value=" + value; } [HttpGet("/api/[controller]/encoding/{first}/{second}", Name = "Multi")] public ActionResult Multi(string first, string second) => Ok(new { first, second }); [HttpGet("/api/[controller]/encoding/{only}", Name = "Single")] public ActionResult Single(string only) => Ok(new { only }); } }
42
aws-lambda-dotnet
aws
C#
using Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class TraceTestsController : Controller { [HttpGet] public string GetTraceId() { return this.HttpContext.TraceIdentifier; } } }
15
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 Microsoft.AspNetCore.Mvc; namespace TestWebApp.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // 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"; } // 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) { } [HttpPost] public async Task<IActionResult> ChectContentLength() { using (var sr = new StreamReader(Request.Body)) { var content = await sr.ReadToEndAsync(); var sb = new StringBuilder(); sb.AppendLine($"Request content length: {Request.ContentLength}"); return Content(sb.ToString()); } } } }
54
aws-lambda-dotnet
aws
C#
using System; namespace Amazon.Lambda.TestTool { public class CommandLineOptions { public string Host { get; set; } public int? Port { get; set; } public bool NoLaunchWindow { get; set; } public string Path { get; set; } public bool NoUI { get; set; } public string ConfigFile { get; set; } public string FunctionHandler { get; set; } public string Payload { get; set; } public string AWSProfile { get; set; } public string AWSRegion { get; set; } public bool ShowHelp { get; set; } public bool PauseExit { get; set; } = true; public static CommandLineOptions Parse(string[] args) { var options = new CommandLineOptions(); for (int i = 0; i < args.Length; i++) { bool skipAhead; switch (args[i]) { case "--help": options.ShowHelp = GetNextBoolValue(i, out skipAhead); if (skipAhead) { i++; } break; case "--host": options.Host = GetNextStringValue(i); i++; break; case "--port": options.Port = GetNextIntValue(i); i++; break; case "--no-launch-window": options.NoLaunchWindow = GetNextBoolValue(i, out skipAhead); if (skipAhead) { i++; } break; case "--path": options.Path = GetNextStringValue(i); i++; break; case "--profile": options.AWSProfile = GetNextStringValue(i); i++; break; case "--region": options.AWSRegion = GetNextStringValue(i); i++; break; case "--no-ui": options.NoUI = GetNextBoolValue(i, out skipAhead); if (skipAhead) { i++; } break; case "--config-file": options.ConfigFile = GetNextStringValue(i); i++; break; case "--function-handler": options.FunctionHandler = GetNextStringValue(i); i++; break; case "--payload": options.Payload = GetNextStringValue(i); i++; break; case "--pause-exit": options.PauseExit = GetNextBoolValue(i, out skipAhead); if (skipAhead) { i++; } break; } } return options; string GetNextStringValue(int currentIndex) { var valueIndex = currentIndex + 1; if (valueIndex == args.Length) throw new CommandLineParseException($"Missing value for {args[currentIndex]}"); return args[valueIndex]; } int GetNextIntValue(int currentIndex) { if (int.TryParse(GetNextStringValue(currentIndex), out var value)) { return value; } throw new CommandLineParseException($"Value for {args[currentIndex]} is not a valid integer"); } bool GetNextBoolValue(int currentIndex, out bool skipAhead) { if (currentIndex + 1 < args.Length && !args[currentIndex + 1].StartsWith("--") && bool.TryParse(GetNextStringValue(currentIndex), out var value)) { skipAhead = true; return value; } skipAhead = false; return true; } } public static void PrintUsage() { Console.WriteLine(); Console.WriteLine("The .NET Lambda Test Tool can be launched in 2 modes. The default mode is to launch a web interface to select the Lambda code"); Console.WriteLine("to execute with in the Lambda test tool. The second mode skips using the web interface and the Lambda code is identified"); Console.WriteLine("using the commandline switches as described below. To switch to the no web interface mode use the --no-ui command line switch."); Console.WriteLine(); Console.WriteLine("These options are valid for either mode the Lambda test tool is running in."); Console.WriteLine(); Console.WriteLine("\t--path <directory> The path to the lambda project to execute. If not set then the current directory will be used."); Console.WriteLine(); Console.WriteLine("These options are valid when using the web interface to select and execute the Lambda code."); Console.WriteLine(); Console.WriteLine("\t--host <hostname-or-ip-address> The port number used for the test tool's web interface."); Console.WriteLine("\t Any host other than an explicit IP address or localhost (e.g. '*', '+' or 'example.com')"); Console.WriteLine("\t binds to all public IPv4 and IPv6 addresses."); Console.WriteLine("\t--port <port-number> The port number used for the test tool's web interface."); Console.WriteLine("\t--no-launch-window Disable auto launching the test tool's web interface in a browser."); Console.WriteLine(); Console.WriteLine("These options are valid in the no web interface mode."); Console.WriteLine(); Console.WriteLine("\t--no-ui Disable launching the web interface and immediately execute the Lambda code."); Console.WriteLine("\t--profile <profile-name> Set the AWS credentials profile to provide credentials to the Lambda code."); Console.WriteLine("\t If not set the profile from the config file will be used."); Console.WriteLine("\t--region <region-name> Set the AWS region to as the default region for the Lambda code being executed."); Console.WriteLine("\t If not set the region from the config file will be used."); Console.WriteLine("\t--config-file <file-name> The config file to read for Lambda settings. If not set then aws-lambda-tools-defaults.json"); Console.WriteLine("\t will be used."); Console.WriteLine("\t--function-handler <handler-string> The Lambda function handler to identify the code to run. If not set then the function handler"); Console.WriteLine("\t from the config file will be used. This is the format of <assembly::type-name::method-name>."); Console.WriteLine("\t--payload <file-name> The JSON payload to send to the Lambda function. This can be either an inline string or a"); Console.WriteLine("\t file path to a JSON file."); Console.WriteLine("\t--pause-exit <true or false> If set to true the test tool will pause waiting for a key input before exiting. The is useful"); Console.WriteLine("\t when executing from an IDE so you can avoid having the output window immediately disappear after"); Console.WriteLine("\t executing the Lambda code. The default value is true."); } } public class CommandLineParseException : Exception { public CommandLineParseException(string message) : base(message) { } } }
187
aws-lambda-dotnet
aws
C#
using System; namespace Amazon.Lambda.TestTool { public class InvokeParameters { public string Profile { get; set; } public string Region { get; set; } public string Payload { get; set; } } }
11
aws-lambda-dotnet
aws
C#
using System; using System.Text.Json.Serialization; namespace Amazon.Lambda.TestTool { public class LambdaConfigFile { public string Framework { get; set; } public string Profile { get; set; } public string Region { get; set; } public string Template { get; set; } [JsonPropertyName("function-handler")] public string FunctionHandler { get; set; } [JsonPropertyName("function-name")] public string FunctionName { get; set; } [JsonPropertyName("image-command")] public string ImageCommand { get; set; } [JsonPropertyName("environment-variables")] public string EnvironmentVariables { get; set; } public string ConfigFileLocation { get; set; } public string DetermineHandler() { if (!string.IsNullOrEmpty(this.FunctionHandler)) return this.FunctionHandler; return this.ImageCommand; } } }
36
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.TestTool.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Amazon.Lambda.TestTool { public class LocalLambdaOptions { public string Host { get; set; } public int? Port { get; set; } public IList<string> LambdaConfigFiles { get; set; } public ILocalLambdaRuntime LambdaRuntime { get; set; } public LambdaFunction LoadLambdaFuntion(string configFile, string functionHandler) { var fullConfigFilePath = this.LambdaConfigFiles.FirstOrDefault(x => string.Equals(configFile, x, StringComparison.OrdinalIgnoreCase) || string.Equals(configFile, Path.GetFileName(x), StringComparison.OrdinalIgnoreCase)); if (fullConfigFilePath == null) { throw new Exception($"{configFile} is not a config file for this project"); } var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(fullConfigFilePath); return LoadLambdaFuntion(configInfo, functionHandler); } public bool TryLoadLambdaFuntion(LambdaConfigInfo configInfo, string functionHandler, out LambdaFunction lambdaFunction) { lambdaFunction = null; try { lambdaFunction = LoadLambdaFuntion(configInfo, functionHandler); return true; } catch { } return false; } public LambdaFunction LoadLambdaFuntion(LambdaConfigInfo configInfo, string functionHandler) { var functionInfo = configInfo.FunctionInfos.FirstOrDefault(x => string.Equals(functionHandler, x.Handler, StringComparison.OrdinalIgnoreCase)); if (functionInfo == null) { throw new Exception($"Failed to find function {functionHandler}"); } var function = this.LambdaRuntime.LoadLambdaFunction(functionInfo); return function; } /// <summary> /// The directory to store in local settings for a Lambda project for example saved Lambda requests. /// </summary> public string GetPreferenceDirectory(bool createIfNotExist) { var currentDirectory = this.LambdaRuntime.LambdaAssemblyDirectory; while (currentDirectory != null && !Utils.IsProjectDirectory(currentDirectory)) { currentDirectory = Directory.GetParent(currentDirectory).FullName; } if (currentDirectory == null) currentDirectory = this.LambdaRuntime.LambdaAssemblyDirectory; var preferenceDirectory = Path.Combine(currentDirectory, ".lambda-test-tool"); if (createIfNotExist && !Directory.Exists(preferenceDirectory)) { Directory.CreateDirectory(preferenceDirectory); } return preferenceDirectory; } } }
82
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.TestTool.Runtime; using Amazon.Lambda.TestTool.SampleRequests; using System; using System.Diagnostics; using System.IO; using System.Linq; namespace Amazon.Lambda.TestTool { public class TestToolStartup { public class RunConfiguration { public enum RunMode { Normal, Test }; /// <summary> /// If this is set to Test then that disables any interactive activity or any calls to Environment.Exit which wouldn't work well during a test run. /// </summary> public RunMode Mode { get; set; } = RunMode.Normal; /// <summary> /// Allows you to capture the output for tests to example instead of just writing to the console windows. /// </summary> public TextWriter OutputWriter { get; set; } = Console.Out; } public static void Startup(string productName, Action<LocalLambdaOptions, bool> uiStartup, string[] args) { Startup(productName, uiStartup, args, new RunConfiguration()); } public static void Startup(string productName, Action<LocalLambdaOptions, bool> uiStartup, string[] args, RunConfiguration runConfiguration) { try { Utils.PrintToolTitle(productName); var commandOptions = CommandLineOptions.Parse(args); if (commandOptions.ShowHelp) { CommandLineOptions.PrintUsage(); return; } var localLambdaOptions = new LocalLambdaOptions() { Host = commandOptions.Host, Port = commandOptions.Port }; var lambdaAssemblyDirectory = commandOptions.Path ?? Directory.GetCurrentDirectory(); #if NETCOREAPP3_1 var targetFramework = "netcoreapp3.1"; #elif NET5_0 var targetFramework = "net5.0"; #elif NET6_0 var targetFramework = "net6.0"; #elif NET7_0 var targetFramework = "net7.0"; #endif // Check to see if running in debug mode from this project's directory which means the test tool is being debugged. // To make debugging easier pick one of the test Lambda projects. if (lambdaAssemblyDirectory.EndsWith("Amazon.Lambda.TestTool.WebTester21")) { lambdaAssemblyDirectory = Path.Combine(lambdaAssemblyDirectory, $"../../tests/LambdaFunctions/netcore21/S3EventFunction/bin/Debug/{targetFramework}"); } else if (lambdaAssemblyDirectory.EndsWith("Amazon.Lambda.TestTool.WebTester31")) { lambdaAssemblyDirectory = Path.Combine(lambdaAssemblyDirectory, $"../../tests/LambdaFunctions/netcore31/S3EventFunction/bin/Debug/{targetFramework}"); } // If running in the project directory select the build directory so the deps.json file can be found. else if (Utils.IsProjectDirectory(lambdaAssemblyDirectory)) { lambdaAssemblyDirectory = Path.Combine(lambdaAssemblyDirectory, $"bin/Debug/{targetFramework}"); } lambdaAssemblyDirectory = Utils.SearchLatestCompilationDirectory(lambdaAssemblyDirectory); localLambdaOptions.LambdaRuntime = LocalLambdaRuntime.Initialize(lambdaAssemblyDirectory); runConfiguration.OutputWriter.WriteLine($"Loaded local Lambda runtime from project output {lambdaAssemblyDirectory}"); if (commandOptions.NoUI) { ExecuteWithNoUi(localLambdaOptions, commandOptions, lambdaAssemblyDirectory, runConfiguration); } else { // Look for aws-lambda-tools-defaults.json or other config files. localLambdaOptions.LambdaConfigFiles = Utils.SearchForConfigFiles(lambdaAssemblyDirectory); // Start the test tool web server. uiStartup(localLambdaOptions, !commandOptions.NoLaunchWindow); } } catch (CommandLineParseException e) { runConfiguration.OutputWriter.WriteLine($"Invalid command line arguments: {e.Message}"); runConfiguration.OutputWriter.WriteLine("Use the --help option to learn about the possible command line arguments"); if (runConfiguration.Mode == RunConfiguration.RunMode.Normal) { if (Debugger.IsAttached) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } System.Environment.Exit(-1); } } catch (Exception e) { runConfiguration.OutputWriter.WriteLine($"Unknown error occurred causing process exit: {e.Message}"); runConfiguration.OutputWriter.WriteLine(e.StackTrace); if (runConfiguration.Mode == RunConfiguration.RunMode.Normal) { if (Debugger.IsAttached) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } System.Environment.Exit(-2); } } } public static void ExecuteWithNoUi(LocalLambdaOptions localLambdaOptions, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, RunConfiguration runConfiguration) { runConfiguration.OutputWriter.WriteLine("Executing Lambda function without web interface"); var lambdaProjectDirectory = Utils.FindLambdaProjectDirectory(lambdaAssemblyDirectory); string configFile = DetermineConfigFile(commandOptions, lambdaAssemblyDirectory: lambdaAssemblyDirectory, lambdaProjectDirectory: lambdaProjectDirectory); LambdaConfigInfo configInfo = LoadLambdaConfigInfo(configFile, commandOptions, lambdaAssemblyDirectory: lambdaAssemblyDirectory, lambdaProjectDirectory: lambdaProjectDirectory, runConfiguration); LambdaFunction lambdaFunction = LoadLambdaFunction(configInfo, localLambdaOptions, commandOptions, lambdaAssemblyDirectory: lambdaAssemblyDirectory, lambdaProjectDirectory: lambdaProjectDirectory, runConfiguration); string payload = DeterminePayload(localLambdaOptions, commandOptions, lambdaAssemblyDirectory: lambdaAssemblyDirectory, lambdaProjectDirectory: lambdaProjectDirectory, runConfiguration); var awsProfile = commandOptions.AWSProfile ?? configInfo.AWSProfile; if (!string.IsNullOrEmpty(awsProfile)) { if (new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain().TryGetProfile(awsProfile, out _)) { runConfiguration.OutputWriter.WriteLine($"... Setting AWS_PROFILE environment variable to {awsProfile}."); } else { runConfiguration.OutputWriter.WriteLine($"... Warning: Profile {awsProfile} not found in the aws credential store."); awsProfile = null; } } else { runConfiguration.OutputWriter.WriteLine("... No profile choosen for AWS credentials. The --profile switch can be used to configure an AWS profile."); } var awsRegion = commandOptions.AWSRegion ?? configInfo.AWSRegion; if (!string.IsNullOrEmpty(awsRegion)) { runConfiguration.OutputWriter.WriteLine($"... Setting AWS_REGION environment variable to {awsRegion}."); } else { runConfiguration.OutputWriter.WriteLine("... No default AWS region configured. The --region switch can be used to configure an AWS Region."); } // Create the execution request that will be sent into the LocalLambdaRuntime. var request = new ExecutionRequest() { AWSProfile = awsProfile, AWSRegion = awsRegion, Payload = payload, Function = lambdaFunction }; ExecuteRequest(request, localLambdaOptions, runConfiguration); if (runConfiguration.Mode == RunConfiguration.RunMode.Normal && commandOptions.PauseExit) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } private static string DetermineConfigFile(CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory) { string configFile = null; if (string.IsNullOrEmpty(commandOptions.ConfigFile)) { configFile = Utils.SearchForConfigFiles(lambdaAssemblyDirectory).FirstOrDefault(x => string.Equals(Utils.DEFAULT_CONFIG_FILE, Path.GetFileName(x), StringComparison.OrdinalIgnoreCase)); } else if (Path.IsPathRooted(commandOptions.ConfigFile)) { configFile = commandOptions.ConfigFile; } else if (File.Exists(Path.Combine(lambdaAssemblyDirectory, commandOptions.ConfigFile))) { configFile = Path.Combine(lambdaAssemblyDirectory, commandOptions.ConfigFile); } else if (lambdaProjectDirectory != null && File.Exists(Path.Combine(lambdaProjectDirectory, commandOptions.ConfigFile))) { configFile = Path.Combine(lambdaProjectDirectory, commandOptions.ConfigFile); } return configFile; } private static LambdaConfigInfo LoadLambdaConfigInfo(string configFile, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory, RunConfiguration runConfiguration) { LambdaConfigInfo configInfo; if (configFile != null) { runConfiguration.OutputWriter.WriteLine($"... Using config file {configFile}"); configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile); } else { // If no config files or function handler are set then we don't know what code to call and must give up. if (string.IsNullOrEmpty(commandOptions.FunctionHandler)) { throw new CommandLineParseException("No config file or function handler specified to test tool is unable to identify the Lambda code to execute."); } // No config files were found so create a temporary config file and use the function handler value that was set on the command line. configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(new LambdaConfigFile { FunctionHandler = commandOptions.FunctionHandler, ConfigFileLocation = lambdaProjectDirectory ?? lambdaAssemblyDirectory }); } return configInfo; } private static LambdaFunction LoadLambdaFunction(LambdaConfigInfo configInfo, LocalLambdaOptions localLambdaOptions, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory, RunConfiguration runConfiguration) { // If no function handler was explicitly set and there is only one function defined in the config file then assume the user wants to debug that function. var functionHandler = commandOptions.FunctionHandler; if (string.IsNullOrEmpty(commandOptions.FunctionHandler)) { if (configInfo.FunctionInfos.Count == 1) { functionHandler = configInfo.FunctionInfos[0].Handler; } else { throw new CommandLineParseException("Project has more then one Lambda function defined. Use the --function-handler switch to identify the Lambda code to execute."); } } LambdaFunction lambdaFunction; if (!localLambdaOptions.TryLoadLambdaFuntion(configInfo, functionHandler, out lambdaFunction)) { // The user has explicitly set a function handler value that is not in the config file or CloudFormation template. // To support users testing add hoc methods create a temporary config object using explicit function handler value. runConfiguration.OutputWriter.WriteLine($"... Info: function handler {functionHandler} is not defined in config file."); var temporaryConfigInfo = LambdaDefaultsConfigFileParser.LoadFromFile(new LambdaConfigFile { FunctionHandler = functionHandler, ConfigFileLocation = Utils.FindLambdaProjectDirectory(lambdaAssemblyDirectory) ?? lambdaAssemblyDirectory }); temporaryConfigInfo.AWSProfile = configInfo.AWSProfile; temporaryConfigInfo.AWSRegion = configInfo.AWSRegion; configInfo = temporaryConfigInfo; lambdaFunction = localLambdaOptions.LoadLambdaFuntion(configInfo, functionHandler); } runConfiguration.OutputWriter.WriteLine($"... Using function handler {functionHandler}"); return lambdaFunction; } private static string DeterminePayload(LocalLambdaOptions localLambdaOptions, CommandLineOptions commandOptions, string lambdaAssemblyDirectory, string lambdaProjectDirectory, RunConfiguration runConfiguration) { var payload = commandOptions.Payload; bool payloadFileFound = false; if (!string.IsNullOrEmpty(payload)) { if (Path.IsPathFullyQualified(payload) && File.Exists(payload)) { runConfiguration.OutputWriter.WriteLine($"... Using payload with from the file {payload}"); payload = File.ReadAllText(payload); payloadFileFound = true; } else { // Look to see if the payload value is a file in // * Directory with user Lambda assemblies. // * Lambda project directory // * Properties directory under the project directory. This is to make it easy to reconcile from the launchSettings.json file. // * Is a saved sample request from the web interface var possiblePaths = new[] { Path.Combine(lambdaAssemblyDirectory, payload), Path.Combine(lambdaProjectDirectory, payload), Path.Combine(lambdaProjectDirectory, "Properties", payload), Path.Combine(localLambdaOptions.GetPreferenceDirectory(false), new SampleRequestManager(localLambdaOptions.GetPreferenceDirectory(false)).GetSaveRequestRelativePath(payload)) }; foreach (var possiblePath in possiblePaths) { if (File.Exists(possiblePath)) { runConfiguration.OutputWriter.WriteLine($"... Using payload with from the file {Path.GetFullPath(possiblePath)}"); payload = File.ReadAllText(possiblePath); payloadFileFound = true; break; } } } } if (!payloadFileFound) { if (!string.IsNullOrEmpty(payload)) { runConfiguration.OutputWriter.WriteLine($"... Using payload with the value {payload}"); } else { runConfiguration.OutputWriter.WriteLine("... No payload configured. If a payload is required set the --payload switch to a file path or a JSON document."); } } return payload; } private static void ExecuteRequest(ExecutionRequest request, LocalLambdaOptions localLambdaOptions, RunConfiguration runConfiguration) { try { var response = localLambdaOptions.LambdaRuntime.ExecuteLambdaFunctionAsync(request).GetAwaiter().GetResult(); runConfiguration.OutputWriter.WriteLine("Captured Log information:"); runConfiguration.OutputWriter.WriteLine(response.Logs); if (response.IsSuccess) { runConfiguration.OutputWriter.WriteLine("Request executed successfully"); runConfiguration.OutputWriter.WriteLine("Response:"); runConfiguration.OutputWriter.WriteLine(response.Response); } else { runConfiguration.OutputWriter.WriteLine("Request failed to execute"); runConfiguration.OutputWriter.WriteLine($"Error:"); runConfiguration.OutputWriter.WriteLine(response.Error); } } catch (Exception e) { runConfiguration.OutputWriter.WriteLine("Unknown error occurred in the Lambda test tool while executing request."); runConfiguration.OutputWriter.WriteLine($"Error Message: {e.Message}"); runConfiguration.OutputWriter.WriteLine(e.StackTrace); } } } }
360
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Text.Json; using Amazon.Lambda.TestTool.Runtime; namespace Amazon.Lambda.TestTool { public static class Utils { public const string DEFAULT_CONFIG_FILE = "aws-lambda-tools-defaults.json"; public static string DetermineToolVersion() { AssemblyInformationalVersionAttribute attribute = null; try { var assembly = Assembly.GetEntryAssembly(); if (assembly == null) return null; attribute = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>(); } catch (Exception) { // ignored } return attribute?.InformationalVersion; } /// <summary> /// A collection of known paths for common utilities that are usually not found in the path /// </summary> static readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe" }, {"dotnet", @"/usr/local/share/dotnet/dotnet" } }; /// <summary> /// Search the path environment variable for the command given. /// </summary> /// <param name="command">The command to search for in the path</param> /// <returns>The full path to the command if found otherwise it will return null</returns> public static string FindExecutableInPath(string command) { if (File.Exists(command)) return Path.GetFullPath(command); if (string.Equals(command, "dotnet.exe")) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { command = "dotnet"; } var mainModule = Process.GetCurrentProcess().MainModule; if (!string.IsNullOrEmpty(mainModule?.FileName) && Path.GetFileName(mainModule.FileName).Equals(command, StringComparison.OrdinalIgnoreCase)) { return mainModule.FileName; } } Func<string, string> quoteRemover = x => { if (x.StartsWith("\"")) x = x.Substring(1); if (x.EndsWith("\"")) x = x.Substring(0, x.Length - 1); return x; }; var envPath = Environment.GetEnvironmentVariable("PATH"); foreach (var path in envPath.Split(Path.PathSeparator)) { try { var fullPath = Path.Combine(quoteRemover(path), command); if (File.Exists(fullPath)) return fullPath; } catch (Exception) { // Catch exceptions and continue if there are invalid characters in the user's path. } } if (KNOWN_LOCATIONS.ContainsKey(command) && File.Exists(KNOWN_LOCATIONS[command])) return KNOWN_LOCATIONS[command]; return null; } public static bool IsProjectDirectory(string directory) { if (Directory.GetFiles(directory, "*.csproj").Length > 0 || Directory.GetFiles(directory, "*.fsproj").Length > 0 || Directory.GetFiles(directory, "*.vbproj").Length > 0) { return true; } return false; } public static string FindLambdaProjectDirectory(string lambdaAssemblyDirectory) { if (string.IsNullOrEmpty(lambdaAssemblyDirectory)) return null; if (IsProjectDirectory(lambdaAssemblyDirectory)) return lambdaAssemblyDirectory; return FindLambdaProjectDirectory(Directory.GetParent(lambdaAssemblyDirectory)?.FullName); } public static IList<string> SearchForConfigFiles(string lambdaFunctionDirectory) { var configFiles = new List<string>(); // Look for JSON files that are .NET Lambda config files like aws-lambda-tools-defaults.json. The parameter // lambdaFunctionDirectory will be set to the build directory so the search goes up the directory hierarchy. do { foreach (var file in Directory.GetFiles(lambdaFunctionDirectory, "*.json", SearchOption.TopDirectoryOnly)) { try { var configFile = System.Text.Json.JsonSerializer.Deserialize<LambdaConfigFile>(File.ReadAllText(file), new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true }); configFile.ConfigFileLocation = file; if (!string.IsNullOrEmpty(configFile.DetermineHandler())) { Console.WriteLine($"Found Lambda config file {file}"); configFiles.Add(file); } else if (!string.IsNullOrEmpty(configFile.Template) && File.Exists(Path.Combine(lambdaFunctionDirectory, configFile.Template))) { var config = LambdaDefaultsConfigFileParser.LoadFromFile(configFile); if (config.FunctionInfos?.Count > 0) { Console.WriteLine($"Found Lambda config file {file}"); configFiles.Add(file); } } } catch { Console.WriteLine($"Error parsing JSON file: {file}"); } } lambdaFunctionDirectory = Directory.GetParent(lambdaFunctionDirectory)?.FullName; } while (lambdaFunctionDirectory != null && configFiles.Count == 0); return configFiles; } public static void PrintToolTitle(string productName) { var sb = new StringBuilder(productName); var version = Utils.DetermineToolVersion(); if (!string.IsNullOrEmpty(version)) { sb.Append($" ({version})"); } Console.WriteLine(sb.ToString()); } /// <summary> /// Attempt to pretty print the input string. If pretty print fails return back the input string in its original form. /// </summary> /// <param name="data"></param> /// <returns></returns> public static string TryPrettyPrintJson(string data) { try { var doc = JsonDocument.Parse(data); var prettyPrintJson = System.Text.Json.JsonSerializer.Serialize(doc, new JsonSerializerOptions() { WriteIndented = true }); return prettyPrintJson; } catch (Exception) { return data; } } public static bool IsExecutableAssembliesSupported { get { #if NET6_0_OR_GREATER return true; #else return false; #endif } } public static string DetermineLaunchUrl(string host, int port, string defaultHost) { if (!IPAddress.TryParse(host, out _)) // Any host other than explicit IP will be redirected to default host (i.e. localhost) return $"http://{defaultHost}:{port}"; return $"http://{host}:{port}"; } /// <summary> /// From the debug directory look to see where the latest compilation occurred for debugging. This can vary between the /// root debug directory and the runtime specific subfolders. Starting with .NET 7 SDK if ready 2 run is enabled then /// project compiles into the runtime specific folder. /// </summary> /// <param name="debugDirectory"></param> /// <returns></returns> public static string SearchLatestCompilationDirectory(string debugDirectory) { var depsFile = new DirectoryInfo(debugDirectory).GetFiles("*.deps.json", SearchOption.AllDirectories) .OrderByDescending(x => x.LastWriteTime).ToList(); if (depsFile.Count == 0) return debugDirectory; return depsFile[0].Directory.FullName; } } }
246
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Text; using Amazon.Lambda.Core; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// This class is used to capture standard out and standard error when executing the Lambda function. /// </summary> public class ConsoleOutWrapper : IDisposable { private readonly TextWriter _standardOut; private readonly TextWriter _standardError; public ConsoleOutWrapper(ILambdaLogger logger) { _standardOut = Console.Out; Console.SetOut(new WrapperTextWriter(_standardOut, logger, false)); _standardError = Console.Error; Console.SetError(new WrapperTextWriter(_standardError, logger, false)); } public void Dispose() { Console.SetOut(_standardOut); Console.SetError(_standardError); } class WrapperTextWriter : TextWriter { private readonly TextWriter _innerWriter; private readonly ILambdaLogger _logger; private readonly bool _writeToInnerWriter; public WrapperTextWriter(TextWriter innerWriter, ILambdaLogger logger, bool writeToInnerWriter) { _innerWriter = innerWriter; _logger = logger; _writeToInnerWriter = writeToInnerWriter; } public override Encoding Encoding { get { return Encoding.UTF8;} } public override void Write(string value) { _logger.Log(value); if (this._writeToInnerWriter) { this._innerWriter?.Write(value); } } } } }
64
aws-lambda-dotnet
aws
C#
using Amazon.SQS.Model; using System; using System.Collections.Generic; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// This class will continually poll a SQS queue for more messages from a dead letter queue. If a message was read then the Lambda function /// will be invoked within the test tool. /// </summary> public class DlqMonitor { private readonly object LOG_LOCK = new object(); private CancellationTokenSource _cancelSource; private IList<LogRecord> _records = new List<LogRecord>(); private readonly ILocalLambdaRuntime _runtime; private readonly LambdaFunction _function; private readonly string _profile; private readonly string _region; private readonly string _queueUrl; public DlqMonitor(ILocalLambdaRuntime runtime, LambdaFunction function, string profile, string region, string queueUrl) { this._runtime = runtime; this._function = function; this._profile = profile; this._region = region; this._queueUrl = queueUrl; } public void Start() { this._cancelSource = new CancellationTokenSource(); _ = Loop(this._cancelSource.Token); } public void Stop() { this._cancelSource.Cancel(); } private async Task Loop(CancellationToken token) { var aws = this._runtime.AWSService; while (!token.IsCancellationRequested) { Message message = null; LogRecord logRecord = null; try { // Read a message from the queue using the ExternalCommands console application. message = await aws.ReadMessageAsync(this._profile, this._region, this._queueUrl); if (token.IsCancellationRequested) { return; } if (message == null) { // Since there are no messages, sleep a bit to wait for messages to come. Thread.Sleep(1000); continue; } // If a message was received execute the Lambda function within the test tool. var request = new ExecutionRequest { AWSProfile = this._profile, AWSRegion = this._region, Function = this._function, Payload = JsonSerializer.Serialize(new { Records = new List<Message> { message } }) }; var response = await this._runtime.ExecuteLambdaFunctionAsync(request); // Capture the results to send back to the client application. logRecord = new LogRecord { ProcessTime = DateTime.Now, ReceiptHandle = message.ReceiptHandle, Logs = response.Logs, Error = response.Error }; } catch (Exception e) { logRecord = new LogRecord { ProcessTime = DateTime.Now, Error = e.Message }; Thread.Sleep(1000); } if (logRecord != null && message != null) { logRecord.Event = message.Body; } lock (LOG_LOCK) { this._records.Add(logRecord); } } } // Grabs the log messages since last requests and then resets the records collection. public IList<LogRecord> FetchNewLogs() { lock (LOG_LOCK) { var logsToSend = this._records; this._records = new List<LogRecord>(); return logsToSend; } } public class LogRecord { public DateTime ProcessTime { get; set; } public string Event { get; set; } public string Logs { get; set; } public string Error { get; set; } public string ReceiptHandle { get; set; } } } }
138
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// The information used to execute the Lambda function within the test tool /// </summary> public class ExecutionRequest { /// <summary> /// The container for the holds a reference to the code executed for the Lambda function. /// </summary> public LambdaFunction Function { get; set; } /// <summary> /// The AWS region that the AWS_REGION environment variable is set to so the AWS SDK for .NET will pick up. /// </summary> public string AWSRegion { get; set; } /// <summary> /// The AWS profile that the AWS_PROFILE environment variable is set to so the AWS SDK for .NET will pick up and use for credentials. /// </summary> public string AWSProfile { get; set; } /// <summary> /// The JSON payload that will be the input of the Lambda function. /// </summary> public string Payload { get; set; } } }
29
aws-lambda-dotnet
aws
C#
using System; using System.Runtime.Serialization; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// The class represents the output of an executed Lambda function. /// </summary> public class ExecutionResponse { /// <summary> /// The return data from a Lambda function. /// </summary> public string Response { get; set; } /// <summary> /// The logs captures from calls to ILambdaContext.Logger and Console.Write /// </summary> public string Logs { get; set; } /// <summary> /// If an unhandled exception occured in the Lambda function this will contain the error message and stack trace. /// </summary> public string Error { get; set; } /// <summary> /// True if the Lambda function was executed without any unhandled exceptions. /// </summary> public bool IsSuccess => this.Error == null; } }
32
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.DependencyModel.Resolution; namespace Amazon.Lambda.TestTool.Runtime { public class LambdaAssemblyLoadContext : AssemblyLoadContext { #if !NETCOREAPP2_1 private AssemblyDependencyResolver _builtInResolver; #endif private CustomAssemblyResolver _customResolver; private CustomAssemblyResolver _customDefaultContextResolver; public LambdaAssemblyLoadContext(string lambdaPath) : #if !NETCOREAPP2_1 base("LambdaContext") { _builtInResolver = new AssemblyDependencyResolver(lambdaPath); #else base() { #endif _customResolver = new CustomAssemblyResolver(this, lambdaPath); _customDefaultContextResolver = new CustomAssemblyResolver(AssemblyLoadContext.Default, lambdaPath); AssemblyLoadContext.Default.Resolving += OnDefaultAssemblyLoadContextResolving; } private Assembly OnDefaultAssemblyLoadContextResolving(AssemblyLoadContext context, AssemblyName assemblyName) { string assemblyPath = _customDefaultContextResolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); } return null; } protected override Assembly Load(AssemblyName assemblyName) { if (assemblyName.Name.StartsWith("Amazon.Lambda.Core")) return null; string assemblyPath = null; #if !NETCOREAPP2_1 assemblyPath = _builtInResolver.ResolveAssemblyToPath(assemblyName); #endif if (assemblyPath == null || !File.Exists(assemblyPath)) { assemblyPath = _customResolver.ResolveAssemblyToPath(assemblyName); } if (assemblyPath == null) { assemblyPath = SearchMicrosoftAspNetCoreApp(assemblyName); } if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); } return null; } /// <summary> /// See if the assembly being loaded is coming from the Microsoft.AspNetCore.App runtime. If so /// then load that assembly. /// /// This is done because if fallback to the Default AssemblyLoadContext is used then services added /// to the IServiceCollection will not be resolved. They will be added from the Lambda context but be /// attempted to resolved in the Default context. The Default context doesn't have access to the types in the /// Lambda context and so they will fail to resolve. /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> private string SearchMicrosoftAspNetCoreApp(AssemblyName assemblyName) { var pathMicrosoftAspNetCoreApp = Path.GetDirectoryName(typeof(string).Assembly.Location).Replace("Microsoft.NETCore.App", "Microsoft.AspNetCore.App"); var assemblyDllName = assemblyName.Name + ".dll"; var fullPath = Path.Combine(pathMicrosoftAspNetCoreApp, assemblyDllName); return File.Exists(fullPath) ? fullPath : null; } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { string libraryPath = null; #if !NETCOREAPP2_1 libraryPath = _builtInResolver.ResolveUnmanagedDllToPath(unmanagedDllName); #endif if (libraryPath != null) { return LoadUnmanagedDllFromPath(libraryPath); } return IntPtr.Zero; } class CustomAssemblyResolver { private readonly ICompilationAssemblyResolver assemblyResolver; private readonly DependencyContext dependencyContext; public CustomAssemblyResolver(AssemblyLoadContext assemblyLoadContext, string rootAssemblyPath) { var assembly = assemblyLoadContext.LoadFromAssemblyPath(rootAssemblyPath); this.dependencyContext = DependencyContext.Load(assembly); this.assemblyResolver = new CompositeCompilationAssemblyResolver (new ICompilationAssemblyResolver[] { new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(rootAssemblyPath)), new ReferenceAssemblyPathResolver(), new PackageCompilationAssemblyResolver() }); } public string ResolveAssemblyToPath(AssemblyName name) { bool NamesMatch(RuntimeLibrary runtime) { return string.Equals(runtime.Name, name.Name, StringComparison.OrdinalIgnoreCase); } bool ResourceAssetPathMatch(RuntimeLibrary runtime) { foreach (var group in runtime.RuntimeAssemblyGroups) { foreach (var path in group.AssetPaths) { if (path.EndsWith("/" + name.Name + ".dll")) { return true; } } } return false; } RuntimeLibrary library = this.dependencyContext.RuntimeLibraries.FirstOrDefault(NamesMatch); if (library == null) library = this.dependencyContext.RuntimeLibraries.FirstOrDefault(ResourceAssetPathMatch); if (library != null) { var wrapper = new CompilationLibrary( library.Type, library.Name, library.Version, library.Hash, library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths), library.Dependencies, library.Serviceable); var assemblies = new List<string>(); this.assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies); if (assemblies.Count > 0) { return assemblies[0]; } } return null; } } } }
185
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// This class represents the config info for the available lambda functions gathered from the aws-lambda-tools-defaults.json or similiar files and possibly /// an associated CloudFormation template. /// </summary> public class LambdaConfigInfo { public string AWSProfile { get; set; } public string AWSRegion { get; set; } public List<LambdaFunctionInfo> FunctionInfos { get; set; } } }
16
aws-lambda-dotnet
aws
C#
using System; using System.Collections; using System.IO; using System.Collections.Generic; using System.Text.Json; using YamlDotNet.RepresentationModel; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// This class handles getting the configuration information from aws-lambda-tools-defaults.json file /// and possibly a CloudFormation template. YAML CloudFormation templates aren't supported yet. /// </summary> public static class LambdaDefaultsConfigFileParser { public static LambdaConfigInfo LoadFromFile(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"Lambda config file {filePath} not found"); } var configFile = JsonSerializer.Deserialize<LambdaConfigFile>(File.ReadAllText(filePath).Trim(), new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true }); configFile.ConfigFileLocation = filePath; return LoadFromFile(configFile); } public static LambdaConfigInfo LoadFromFile(LambdaConfigFile configFile) { var configInfo = new LambdaConfigInfo { AWSProfile = !string.IsNullOrEmpty(configFile.Profile) ? configFile.Profile : "default", AWSRegion = !string.IsNullOrEmpty(configFile.Region) ? configFile.Region : null, FunctionInfos = new List<LambdaFunctionInfo>() }; if (string.IsNullOrEmpty(configInfo.AWSProfile)) configInfo.AWSProfile = "default"; var templateFileName = !string.IsNullOrEmpty(configFile.Template) ? configFile.Template : null; var functionHandler = !string.IsNullOrEmpty(configFile.DetermineHandler()) ? configFile.DetermineHandler() : null; if (!string.IsNullOrEmpty(templateFileName)) { var directory = Directory.Exists(configFile.ConfigFileLocation) ? configFile.ConfigFileLocation : Path.GetDirectoryName(configFile.ConfigFileLocation); var templateFullPath = Path.Combine(directory, templateFileName); if (!File.Exists(templateFullPath)) { throw new FileNotFoundException($"Serverless template file {templateFullPath} not found"); } ProcessServerlessTemplate(configInfo, templateFullPath); } else if(!string.IsNullOrEmpty(functionHandler)) { var info = new LambdaFunctionInfo { Handler = functionHandler }; info.Name = !string.IsNullOrEmpty(configFile.FunctionName) ? configFile.FunctionName : null; if (string.IsNullOrEmpty(info.Name)) { info.Name = functionHandler; } if(configFile.EnvironmentVariables != null) { ParseKeyValueOption(configFile.EnvironmentVariables, info.EnvironmentVariables); } configInfo.FunctionInfos.Add(info); } configInfo.FunctionInfos.Sort((x, y ) => string.CompareOrdinal(x.Name, y.Name)); return configInfo; } public static void ParseKeyValueOption(string keyValueString, IDictionary<string, string> values) { if (string.IsNullOrWhiteSpace(keyValueString)) return; try { var currentPos = 0; while (currentPos != -1 && currentPos < keyValueString.Length) { string name; GetNextToken(keyValueString, '=', ref currentPos, out name); string value; GetNextToken(keyValueString, ';', ref currentPos, out value); if (string.IsNullOrEmpty(name)) throw new CommandLineParseException($"Error parsing option ({keyValueString}), format should be <key1>=<value1>;<key2>=<value2>"); values[name] = value ?? string.Empty; } } catch (CommandLineParseException) { throw; } catch (Exception e) { throw new CommandLineParseException($"Error parsing option ({keyValueString}), format should be <key1>=<value1>;<key2>=<value2>: {e.Message}"); } return; } private static void GetNextToken(string option, char endToken, ref int currentPos, out string token) { if (option.Length <= currentPos) { token = string.Empty; return; } int tokenStart = currentPos; int tokenEnd = -1; bool inQuote = false; if (option[currentPos] == '"') { inQuote = true; tokenStart++; currentPos++; while (currentPos < option.Length && option[currentPos] != '"') { currentPos++; } if (option[currentPos] == '"') tokenEnd = currentPos; } while (currentPos < option.Length && option[currentPos] != endToken) { currentPos++; } if (!inQuote) { if (currentPos < option.Length && option[currentPos] == endToken) tokenEnd = currentPos; } if (tokenEnd == -1) token = option.Substring(tokenStart); else token = option.Substring(tokenStart, tokenEnd - tokenStart); currentPos++; } private static void ProcessServerlessTemplate(LambdaConfigInfo configInfo, string templateFilePath) { var content = File.ReadAllText(templateFilePath).Trim(); if(content[0] != '{') { ProcessYamlServerlessTemplate(configInfo, content); } else { ProcessJsonServerlessTemplate(configInfo, content); } } private static void ProcessYamlServerlessTemplate(LambdaConfigInfo configInfo, string content) { var yaml = new YamlStream(); yaml.Load(new StringReader(content)); var root = (YamlMappingNode)yaml.Documents[0].RootNode; if (root == null) return; YamlMappingNode resources = null; if (root.Children.ContainsKey("Resources")) { resources = root.Children["Resources"] as YamlMappingNode; ProcessYamlServerlessTemplateResourcesBased(configInfo, resources); } else if (root.Children.ContainsKey("functions")) { resources = (YamlMappingNode) root.Children["functions"]; ProcessYamlServerlessTemplateFunctionBased(configInfo, resources); } ; } private static void ProcessYamlServerlessTemplateResourcesBased(LambdaConfigInfo configInfo, YamlMappingNode resources) { if (resources == null) return; foreach (var resource in resources.Children) { var resourceBody = (YamlMappingNode) resource.Value; var type = resourceBody.Children.ContainsKey("Type") ? ((YamlScalarNode) resourceBody.Children["Type"])?.Value : null; if (!string.Equals("AWS::Serverless::Function", type, StringComparison.Ordinal) && !string.Equals("AWS::Lambda::Function", type, StringComparison.Ordinal)) { continue; } var properties = resourceBody.Children.ContainsKey("Properties") ? resourceBody.Children["Properties"] as YamlMappingNode : null; if (properties == null) { continue; } string handler = null; if(properties.Children.ContainsKey("Handler")) { handler = ((YamlScalarNode)properties.Children["Handler"])?.Value; } if (string.IsNullOrEmpty(handler) && properties.Children.ContainsKey("ImageConfig")) { var imageConfigNode = properties.Children["ImageConfig"] as YamlMappingNode; if (imageConfigNode.Children.ContainsKey("Command")) { var imageCommandNode = imageConfigNode.Children["Command"] as YamlSequenceNode; // Grab the first element assuming that is the function handler. var en = imageCommandNode.GetEnumerator(); en.MoveNext(); handler = ((YamlScalarNode)en.Current)?.Value; } } if (!string.IsNullOrEmpty(handler)) { var functionInfo = new LambdaFunctionInfo { Name = resource.Key.ToString(), Handler = handler }; configInfo.FunctionInfos.Add(functionInfo); } } } private static void ProcessYamlServerlessTemplateFunctionBased(LambdaConfigInfo configInfo, YamlMappingNode resources) { if (resources == null) return; foreach (var resource in resources.Children) { var resourceBody = (YamlMappingNode) resource.Value; var handler = resourceBody.Children.ContainsKey("handler") ? ((YamlScalarNode) resourceBody.Children["handler"])?.Value : null; if (handler == null) continue; if (string.IsNullOrEmpty(handler)) continue; var functionInfo = new LambdaFunctionInfo { Name = resource.Key.ToString(), Handler = handler }; if (resourceBody.Children.TryGetValue("Environment", out var environmentProperty) && environmentProperty is YamlMappingNode) { if (((YamlMappingNode)environmentProperty).Children.TryGetValue("Environment", out var variableProperty) && variableProperty is YamlMappingNode) { foreach(var kvp in ((YamlMappingNode)variableProperty).Children) { if(kvp.Key is YamlScalarNode keyNode && keyNode.Value != null && kvp.Value is YamlScalarNode valueNode && valueNode.Value != null) { functionInfo.EnvironmentVariables[keyNode.Value] = valueNode.Value; } } } } configInfo.FunctionInfos.Add(functionInfo); } } private static void ProcessJsonServerlessTemplate(LambdaConfigInfo configInfo, string content) { var rootData = JsonDocument.Parse(content); JsonElement resourcesNode; if (!rootData.RootElement.TryGetProperty("Resources", out resourcesNode)) return; foreach (var resourceProperty in resourcesNode.EnumerateObject()) { var resource = resourceProperty.Value; JsonElement typeProperty; if (!resource.TryGetProperty("Type", out typeProperty)) continue; var type = typeProperty.GetString(); JsonElement propertiesProperty; if (!resource.TryGetProperty("Properties", out propertiesProperty)) continue; if (!string.Equals("AWS::Serverless::Function", type, StringComparison.Ordinal) && !string.Equals("AWS::Lambda::Function", type, StringComparison.Ordinal)) { continue; } string handler = null; if (propertiesProperty.TryGetProperty("Handler", out var handlerProperty)) { handler = handlerProperty.GetString(); } else if(propertiesProperty.TryGetProperty("ImageConfig", out var imageConfigProperty) && imageConfigProperty.TryGetProperty("Command", out var imageCommandProperty)) { if(imageCommandProperty.GetArrayLength() > 0) { // Grab the first element assuming that is the function handler. var en = imageCommandProperty.EnumerateArray(); en.MoveNext(); handler = en.Current.GetString(); } } if (!string.IsNullOrEmpty(handler)) { var functionInfo = new LambdaFunctionInfo { Name = resourceProperty.Name, Handler = handler }; if(propertiesProperty.TryGetProperty("Environment", out var environmentProperty) && environmentProperty.TryGetProperty("Variables", out var variablesProperty)) { foreach(var property in variablesProperty.EnumerateObject()) { if(property.Value.ValueKind == JsonValueKind.String) { functionInfo.EnvironmentVariables[property.Name] = property.Value.GetString(); } } } configInfo.FunctionInfos.Add(functionInfo); } } } } }
374
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.TestTool.Runtime.LambdaMocks; namespace Amazon.Lambda.TestTool.Runtime { public class LambdaExecutor { private static readonly SemaphoreSlim executeSlim = new SemaphoreSlim(1, 1); public async Task<ExecutionResponse> ExecuteAsync(ExecutionRequest request) { var logger = new LocalLambdaLogger(); var response = new ExecutionResponse(); if (!string.IsNullOrEmpty(request.Function.ErrorMessage)) { response.Error = request.Function.ErrorMessage; return response; } try { if (!string.IsNullOrEmpty(request.AWSRegion)) { Environment.SetEnvironmentVariable("AWS_REGION", request.AWSRegion); } if (!string.IsNullOrEmpty(request.AWSProfile)) { Environment.SetEnvironmentVariable("AWS_PROFILE", request.AWSProfile); } // Set the Lambda environment variable for the function name. Some libraries like // our Amazon.Lambda.AspNetCoreServer.Hosting use this environment variable to // tell if they are running in Lambda and if so activate. Since we are emulating // Lambda we want those libraries to activate. Environment.SetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME", request.Function.FunctionInfo.Name); // If Environment variables were defined for the function // then set them for the process to the emulated function picks up the variables. foreach (var kvp in request.Function.FunctionInfo.EnvironmentVariables) { Environment.SetEnvironmentVariable(kvp.Key, kvp.Value); } var context = new LocalLambdaContext() { Logger = logger }; object instance = null; if (!request.Function.LambdaMethod.IsStatic) { instance = Activator.CreateInstance(request.Function.LambdaType); } var parameters = BuildParameters(request, context); // Because a Lambda compute environment never executes more then one event at a time // create a lock around the execution to match that environment. await executeSlim.WaitAsync(); try { using (var wrapper = new ConsoleOutWrapper(logger)) { var lambdaReturnObject = request.Function.LambdaMethod.Invoke(instance, parameters); response.Response = await ProcessReturnAsync(request, lambdaReturnObject); } } finally { // To avoid side effects remove the environment variables that were set specifically // for running the lambda function. foreach (var kvp in request.Function.FunctionInfo.EnvironmentVariables) { Environment.SetEnvironmentVariable(kvp.Key, null); } executeSlim.Release(); } } catch (TargetInvocationException e) { response.Error = GenerateErrorMessage(e.InnerException); } catch (Exception e) { response.Error = GenerateErrorMessage(e); } response.Logs = logger.Buffer; return response; } private static string SeachForDllNotFoundException(Exception e) { var excep = e; do { if (excep is DllNotFoundException) return excep.Message; excep = excep.InnerException; } while (excep != null); return null; } public static string GenerateErrorMessage(Exception e) { var dllNotFoundMessage = SeachForDllNotFoundException(e); if (!string.IsNullOrEmpty(dllNotFoundMessage)) return dllNotFoundMessage; StringBuilder sb = new StringBuilder(); if (e is AggregateException) e = e.InnerException; var exceptionDepth = 0; while (e != null) { if (sb.Length > 0) sb.AppendLine($"---------------- Inner {exceptionDepth} Exception ------------"); sb.AppendLine($"{e.GetType().FullName}: {e.Message}"); sb.AppendLine(e.StackTrace); e = e.InnerException; exceptionDepth++; } return sb.ToString(); } public static async Task<string> ProcessReturnAsync(ExecutionRequest request, object lambdaReturnObject) { Stream lambdaReturnStream = null; if (lambdaReturnObject == null) return null; // If the return was a Task then wait till the task is complete. if (lambdaReturnObject is Task task) { await task; // Check to see if the Task returns back an object. // The return type from the Lambda functions MethodInfo must be used for checking if it generic. // If you check the type from the object instance returned the non generic Task gets converted // by the runtime to Task<VoidTaskResult>. if (request.Function.LambdaMethod.ReturnType.IsGenericType) { var resultProperty = task.GetType().GetProperty("Result", BindingFlags.Public | BindingFlags.Instance); if (resultProperty != null) { var taskResult = resultProperty.GetMethod.Invoke(task, null); if (taskResult is Stream stream) { lambdaReturnStream = stream; } else { lambdaReturnStream = new MemoryStream(); MakeGenericSerializerCall(request.Function.Serializer, taskResult, lambdaReturnStream); } } } } else { lambdaReturnStream = new MemoryStream(); MakeGenericSerializerCall(request.Function.Serializer, lambdaReturnObject, lambdaReturnStream); } if (lambdaReturnStream == null) return null; lambdaReturnStream.Position = 0; using (var reader = new StreamReader(lambdaReturnStream)) { return reader.ReadToEnd(); } } /// <summary> /// Reflection is used to invoke the Lambda function which returns the response as an object. The /// Serialize method from ILambdaSerializer is a generic method based on the type of the response object. /// This method converts the generic Serialize method to the specific type of the response. /// /// If we don't do this the 'T' of the generic Serialize method is an object which will break /// when using the source generator serializer SourceGeneratorLambdaJsonSerializer. /// </summary> /// <param name="serializer"></param> /// <param name="lambdaReturnObject"></param> /// <param name="lambdaReturnStream"></param> private static void MakeGenericSerializerCall(ILambdaSerializer serializer, object lambdaReturnObject, Stream lambdaReturnStream) { var serializerMethodInfo = typeof(ILambdaSerializer).GetMethod("Serialize"); var genericSerializerMethodInfo = serializerMethodInfo.MakeGenericMethod(lambdaReturnObject.GetType()); genericSerializerMethodInfo.Invoke(serializer, new object[] { lambdaReturnObject, lambdaReturnStream }); } /// <summary> /// Create the parameter array that will be passed into the Invoke for the Lambda function. /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> /// <exception cref="Exception"></exception> public static object[] BuildParameters(ExecutionRequest request, ILambdaContext context) { var parms = request.Function.LambdaMethod.GetParameters(); var parmValues = new object[parms.Length]; if(parmValues.Length > 2) throw new Exception($".NET Method has too many parameters, {parmValues.Length}. Methods called by Lambda can have at most 2 parameters. The first is the input object and the second is an ILambdaContext."); for (var i = 0; i < parms.Length; i++) { if (parms[i].ParameterType == typeof(ILambdaContext)) { parmValues[i] = context; } else { var bytes = Encoding.UTF8.GetBytes((request.Payload != null) ? request.Payload : "{}"); var stream = new MemoryStream(bytes); if (request.Function.Serializer != null) { var genericMethodInfo = request.Function.Serializer.GetType() .GetMethods(BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(x => string.Equals(x.Name, "Deserialize")); var methodInfo = genericMethodInfo.MakeGenericMethod(new Type[]{parms[i].ParameterType}); try { parmValues[i] = methodInfo.Invoke(request.Function.Serializer, new object[] {stream}); } catch (Exception e) { throw new Exception($"Error deserializing the input JSON to type {parms[i].ParameterType.Name}", e); } } else { parmValues[i] = stream; } } } return parmValues; } } }
268
aws-lambda-dotnet
aws
C#
using System; using System.Reflection; using Amazon.Lambda.TestTool.Runtime; using Amazon.Lambda.Core; namespace Amazon.Lambda.TestTool.Runtime { /// <summary> /// The abstraction above the code that will be called when during a Lambda invocation. /// </summary> public class LambdaFunction { public LambdaFunctionInfo FunctionInfo { get; private set; } /// <summary> /// False if the test tool was unable to find the reflection objects for the function handler. /// </summary> public bool IsSuccess => string.IsNullOrEmpty(this.ErrorMessage); public string ErrorMessage { get; set; } public Assembly LambdaAssembly { get; set; } public Type LambdaType { get; set; } public MethodInfo LambdaMethod { get; set; } public ILambdaSerializer Serializer { get; set; } public LambdaFunction(LambdaFunctionInfo functionInfo) { this.FunctionInfo = functionInfo; } } }
33
aws-lambda-dotnet
aws
C#
using System.Collections.Generic; namespace Amazon.Lambda.TestTool.Runtime { public class LambdaFunctionInfo { /// <summary> /// Display friendly name of the Lambda Function. /// </summary> public string Name { get; set; } /// <summary> /// The Lambda function handler string. /// </summary> public string Handler { get; set; } public IDictionary<string, string> EnvironmentVariables { get; } = new Dictionary<string, string>(); } }
19
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Net; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.TestTool.Services; namespace Amazon.Lambda.TestTool.Runtime { public interface ILocalLambdaRuntime : IDisposable { string LambdaAssemblyDirectory { get; } LambdaFunction LoadLambdaFunction(LambdaFunctionInfo functionInfo); IList<LambdaFunction> LoadLambdaFunctions(IList<LambdaFunctionInfo> configInfos); Task<ExecutionResponse> ExecuteLambdaFunctionAsync(ExecutionRequest request); IAWSService AWSService { get; } } /// <summary> /// A mock Lambda runtime to execute Lambda functions. /// </summary> public class LocalLambdaRuntime : ILocalLambdaRuntime { private LambdaAssemblyLoadContext LambdaContext { get; } public string LambdaAssemblyDirectory { get; } public IAWSService AWSService { get; } private LocalLambdaRuntime(LambdaAssemblyLoadContext lambdaContext, string lambdaAssemblyDirectory, IAWSService awsService) { LambdaContext = lambdaContext; this.LambdaAssemblyDirectory = lambdaAssemblyDirectory; this.AWSService = awsService; } public static ILocalLambdaRuntime Initialize(string directory) { return Initialize(directory, new AWSServiceImpl()); } public static ILocalLambdaRuntime Initialize(string directory, IAWSService awsService) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException($"Directory containing built Lambda project does not exist {directory}"); } var depsFile = Directory.GetFiles(directory, "*.deps.json").FirstOrDefault(); if (depsFile == null) { throw new Exception($"Failed to find a deps.json file in the specified directory ({directory})"); } var fileName = depsFile.Substring(0, depsFile.Length - ".deps.json".Length) + ".dll"; if (!File.Exists(fileName)) { throw new Exception($"Failed to find Lambda project entry assembly in the specified directory ({directory})"); } // The resolver provides the ability to load the assemblies containing the select Lambda function. var resolver = new LambdaAssemblyLoadContext(fileName); var runtime = new LocalLambdaRuntime(resolver, directory, awsService); return runtime; } public IList<LambdaFunction> LoadLambdaFunctions(IList<LambdaFunctionInfo> configInfos) { var functions = new List<LambdaFunction>(); foreach (var configInfo in configInfos) { functions.Add(LoadLambdaFunction(configInfo)); } return functions; } /// <summary> /// Find the reflection objects for the code that will be executed for the Lambda function based on the /// Lambda function handler. /// </summary> /// <param name="functionInfo"></param> /// <returns></returns> public LambdaFunction LoadLambdaFunction(LambdaFunctionInfo functionInfo) { var function = new LambdaFunction(functionInfo); var handlerTokens = functionInfo.Handler.Split("::"); if (handlerTokens.Length != 3) { function.ErrorMessage = $"Invalid format for function handler string {functionInfo.Handler}. Format is <assembly>::<type-name>::<method>."; return function; } // Using our custom Assembly resolver load the target Assembly. function.LambdaAssembly = this.LambdaContext.LoadFromAssemblyName(new AssemblyName(handlerTokens[0])); if (function.LambdaAssembly == null) { function.ErrorMessage = $"Failed to find assembly {handlerTokens[0]}"; return function; } function.LambdaType = function.LambdaAssembly.GetType(handlerTokens[1]); if (function.LambdaType == null) { function.ErrorMessage = $"Failed to find type {handlerTokens[1]}"; return function; } var methodInfos = function.LambdaType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) .Where(x => string.Equals(x.Name, handlerTokens[2])).ToArray(); if (methodInfos.Length == 1) { function.LambdaMethod = methodInfos[0]; } else { // TODO: Handle method overloads if (methodInfos.Length > 1) { function.ErrorMessage = $"More then one method called {handlerTokens[2]} was found. This tool does not currently support method overloading."; } else { function.ErrorMessage = $"Failed to find method {handlerTokens[2]}"; } return function; } // Search to see if a Lambda serializer is registered. var attribute = function.LambdaMethod.GetCustomAttribute(typeof(LambdaSerializerAttribute)) as LambdaSerializerAttribute ?? function.LambdaAssembly.GetCustomAttribute(typeof(LambdaSerializerAttribute)) as LambdaSerializerAttribute; if (attribute != null) { function.Serializer = Activator.CreateInstance(attribute.SerializerType) as ILambdaSerializer; } return function; } /// <summary> /// Execute the Lambda function. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<ExecutionResponse> ExecuteLambdaFunctionAsync(ExecutionRequest request) { return await (new LambdaExecutor()).ExecuteAsync(request); } public void Dispose() { } } }
169
aws-lambda-dotnet
aws
C#
using System; using Amazon.Lambda.Core; namespace Amazon.Lambda.TestTool.Runtime.LambdaMocks { public class LocalLambdaContext : ILambdaContext { public string AwsRequestId { get; set; } public IClientContext ClientContext { get; set; } public string FunctionName { get; set; } public string FunctionVersion { get; set; } public ICognitoIdentity Identity { get; set; } public string InvokedFunctionArn { get; set; } public ILambdaLogger Logger { get; set; } public string LogGroupName { get; set; } public string LogStreamName { get; set; } public int MemoryLimitInMB { get; set; } public TimeSpan RemainingTime { get; set; } } }
20
aws-lambda-dotnet
aws
C#
using System.Text; using Amazon.Lambda.Core; namespace Amazon.Lambda.TestTool.Runtime.LambdaMocks { public class LocalLambdaLogger : ILambdaLogger { private StringBuilder _buffer = new StringBuilder(); public void Log(string message) { _buffer.Append(message); } public void LogLine(string message) { _buffer.AppendLine(message); } public string Buffer { get { return this._buffer.ToString(); } } } }
25
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.TestTool.SampleRequests { public class LambdaRequest { public string Name { get; set; } public string Group { get; set; } public string Filename { get; set; } } }
9
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; namespace Amazon.Lambda.TestTool.SampleRequests { /// <summary> /// This class manages the sample Lambda input requests. This includes the precanned requests and saved requests. /// </summary> public class SampleRequestManager { public const string SAVED_REQUEST_GROUP = "Saved Requests"; public const string SAVED_REQUEST_DIRECTORY = "SavedRequests"; private string _preferenceDirectory; public SampleRequestManager(string preferenceDirectory) { this._preferenceDirectory = preferenceDirectory; } public IDictionary<string, IList<LambdaRequest>> GetSampleRequests() { var content = GetEmbeddedResource("manifest.xml"); XDocument xmlDoc = XDocument.Parse(content); var query = from item in xmlDoc.Descendants("request") select new { Name = item.Element("name").Value, Filename = item.Element("filename").Value }; var requests = from item in xmlDoc.Descendants("request") select new LambdaRequest { Group = item.Attribute("category")?.Value ?? string.Empty, Name = item.Element("name")?.Value ?? string.Empty, Filename = item.Element("filename")?.Value ?? string.Empty, }; var hash = new Dictionary<string, IList<LambdaRequest>>(); foreach (var request in requests) { IList<LambdaRequest> r; if (!hash.TryGetValue(request.Group, out r)) { r = new List<LambdaRequest>(); hash[request.Group] = r; } r.Add(request); } var savedRequestDirectory = GetSavedRequestDirectory(); if(Directory.Exists(savedRequestDirectory)) { var savedRequestFiles = Directory.GetFiles(GetSavedRequestDirectory(), "*.json"); if (savedRequestFiles.Length > 0) { var savedRequests = new List<LambdaRequest>(); hash[SAVED_REQUEST_GROUP] = savedRequests; foreach (var file in savedRequestFiles) { var r = new LambdaRequest { Filename = $"{SAVED_REQUEST_DIRECTORY}@{Path.GetFileName(file)}", Group = SAVED_REQUEST_GROUP, Name = Path.GetFileNameWithoutExtension(file) }; savedRequests.Add(r); } } } foreach (var key in hash.Keys.ToList()) { hash[key] = hash[key].OrderBy(x => x.Name).ToList(); } return hash; } public static bool TryDetermineSampleRequestName(string value, out string sampleName) { sampleName = null; if (value == null) return false; if (!value.StartsWith(SAVED_REQUEST_DIRECTORY)) return false; // The minus 6 is for the "@" and the trailing ".json" sampleName = value.Substring(SAVED_REQUEST_DIRECTORY.Length + 1, value.Length - SAVED_REQUEST_DIRECTORY.Length - 6); return true; } public string GetRequest(string name) { if(name.StartsWith(SAVED_REQUEST_DIRECTORY + "@")) { name = name.Substring(name.IndexOf("@") + 1); var path = Path.Combine(this.GetSavedRequestDirectory(), name); return File.ReadAllText(path); } return GetEmbeddedResource(name); } public string SaveRequest(string name, string content) { var filename = $"{name}.json"; var savedRequestDirectory = GetSavedRequestDirectory(); if (!Directory.Exists(savedRequestDirectory)) Directory.CreateDirectory(savedRequestDirectory); File.WriteAllText(Path.Combine(savedRequestDirectory, filename), content); return $"{SAVED_REQUEST_DIRECTORY}@{filename}"; } public string GetSaveRequestRelativePath(string name) { var relativePath = $"{SAVED_REQUEST_DIRECTORY}{Path.DirectorySeparatorChar}{name}"; if (!name.EndsWith(".json")) relativePath += ".json"; return relativePath; } private string GetEmbeddedResource(string name) { using (var stream = typeof(Amazon.Lambda.TestTool.Services.IAWSService).Assembly.GetManifestResourceStream( "Amazon.Lambda.TestTool.Resources.SampleRequests." + name)) using(var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public string GetSavedRequestDirectory() { var path = Path.Combine(this._preferenceDirectory, SAVED_REQUEST_DIRECTORY); return path; } } }
149
aws-lambda-dotnet
aws
C#
using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.SQS; using Amazon.SQS.Model; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.Lambda.TestTool.Services { public class AWSServiceImpl : IAWSService { public IList<string> ListProfiles() { var profileNames = new List<string>(); foreach (var profile in new CredentialProfileStoreChain().ListProfiles()) { // Guard against the same profile existing in both the .NET SDK encrypted store // and the shared credentials file. Lambda test tool does not have a mechanism // to specify the which store to use the profile from. if (!profileNames.Contains(profile.Name)) { profileNames.Add(profile.Name); } } return profileNames; } public async Task<IList<string>> ListQueuesAsync(string profile, string region) { var creds = GetCredentials(profile); var queues = new List<string>(); using (var client = new AmazonSQSClient(creds, RegionEndpoint.GetBySystemName(region))) { var response = await client.ListQueuesAsync(new ListQueuesRequest()); return response.QueueUrls; } } public async Task<Message> ReadMessageAsync(string profile, string region, string queueUrl) { var creds = GetCredentials(profile); using (var client = new AmazonSQSClient(creds, RegionEndpoint.GetBySystemName(region))) { var request = new ReceiveMessageRequest { QueueUrl = queueUrl, WaitTimeSeconds = 20, MaxNumberOfMessages = 1, VisibilityTimeout = 60, AttributeNames = new List<string>() { "All" }, MessageAttributeNames = new List<string>() { "*" } }; var response = await client.ReceiveMessageAsync(request); if (response.Messages.Count == 0) { return null; } return response.Messages[0]; } } public async Task DeleteMessageAsync(string profile, string region, string queueUrl, string receiptHandle) { var creds = GetCredentials(profile); using (var client = new AmazonSQSClient(creds, RegionEndpoint.GetBySystemName(region))) { var request = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiptHandle }; await client.DeleteMessageAsync(request); } } public async Task PurgeQueueAsync(string profile, string region, string queueUrl) { var creds = GetCredentials(profile); using (var client = new AmazonSQSClient(creds, RegionEndpoint.GetBySystemName(region))) { var request = new PurgeQueueRequest() { QueueUrl = queueUrl }; await client.PurgeQueueAsync(request); } } static AWSCredentials GetCredentials(string profileName) { AWSCredentials credentials = null; if (!string.IsNullOrEmpty(profileName)) { var chain = new CredentialProfileStoreChain(); chain.TryGetAWSCredentials(profileName, out credentials); } else { credentials = FallbackCredentialsFactory.GetCredentials(); } return credentials; } } }
113
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SQS.Model; namespace Amazon.Lambda.TestTool.Services { public interface IAWSService { IList<string> ListProfiles(); Task<IList<string>> ListQueuesAsync(string profile, string region); Task<Message> ReadMessageAsync(string profile, string region, string queueUrl); Task DeleteMessageAsync(string profile, string region, string queueUrl, string receiptHandle); Task PurgeQueueAsync(string profile, string region, string queueUrl); } }
22
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.TestTool.BlazorTester { public class Constants { public const int DEFAULT_PORT = 5050; public const string DEFAULT_HOST = "localhost"; #if NETCOREAPP3_1 public const string PRODUCT_NAME = "AWS .NET Core 3.1 Mock Lambda Test Tool"; #elif NET5_0 public const string PRODUCT_NAME = "AWS .NET Core 5.0 Mock Lambda Test Tool"; #elif NET6_0 public const string PRODUCT_NAME = "AWS .NET Core 6.0 Mock Lambda Test Tool"; #elif NET7_0 public const string PRODUCT_NAME = "AWS .NET Core 7.0 Mock Lambda Test Tool"; #else Update for new target framework!!! #endif public const string ResponseSuccessStyle = "white-space: pre-wrap; height: min-content; font-size: 75%; color: black"; public const string ResponseErrorStyle = "white-space: pre-wrap; height: min-content; font-size: 75%; color: red"; public const string ResponseSuccessStyleSizeConstraint = "white-space: pre-wrap; height: 300px; font-size: 75%; color: black"; public const string ResponseErrorStyleSizeConstraint = "white-space: pre-wrap; height: 300px; font-size: 75%; color: red"; public const string LINK_GITHUB_TEST_TOOL = "https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool"; public const string LINK_GITHUB_TEST_TOOL_INSTALL_AND_RUN = "https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool#installing-and-running"; public const string LINK_DLQ_DEVELOEPR_GUIDE = "https://docs.aws.amazon.com/lambda/latest/dg/dlq.html"; public const string LINK_MSDN_ASSEMBLY_LOAD_CONTEXT = "https://docs.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext"; public const string LINK_VS_TOOLKIT_MARKETPLACE = "https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.AWSToolkitforVisualStudio2017"; } }
34
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Amazon.Lambda.TestTool.BlazorTester { public class Program { public static void Main(string[] args) { Environment.SetEnvironmentVariable("AWS_EXECUTION_ENV", "AWS_DOTNET_LAMDBA_TEST_TOOL_BLAZOR_" + Utils.DetermineToolVersion()); TestToolStartup.Startup(Constants.PRODUCT_NAME, (options, showUI) => Startup.LaunchWebTester(options, showUI), args); } } }
23
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.TestTool.BlazorTester.Services; using Blazored.Modal; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Amazon.Lambda.TestTool.BlazorTester { public class Startup { public static void LaunchWebTester(LocalLambdaOptions lambdaOptions, bool openWindow) { var host = StartWebTesterAsync(lambdaOptions, openWindow).GetAwaiter().GetResult(); host.WaitForShutdown(); } public static async Task<IWebHost> StartWebTesterAsync(LocalLambdaOptions lambdaOptions, bool openWindow, CancellationToken token = default(CancellationToken)) { var host = string.IsNullOrEmpty(lambdaOptions.Host) ? Constants.DEFAULT_HOST : lambdaOptions.Host; var port = lambdaOptions.Port ?? Constants.DEFAULT_PORT; var url = $"http://{host}:{port}"; var contentPath = Path.GetFullPath(Directory.GetCurrentDirectory()); var builder = new WebHostBuilder() .UseKestrel() .SuppressStatusMessages(true) .ConfigureServices(services => services.AddSingleton(lambdaOptions)) .UseContentRoot(contentPath) .UseUrls(url) .UseStartup<Startup>(); var webHost = builder.Build(); await webHost.StartAsync(token); Console.WriteLine($"Environment running at {url}"); if (openWindow) { try { string launchUrl = Utils.DetermineLaunchUrl(host, port, Constants.DEFAULT_HOST); var info = new ProcessStartInfo { UseShellExecute = true, FileName = launchUrl }; Process.Start(info); } catch (Exception e) { Console.Error.WriteLine($"Error launching browser: {e.Message}"); } } return webHost; } 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. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IRuntimeApiDataStore, RuntimeApiDataStore>(); services.AddControllers(); services.AddRazorPages(); services.AddServerSideBlazor() .AddHubOptions(options => options.MaximumReceiveMessageSize = null); services.AddHttpContextAccessor(); services.AddBlazoredModal(); services.AddOptions<StaticFileOptions>() .PostConfigure(o => { var fileProvider = new ManifestEmbeddedFileProvider(typeof(Startup).Assembly, "wwwroot"); // Make sure we don't remove the existing file providers (blazor needs this) o.FileProvider = new CompositeFileProvider(o.FileProvider, fileProvider); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapBlazorHub(o => { o.ApplicationMaxBufferSize = 6 * (1024 * 1024); o.TransportMaxBufferSize = 6 * (1024 * 1024); }); endpoints.MapFallbackToPage("/_Host"); }); } } }
119
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.TestTool.BlazorTester.Services; using Microsoft.AspNetCore.Mvc; namespace Amazon.Lambda.TestTool.BlazorTester.Controllers { #if NET6_0_OR_GREATER public class RuntimeApiController : ControllerBase { private const string HEADER_BREAK = "-----------------------------------"; private readonly IRuntimeApiDataStore _runtimeApiDataStore; public RuntimeApiController(IRuntimeApiDataStore runtimeApiDataStore) { _runtimeApiDataStore = runtimeApiDataStore; } [HttpPost("/runtime/test-event")] [HttpPost("/2015-03-31/functions/function/invocations")] public async Task<IActionResult> PostTestEvent() { using var reader = new StreamReader(Request.Body); var testEvent = await reader.ReadToEndAsync(); _runtimeApiDataStore.QueueEvent(testEvent); return Accepted(); } [HttpPost("/2018-06-01/runtime/init/error")] public IActionResult PostInitError([FromHeader(Name = "Lambda-Runtime-Function-Error-Type")] string errorType, [FromBody] string error) { Console.Error.WriteLine("Init Error Type: " + errorType); Console.Error.WriteLine(error); Console.Error.WriteLine(HEADER_BREAK); return Accepted(new StatusResponse{Status = "success"}); } [HttpGet("/2018-06-01/runtime/invocation/next")] public async Task GetNextInvocation() { IEventContainer activeEvent; while (!_runtimeApiDataStore.TryActivateEvent(out activeEvent)) { await Task.Delay(TimeSpan.FromMilliseconds(100)); } Console.WriteLine(HEADER_BREAK); Console.WriteLine($"Next invocation returned: {activeEvent.AwsRequestId}"); Response.Headers["Lambda-Runtime-Aws-Request-Id"] = activeEvent.AwsRequestId; Response.Headers["Lambda-Runtime-Trace-Id"] = Guid.NewGuid().ToString(); Response.Headers["Lambda-Runtime-Invoked-Function-Arn"] = activeEvent.FunctionArn; Response.StatusCode = 200; if (activeEvent.EventJson?.Length != 0) { // The event is written directly to the response stream to avoid ASP.NET Core attempting any // encoding on content passed in the Ok() method. Response.Headers["Content-Type"] = "application/json"; var buffer = UTF8Encoding.UTF8.GetBytes(activeEvent.EventJson); await Response.Body.WriteAsync(buffer, 0, buffer.Length); Response.Body.Close(); } } [HttpPost("/2018-06-01/runtime/invocation/{awsRequestId}/response")] public async Task<IActionResult> PostInvocationResponse(string awsRequestId) { using var reader = new StreamReader(Request.Body); var response = await reader.ReadToEndAsync(); _runtimeApiDataStore.ReportSuccess(awsRequestId, response); Console.WriteLine(HEADER_BREAK); Console.WriteLine($"Response for request {awsRequestId}"); Console.WriteLine(response); return Accepted(new StatusResponse{Status = "success"}); } [HttpPost("/2018-06-01/runtime/invocation/{awsRequestId}/error")] public async Task<IActionResult> PostError(string awsRequestId, [FromHeader(Name = "Lambda-Runtime-Function-Error-Type")] string errorType) { using var reader = new StreamReader(Request.Body); var errorBody = await reader.ReadToEndAsync(); _runtimeApiDataStore.ReportError(awsRequestId, errorType, errorBody); await Console.Error.WriteLineAsync(HEADER_BREAK); await Console.Error.WriteLineAsync($"Request {awsRequestId} Error Type: {errorType}"); await Console.Error.WriteLineAsync(errorBody); return Accepted(new StatusResponse{Status = "success"}); } } internal class StatusResponse { [System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } } #endif }
105
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.TestTool.BlazorTester.Models { public class QueueItem { public string QueueUrl { get; set; } public string QueueName => this.QueueUrl.Substring(this.QueueUrl.LastIndexOf('/') + 1); } }
8
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; namespace Amazon.Lambda.TestTool.BlazorTester.Services { public interface IRuntimeApiDataStore { EventContainer QueueEvent(string eventBody); IReadOnlyList<IEventContainer> QueuedEvents { get; } IReadOnlyList<IEventContainer> ExecutedEvents { get; } void ClearQueued(); void ClearExecuted(); void DeleteEvent(string awsRequestId); IEventContainer ActiveEvent { get; } event EventHandler StateChange; bool TryActivateEvent(out IEventContainer activeEvent); void ReportSuccess(string awsRequestId, string response); void ReportError(string awsRequestId, string errorType, string errorBody); } public class RuntimeApiDataStore : IRuntimeApiDataStore { private IList<EventContainer> _queuedEvents = new List<EventContainer>(); private IList<EventContainer> _executedEvents = new List<EventContainer>(); private int _eventCounter = 1; private object _lock = new object(); public event EventHandler StateChange; public EventContainer QueueEvent(string eventBody) { var evnt = new EventContainer(this, _eventCounter++, eventBody); lock (_lock) { _queuedEvents.Add(evnt); } RaiseStateChanged(); return evnt; } public bool TryActivateEvent(out IEventContainer activeEvent) { activeEvent = null; lock(_lock) { if (!_queuedEvents.Any()) { return false; } var evnt = _queuedEvents[0]; _queuedEvents.RemoveAt(0); evnt.EventStatus = IEventContainer.Status.Executing; if (ActiveEvent != null) { _executedEvents.Add(ActiveEvent as EventContainer); } ActiveEvent = evnt; activeEvent = ActiveEvent; RaiseStateChanged(); return true; } } public IEventContainer ActiveEvent { get; private set; } public IReadOnlyList<IEventContainer> QueuedEvents { get { lock(_lock) { return new ReadOnlyCollection<EventContainer>(_queuedEvents.ToArray()); } } } public IReadOnlyList<IEventContainer> ExecutedEvents { get { lock(_lock) { return new ReadOnlyCollection<EventContainer>(_executedEvents.ToArray()); } } } public void ReportSuccess(string awsRequestId, string response) { lock(_lock) { var evnt = FindEventContainer(awsRequestId); if (evnt == null) { return; } evnt.ReportSuccessResponse(response); } RaiseStateChanged(); } public void ReportError(string awsRequestId, string errorType, string errorBody) { lock(_lock) { var evnt = FindEventContainer(awsRequestId); if (evnt == null) { return; } evnt.ReportErrorResponse(errorType, errorBody); } RaiseStateChanged(); } public void ClearQueued() { lock(_lock) { this._queuedEvents.Clear(); } RaiseStateChanged(); } public void ClearExecuted() { lock(_lock) { this._executedEvents.Clear(); } RaiseStateChanged(); } public void DeleteEvent(string awsRequestId) { lock(_lock) { var executedEvent = this._executedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, awsRequestId)); if (executedEvent != null) { this._executedEvents.Remove(executedEvent); } else { executedEvent = this._queuedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, awsRequestId)); if (executedEvent != null) { this._queuedEvents.Remove(executedEvent); } } } RaiseStateChanged(); } private EventContainer FindEventContainer(string awsRequestId) { if (string.Equals(this.ActiveEvent?.AwsRequestId, awsRequestId)) { return this.ActiveEvent as EventContainer; } var evnt = _executedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, awsRequestId)) as EventContainer; if (evnt != null) { return evnt; } evnt = _queuedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, awsRequestId)) as EventContainer; return evnt; } internal void RaiseStateChanged() { var handler = StateChange; handler?.Invoke(this, EventArgs.Empty); } } public interface IEventContainer { public enum Status {Queued, Executing, Success, Failure} string AwsRequestId { get; } string EventJson { get; } string ErrorResponse { get; } string ErrorType { get; } string Response { get; } Status EventStatus { get; } string FunctionArn { get; } DateTime LastUpdated { get; } } public class EventContainer : IEventContainer { private const string defaultFunctionArn = "arn:aws:lambda:us-west-2:123412341234:function:Function"; public string AwsRequestId { get; } public string EventJson { get; } public string ErrorResponse { get; private set; } public string ErrorType { get; private set; } public string Response { get; private set; } public DateTime LastUpdated { get; private set; } private IEventContainer.Status _status = IEventContainer.Status.Queued; public IEventContainer.Status EventStatus { get => _status; set { _status = value; LastUpdated = DateTime.Now; } } private readonly RuntimeApiDataStore _dataStore; public EventContainer(RuntimeApiDataStore dataStore, int eventCount, string eventJson) { LastUpdated = DateTime.Now; this._dataStore = dataStore; this.AwsRequestId = eventCount.ToString("D12"); this.EventJson = eventJson; } public string FunctionArn { get => defaultFunctionArn; } public void ReportSuccessResponse(string response) { LastUpdated = DateTime.Now; this.Response = response; this.EventStatus = IEventContainer.Status.Success; _dataStore.RaiseStateChanged(); } public void ReportErrorResponse(string errorType, string errorBody) { LastUpdated = DateTime.Now; this.ErrorType = errorType; this.ErrorResponse = errorBody; this.EventStatus = IEventContainer.Status.Failure; _dataStore.RaiseStateChanged(); } } }
270
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.TestTool.BlazorTester.Services; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.Lambda.TestTool.BlazorTester.Tests { public class RuntimeApiControllerTests { [Fact] public async Task ExecuteEventSuccessfully() { using var session = await TestSession.CreateSessionAsync(host: "*", port: 10111); using var queueResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri("/runtime/test-event", UriKind.Relative), Method = HttpMethod.Post, Content = new StringContent("\"raw data\"") }); Assert.Equal(HttpStatusCode.Accepted, queueResponse.StatusCode); Assert.Single(session.Store.QueuedEvents); using var getNextInvokeResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri("/2018-06-01/runtime/invocation/next", UriKind.Relative), Method = HttpMethod.Get, }); Assert.Equal(HttpStatusCode.OK, getNextInvokeResponse.StatusCode); Assert.Empty(session.Store.QueuedEvents); var awsRequestId = getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Aws-Request-Id").FirstOrDefault(); Assert.Equal(session.Store.ActiveEvent.AwsRequestId, awsRequestId); Assert.Single(getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Trace-Id")); Assert.Single(getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Invoked-Function-Arn")); var responseBody = await getNextInvokeResponse.Content.ReadAsStringAsync(); Assert.Equal("\"raw data\"", responseBody); using var postSuccessResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri($"/2018-06-01/runtime/invocation/{awsRequestId}/response", UriKind.Relative), Method = HttpMethod.Post, Content = new StringContent("\"Everything is good here\"") }); Assert.Equal(HttpStatusCode.Accepted, postSuccessResponse.StatusCode); Assert.Equal(IEventContainer.Status.Success, session.Store.ActiveEvent.EventStatus); Assert.Equal("\"Everything is good here\"", session.Store.ActiveEvent.Response); } [Fact] public async Task ExecuteEventFailure() { using var session = await TestSession.CreateSessionAsync(host: "example.com", port: 10112); using var queueResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri("/runtime/test-event", UriKind.Relative), Method = HttpMethod.Post, Content = new StringContent("\"this event will fail\"") }); Assert.Equal(HttpStatusCode.Accepted, queueResponse.StatusCode); Assert.Single(session.Store.QueuedEvents); using var getNextInvokeResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri("/2018-06-01/runtime/invocation/next", UriKind.Relative), Method = HttpMethod.Get, }); Assert.Equal(HttpStatusCode.OK, getNextInvokeResponse.StatusCode); Assert.Empty(session.Store.QueuedEvents); var awsRequestId = getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Aws-Request-Id").FirstOrDefault(); Assert.Equal(session.Store.ActiveEvent.AwsRequestId, awsRequestId); Assert.Single(getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Trace-Id")); Assert.Single(getNextInvokeResponse.Headers.GetValues("Lambda-Runtime-Invoked-Function-Arn")); var responseBody = await getNextInvokeResponse.Content.ReadAsStringAsync(); Assert.Equal("\"this event will fail\"", responseBody); var postFailureRequest = new HttpRequestMessage { RequestUri = new Uri($"/2018-06-01/runtime/invocation/{awsRequestId}/error", UriKind.Relative), Method = HttpMethod.Post, Content = new StringContent("\"Big long exception stacktrace\"") }; postFailureRequest.Headers.Add("Lambda-Runtime-Function-Error-Type", "Company.MyException"); using var postFailureResponse = await session.Client.SendAsync(postFailureRequest); Assert.Equal(HttpStatusCode.Accepted, postFailureResponse.StatusCode); Assert.Equal(IEventContainer.Status.Failure, session.Store.ActiveEvent.EventStatus); Assert.Equal("Company.MyException", session.Store.ActiveEvent.ErrorType); Assert.Equal("\"Big long exception stacktrace\"", session.Store.ActiveEvent.ErrorResponse); } [Fact] public async Task InitError() { using var session = await TestSession.CreateSessionAsync(host: "127.0.0.1", port: 10113); using var queueResponse = await session.Client.SendAsync(new HttpRequestMessage { RequestUri = new Uri("/2015-03-31/functions/function/invocations", UriKind.Relative), Method = HttpMethod.Post, Content = new StringContent("\"Failed to startup\"") }); Assert.Equal(HttpStatusCode.Accepted, queueResponse.StatusCode); } public class TestSession : IDisposable { private bool disposedValue; private CancellationTokenSource Source { get; set; } private string Host { get; set; } private int Port { get; set; } private IWebHost WebHost { get; set; } public HttpClient Client { get; private set; } public IRuntimeApiDataStore Store { get; private set; } public static async Task<TestSession> CreateSessionAsync(string host, int port) { var session = new TestSession() { Host = host, Port = port, Source = new CancellationTokenSource() }; var lambdaOptions = new LocalLambdaOptions() { Host = host, Port = port }; session.WebHost = await Startup.StartWebTesterAsync(lambdaOptions, false, session.Source.Token); var uriString = Utils.DetermineLaunchUrl(session.Host, session.Port, Constants.DEFAULT_HOST); session.Client = new HttpClient() { BaseAddress = new Uri(uriString) }; session.Store = session.WebHost.Services.GetService<IRuntimeApiDataStore>(); return session; } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this.Client.Dispose(); this.Source.Cancel(); this.WebHost.StopAsync().GetAwaiter().GetResult(); } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } } }
185
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.TestTool.BlazorTester.Services; using System.Collections.Generic; using System.Linq; using Xunit; namespace Amazon.Lambda.TestTool.BlazorTester.Tests { public class RuntimeApiDataStoreTests { [Fact] public void ActivateEvents() { var dataStore = new RuntimeApiDataStore(); IEventContainer evnt; Assert.False(dataStore.TryActivateEvent(out evnt)); Assert.Empty(dataStore.QueuedEvents); dataStore.QueueEvent("{}"); Assert.Single(dataStore.QueuedEvents); Assert.Equal(IEventContainer.Status.Queued, dataStore.QueuedEvents[0].EventStatus); Assert.True(dataStore.TryActivateEvent(out evnt)); Assert.Equal("{}", evnt.EventJson); Assert.Equal(evnt, dataStore.ActiveEvent); Assert.Equal(IEventContainer.Status.Executing, dataStore.ActiveEvent.EventStatus); Assert.Equal("{}", dataStore.ActiveEvent.EventJson); } [Fact] public void EnsureRequestIdsAreDifferent() { var dataStore = new RuntimeApiDataStore(); for(int i = 0; i< 10; i++) { dataStore.QueueEvent("{}"); } Assert.Equal(10, dataStore.QueuedEvents.Count); var requestIds = new HashSet<string>(); for(int i = 0;i < 10;i++) { Assert.True(dataStore.TryActivateEvent(out var evnt)); Assert.DoesNotContain(evnt.AwsRequestId, requestIds); requestIds.Add(evnt.AwsRequestId); } // This is 9 because the 10th event is the active event. Assert.Equal(9, dataStore.ExecutedEvents.Count); } [Fact] public void ReportSuccess() { var dataStore = new RuntimeApiDataStore(); dataStore.QueueEvent("{}"); Assert.Equal(IEventContainer.Status.Queued, dataStore.QueuedEvents[0].EventStatus); Assert.True(dataStore.TryActivateEvent(out var evnt)); dataStore.ReportSuccess(evnt.AwsRequestId, "\"Success\""); Assert.Equal(IEventContainer.Status.Success, dataStore.ActiveEvent.EventStatus); Assert.Equal("\"Success\"", dataStore.ActiveEvent.Response); } [Fact] public void ReportError() { var dataStore = new RuntimeApiDataStore(); dataStore.QueueEvent("{}"); Assert.Equal(IEventContainer.Status.Queued, dataStore.QueuedEvents[0].EventStatus); Assert.True(dataStore.TryActivateEvent(out var evnt)); dataStore.ReportError(evnt.AwsRequestId, "BadError", "\"YouFail\""); Assert.Equal(IEventContainer.Status.Failure, dataStore.ActiveEvent.EventStatus); Assert.Equal("BadError", dataStore.ActiveEvent.ErrorType); Assert.Equal("\"YouFail\"", dataStore.ActiveEvent.ErrorResponse); } [Fact] public void ClearQueue() { var dataStore = new RuntimeApiDataStore(); for (int i = 0; i < 10; i++) { dataStore.QueueEvent("{}"); } Assert.Equal(10, dataStore.QueuedEvents.Count); dataStore.ClearQueued(); Assert.Empty(dataStore.QueuedEvents); } [Fact] public void ClearExecuted() { var dataStore = new RuntimeApiDataStore(); for (int i = 0; i < 10; i++) { dataStore.QueueEvent("{}"); } Assert.Equal(10, dataStore.QueuedEvents.Count); for (int i = 0; i < 10; i++) { Assert.True(dataStore.TryActivateEvent(out _)); } // This is 9 because the 10th event is the active event. Assert.Equal(9, dataStore.ExecutedEvents.Count); dataStore.ClearExecuted(); Assert.Empty(dataStore.ExecutedEvents); } [Fact] public void DeleteEvent() { var dataStore = new RuntimeApiDataStore(); for (int i = 0; i < 10; i++) { dataStore.QueueEvent("{}"); } for (int i = 0; i < 5; i++) { Assert.True(dataStore.TryActivateEvent(out _)); } Assert.Equal(5, dataStore.QueuedEvents.Count); Assert.Equal(4, dataStore.ExecutedEvents.Count); var deletedQueueEvent = dataStore.QueuedEvents[1]; dataStore.DeleteEvent(deletedQueueEvent.AwsRequestId); Assert.Equal(4, dataStore.QueuedEvents.Count); Assert.Equal(4, dataStore.ExecutedEvents.Count); Assert.Null(dataStore.QueuedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, deletedQueueEvent.AwsRequestId))); var deletedExecutedEvent = dataStore.ExecutedEvents[1]; dataStore.DeleteEvent(deletedExecutedEvent.AwsRequestId); Assert.Equal(4, dataStore.QueuedEvents.Count); Assert.Equal(3, dataStore.ExecutedEvents.Count); Assert.Null(dataStore.ExecutedEvents.FirstOrDefault(x => string.Equals(x.AwsRequestId, deletedExecutedEvent.AwsRequestId))); dataStore.DeleteEvent("does-not-exist"); Assert.Equal(4, dataStore.QueuedEvents.Count); Assert.Equal(3, dataStore.ExecutedEvents.Count); } } }
153
aws-lambda-dotnet
aws
C#
namespace Amazon.Lambda.TestTool.Tests.NET6 { public class SourceGeneratorTests { [Fact] public void SourceGeneratorInputAndOutput() { var runConfiguration = new TestToolStartup.RunConfiguration { Mode = TestToolStartup.RunConfiguration.RunMode.Test, OutputWriter = new StringWriter() }; var buildPath = Path.GetFullPath($"../../../../LambdaFunctions/net6/SourceGeneratorExample/bin/debug/net6.0"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "{\"Name\" : \"FooBar\"}", "--config-file", "SourceGeneratorInputAndOutput.json" }, runConfiguration); Assert.Contains("Response = FooBar", runConfiguration.OutputWriter.ToString()); } [Fact] public void SourceGeneratorAsyncInputOnly() { var runConfiguration = new TestToolStartup.RunConfiguration { Mode = TestToolStartup.RunConfiguration.RunMode.Test, OutputWriter = new StringWriter() }; var buildPath = Path.GetFullPath($"../../../../LambdaFunctions/net6/SourceGeneratorExample/bin/debug/net6.0"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "{\"Name\" : \"FooBar\"}", "--config-file", "SourceGeneratorAsyncInputOnly.json" }, runConfiguration); Assert.Contains("Calling function with:", runConfiguration.OutputWriter.ToString()); Assert.DoesNotContain("Error:", runConfiguration.OutputWriter.ToString()); } } }
34
aws-lambda-dotnet
aws
C#
global using Xunit;
1
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection.PortableExecutable; using System.Threading.Tasks; using Amazon.Lambda.TestTool.Services; using Xunit; using Amazon.SQS; using Amazon.SQS.Model; using Newtonsoft.Json; namespace Amazon.Lambda.TestTool.Tests { public class AwsServiceTests { [Fact] public void ListProfiles() { if (!TestUtils.ProfileTestsEnabled) return; var aws = new AWSServiceImpl(); var profiles = aws.ListProfiles(); Assert.NotEmpty(profiles); foreach (var profile in profiles) { Assert.False(string.IsNullOrWhiteSpace(profile)); } Assert.True(profiles.Contains(TestUtils.TestProfile)); } [Fact] public async Task ListQueuesAsync() { if (!TestUtils.ProfileTestsEnabled) return; var queueName = "local-reader-list-queue-test-" + DateTime.Now.Ticks; using (var client = new AmazonSQSClient(TestUtils.GetAWSCredentials(), TestUtils.TestRegion)) { var createResponse = await client.CreateQueueAsync(new CreateQueueRequest {QueueName = queueName}); await TestUtils.WaitTillQueueIsCreatedAsync(client, createResponse.QueueUrl); try { var aws = new AWSServiceImpl(); var queues = await aws.ListQueuesAsync(TestUtils.TestProfile, TestUtils.TestRegion.SystemName); Assert.True(queues.Contains(createResponse.QueueUrl)); } finally { await client.DeleteQueueAsync(createResponse.QueueUrl); } } } [Fact] public async Task ReadMessageAsync() { if (!TestUtils.ProfileTestsEnabled) return; var queueName = "local-reader-read-message-test-" + DateTime.Now.Ticks; using (var client = new AmazonSQSClient(TestUtils.GetAWSCredentials(), TestUtils.TestRegion)) { var createResponse = await client.CreateQueueAsync(new CreateQueueRequest {QueueName = queueName}); await TestUtils.WaitTillQueueIsCreatedAsync(client, createResponse.QueueUrl); try { var aws = new AWSServiceImpl(); var message = await aws.ReadMessageAsync(TestUtils.TestProfile, TestUtils.TestRegion.SystemName, createResponse.QueueUrl); Assert.Null(message); await client.SendMessageAsync(new SendMessageRequest { MessageBody = "data", QueueUrl = createResponse.QueueUrl }); message = await aws.ReadMessageAsync(TestUtils.TestProfile, TestUtils.TestRegion.SystemName, createResponse.QueueUrl); Assert.NotNull(message); await aws.DeleteMessageAsync(TestUtils.TestProfile, TestUtils.TestRegion.SystemName, createResponse.QueueUrl, message.ReceiptHandle); } finally { await client.DeleteQueueAsync(createResponse.QueueUrl); } } } } }
97
aws-lambda-dotnet
aws
C#
using Xunit; namespace Amazon.Lambda.TestTool.Tests { public class CommandLineParserTests { [Fact] public void AllValuesGetSet() { var options = CommandLineOptions.Parse(new string[] {"--help", "--host", "example.com", "--port", "1111", "--no-launch-window", "--path", "./foo", "--profile", "test", "--region", "special-region", "--no-ui", "--config-file", "test-config.json", "--payload", "myfile.json", "--pause-exit", "false" }); Assert.True(options.ShowHelp); Assert.Equal("example.com", options.Host); Assert.Equal(1111, options.Port); Assert.True(options.NoLaunchWindow); Assert.Equal("./foo", options.Path); Assert.Equal("test", options.AWSProfile); Assert.Equal("special-region", options.AWSRegion); Assert.True(options.NoUI); Assert.Equal("test-config.json", options.ConfigFile); Assert.Equal("myfile.json", options.Payload); Assert.False(options.PauseExit); } [Fact] public void NoArguments() { var options = CommandLineOptions.Parse(new string[0]); Assert.NotNull(options); } [Fact] public void ParseIntValueForSwitch() { var options = CommandLineOptions.Parse(new string[] { "--port", "8080" }); Assert.Equal(8080, options.Port); } [Fact] public void MissingValue() { Assert.Throws<CommandLineParseException>(() => CommandLineOptions.Parse(new string[] { "--port" })); } [Fact] public void ValueNotAnInt() { Assert.Throws<CommandLineParseException>(() => CommandLineOptions.Parse(new string[] { "--port", "aaa" })); } [Fact] public void BoolSwitchWithoutValueLast() { var options = CommandLineOptions.Parse(new string[] { "--no-ui" }); Assert.True(options.NoUI); } [Fact] public void BoolSwitchWithoutValue() { var options = CommandLineOptions.Parse(new string[] { "--no-ui", "--profile", "test" }); Assert.True(options.NoUI); Assert.Equal("test", options.AWSProfile); } [Fact] public void BoolSwitchValueLast() { var options = CommandLineOptions.Parse(new string[0]); Assert.True(options.PauseExit); options = CommandLineOptions.Parse(new string[] { "--pause-exit", "false" }); Assert.False(options.PauseExit); } [Fact] public void BoolSwitchValue() { var options = CommandLineOptions.Parse(new string[0]); Assert.True(options.PauseExit); options = CommandLineOptions.Parse(new string[] { "--pause-exit", "false", "--profile", "test" }); Assert.False(options.PauseExit); Assert.Equal("test", options.AWSProfile); } } }
92
aws-lambda-dotnet
aws
C#
using System; using Xunit; using Amazon.Lambda.TestTool; using Amazon.Lambda.TestTool.Runtime; using Amazon.Lambda.TestTool.Runtime.LambdaMocks; namespace Amazon.Lambda.TestTool.Tests { public class ConsoleCaptureTests { [Fact] public void CaptureStandardOut() { var logger = new LocalLambdaLogger(); using (var captiure = new ConsoleOutWrapper(logger)) { Console.WriteLine("CAPTURED"); } Console.WriteLine("NOT_CAPTURED"); Assert.Contains("CAPTURED", logger.Buffer); Assert.DoesNotContain("NOT_CAPTURED", logger.Buffer); } [Fact] public void CaptureStandardError() { var logger = new LocalLambdaLogger(); using (var captiure = new ConsoleOutWrapper(logger)) { Console.Error.WriteLine("CAPTURED"); } Console.Error.WriteLine("NOT_CAPTURED"); Assert.Contains("CAPTURED", logger.Buffer); Assert.DoesNotContain("NOT_CAPTURED", logger.Buffer); } } }
41
aws-lambda-dotnet
aws
C#
using System; using System.IO; using Xunit; using Amazon.Lambda.TestTool.Runtime; using Amazon.Lambda.AspNetCoreServer.Internal; using System.Collections.Generic; namespace Amazon.Lambda.TestTool.Tests { public class DefaultsFileParseTests { [Fact] public void LambdaFunctionWithNoName() { var jsonFile = WriteTempConfigFile("{\"function-handler\" : \"Assembly::Type::Method\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Single(configInfo.FunctionInfos); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Name); } finally { File.Delete(jsonFile); } } [Fact] public void LambdaFunctionWithName() { var jsonFile = WriteTempConfigFile("{\"function-handler\" : \"Assembly::Type::Method\", \"function-name\" : \"TheFunc\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Single(configInfo.FunctionInfos); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler); Assert.Equal("TheFunc", configInfo.FunctionInfos[0].Name); } finally { File.Delete(jsonFile); } } [Fact] public void LambdaFunctionWithEnvironmentVariables() { var jsonFile = WriteTempConfigFile("{\"function-handler\" : \"Assembly::Type::Method\", \"environment-variables\" : \"key1=value1;key2=value2\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Single(configInfo.FunctionInfos); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler); Assert.Equal(2, configInfo.FunctionInfos[0].EnvironmentVariables.Count); Assert.Equal("value1", configInfo.FunctionInfos[0].EnvironmentVariables["key1"]); Assert.Equal("value2", configInfo.FunctionInfos[0].EnvironmentVariables["key2"]); } finally { File.Delete(jsonFile); } } [Fact] public void LambdaFunctionWithQuotedEnvironmentVariables() { var jsonFile = WriteTempConfigFile("{\"function-handler\" : \"Assembly::Type::Method\", \"environment-variables\" : \"\\\"key1\\\"=\\\"value1\\\";\\\"key2\\\"=\\\"value2\\\"\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Single(configInfo.FunctionInfos); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler); Assert.Equal(2, configInfo.FunctionInfos[0].EnvironmentVariables.Count); Assert.Equal("value1", configInfo.FunctionInfos[0].EnvironmentVariables["key1"]); Assert.Equal("value2", configInfo.FunctionInfos[0].EnvironmentVariables["key2"]); } finally { File.Delete(jsonFile); } } [Fact] public void LambdaFunctionWithImageCommand() { var jsonFile = WriteTempConfigFile("{\"image-command\" : \"Assembly::Type::Method\", \"function-name\" : \"TheFunc\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Single(configInfo.FunctionInfos); Assert.Equal("Assembly::Type::Method", configInfo.FunctionInfos[0].Handler); Assert.Equal("TheFunc", configInfo.FunctionInfos[0].Name); } finally { File.Delete(jsonFile); } } [Fact] public void NoProfile() { var jsonFile = WriteTempConfigFile("{}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Equal("default", configInfo.AWSProfile); } finally { File.Delete(jsonFile); } } [Fact] public void NonDefaultProfile() { var jsonFile = WriteTempConfigFile("{\"profile\" : \"test-profile\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Equal("test-profile", configInfo.AWSProfile); } finally { File.Delete(jsonFile); } } [Fact] public void NoRegion() { var jsonFile = WriteTempConfigFile("{}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Null(configInfo.AWSRegion); } finally { File.Delete(jsonFile); } } [Fact] public void SetRegion() { var jsonFile = WriteTempConfigFile("{\"region\" : \"us-west-2\"}"); try { var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(jsonFile); Assert.Equal("us-west-2", configInfo.AWSRegion); } finally { File.Delete(jsonFile); } } [Fact] public void LoadServerlessTemplateConfig() { var defaultsFilePath = TestUtils.GetLambdaFunctionSourceFile("ServerlessTemplateExample", "aws-lambda-tools-defaults.json"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath); Assert.Equal(4, configInfo.FunctionInfos.Count); Assert.Equal("default", configInfo.AWSProfile); Assert.Equal("us-west-2", configInfo.AWSRegion); Assert.Equal("AFunction", configInfo.FunctionInfos[0].Name); Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::AFunction", configInfo.FunctionInfos[0].Handler); Assert.Equal("MyHelloWorld", configInfo.FunctionInfos[1].Name); Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::HelloWorld", configInfo.FunctionInfos[1].Handler); Assert.Equal("MyHelloWorldImageCommand", configInfo.FunctionInfos[2].Name); Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::HelloWorldImageFunction", configInfo.FunctionInfos[2].Handler); Assert.Equal("MyToUpper", configInfo.FunctionInfos[3].Name); Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::ToUpper", configInfo.FunctionInfos[3].Handler); } [Fact] public void LoadServerlessResourceBasedYamlTemplateConfig() { var defaultsFilePath = TestUtils.GetLambdaFunctionSourceFile("ServerlessTemplateYamlExample", "aws-lambda-tools-defaults.json"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath); Assert.Equal(4, configInfo.FunctionInfos.Count); Assert.Equal("default", configInfo.AWSProfile); Assert.Equal("us-west-2", configInfo.AWSRegion); Assert.Equal("AFunction", configInfo.FunctionInfos[0].Name); Assert.Equal("ServerlessTemplateYamlExample::ServerlessTemplateYamlExample.Functions::AFunction", configInfo.FunctionInfos[0].Handler); Assert.Equal("MyHelloWorld", configInfo.FunctionInfos[1].Name); Assert.Equal("ServerlessTemplateYamlExample::ServerlessTemplateYamlExample.Functions::HelloWorld", configInfo.FunctionInfos[1].Handler); Assert.Equal("MyHelloWorldImageCommand", configInfo.FunctionInfos[2].Name); Assert.Equal("ServerlessTemplateExample::ServerlessTemplateExample.Functions::HelloWorldImageFunction", configInfo.FunctionInfos[2].Handler); Assert.Equal("MyToUpper", configInfo.FunctionInfos[3].Name); Assert.Equal("ServerlessTemplateYamlExample::ServerlessTemplateYamlExample.Functions::ToUpper", configInfo.FunctionInfos[3].Handler); } [Fact] public void LoadServerlessFunctionBasedYamlTemplateConfig() { var defaultsFilePath = TestUtils.GetLambdaFunctionSourceFile("ServerlessFunctionTemplateYamlExample", "aws-lambda-tools-defaults.json"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(defaultsFilePath); Assert.Equal(3, configInfo.FunctionInfos.Count); Assert.Equal("default", configInfo.AWSProfile); Assert.Equal("us-west-2", configInfo.AWSRegion); Assert.Equal("create", configInfo.FunctionInfos[0].Name); Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.CreateItemFunction::Run", configInfo.FunctionInfos[0].Handler); Assert.Equal("get", configInfo.FunctionInfos[1].Name); Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.GetItemFunction::Run", configInfo.FunctionInfos[1].Handler); Assert.Equal("update", configInfo.FunctionInfos[2].Name); Assert.Equal("DotNetServerless.Lambda::DotNetServerless.Lambda.Functions.UpdateItemFunction::Run", configInfo.FunctionInfos[2].Handler); } [Fact] public void ParseKeyValueParameter() { var parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("Table=Blog", parameters); Assert.Single(parameters); Assert.Equal("Blog", parameters["Table"]); parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("Table=Blog;", parameters); Assert.Single(parameters); Assert.Equal("Blog", parameters["Table"]); parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("\"ConnectionString\"=\"User=foo;Password=test\"", parameters); Assert.Single(parameters); Assert.Equal("User=foo;Password=test", parameters["ConnectionString"]); } [Fact] public void ParseTwoKeyValueParameter() { var parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("Table=Blog;Bucket=MyBucket", parameters); Assert.Equal(2, parameters.Count); Assert.Equal("Blog", parameters["Table"]); Assert.Equal("MyBucket", parameters["Bucket"]); parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("\"ConnectionString1\"=\"User=foo;Password=test\";\"ConnectionString2\"=\"Password=test;User=foo\"", parameters); Assert.Equal(2, parameters.Count); Assert.Equal("User=foo;Password=test", parameters["ConnectionString1"]); Assert.Equal("Password=test;User=foo", parameters["ConnectionString2"]); } [Fact] public void ParseEmptyValue() { var parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("ShouldCreateTable=true;BlogTableName=", parameters); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); parameters = new Dictionary<string, string>(); LambdaDefaultsConfigFileParser.ParseKeyValueOption("BlogTableName=;ShouldCreateTable=true", parameters); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); } [Fact] public void ParseErrors() { var parameters = new Dictionary<string, string>(); Assert.Throws<CommandLineParseException>(() => LambdaDefaultsConfigFileParser.ParseKeyValueOption("=aaa", parameters)); } private string WriteTempConfigFile(string json) { var filePath = Path.GetTempFileName(); File.WriteAllText(filePath, json); return filePath; } } }
303
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection.PortableExecutable; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.TestTool.Runtime; using Xunit; using Amazon.SQS; using Amazon.SQS.Model; namespace Amazon.Lambda.TestTool.Tests { public class DlqMonitorTests { [Fact] public async Task DlqIntegTest() { if (!TestUtils.ProfileTestsEnabled) return; const int WAIT_TIME = 5000; var queueName = "local-dlq-list-queue-test-" + DateTime.Now.Ticks; using (var client = new AmazonSQSClient(TestUtils.GetAWSCredentials(), TestUtils.TestRegion)) { var createResponse = await client.CreateQueueAsync(new CreateQueueRequest {QueueName = queueName}); await TestUtils.WaitTillQueueIsCreatedAsync(client, createResponse.QueueUrl); try { var configFile = TestUtils.GetLambdaFunctionSourceFile("ToUpperFunc", "stream-function.json"); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile); var runtime = LocalLambdaRuntime.Initialize(buildPath); var function = runtime.LoadLambdaFunctions(configInfo.FunctionInfos)[0]; var monitor = new DlqMonitor(runtime, function, TestUtils.TestProfile, TestUtils.TestRegion.SystemName, createResponse.QueueUrl); monitor.Start(); await client.SendMessageAsync(new SendMessageRequest { QueueUrl = createResponse.QueueUrl, MessageBody = "\"testing dlq\"" }); Thread.Sleep(WAIT_TIME); var logs = monitor.FetchNewLogs(); Assert.Single(logs); Assert.Contains("testing dlq", logs[0].Logs); Assert.NotNull(logs[0].ReceiptHandle); Assert.NotEqual(DateTime.MinValue, logs[0].ProcessTime); logs = monitor.FetchNewLogs(); Assert.Equal(0, logs.Count); await client.SendMessageAsync(new SendMessageRequest { QueueUrl = createResponse.QueueUrl, MessageBody = "\"testing dlq1\"" }); await client.SendMessageAsync(new SendMessageRequest { QueueUrl = createResponse.QueueUrl, MessageBody = "\"testing dlq2\"" }); Thread.Sleep(WAIT_TIME); logs = monitor.FetchNewLogs(); Assert.Equal(2, logs.Count); monitor.Stop(); Thread.Sleep(WAIT_TIME); await client.SendMessageAsync(new SendMessageRequest { QueueUrl = createResponse.QueueUrl, MessageBody = "\"testing dlq3\"" }); Thread.Sleep(WAIT_TIME); logs = monitor.FetchNewLogs(); Assert.Equal(0, logs.Count); } finally { await client.DeleteQueueAsync(createResponse.QueueUrl); } } } } }
92
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using Xunit; using Amazon.Lambda.TestTool.Runtime; using System.Threading.Tasks; namespace Amazon.Lambda.TestTool.Tests { public class InvokeFunctionTests { [Fact] public async Task StringToStringWithContextTest() { var payload = "\"TestData\""; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::StringToStringWithContext", payload); Assert.True(response.IsSuccess); Assert.Equal("\"StringToStringWithContext-TestData\"", response.Response); } [Fact] public async Task NoParametersTest() { var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::NoParameters", null); Assert.True(response.IsSuccess); Assert.Equal("\"NoParameters\"", response.Response); } [Fact] public async Task VoidReturnTest() { var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::VoidReturn", null); Assert.True(response.IsSuccess); Assert.Null(response.Response); } [Fact] public async Task NoContextWithParameterTest() { var payload = "\"TestData\""; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::NoContextWithParameter", payload); Assert.True(response.IsSuccess); Assert.Equal("\"NoContextWithParameter-TestData\"", response.Response); } [Fact] public async Task TheStaticMethodTest() { var payload = "\"TestData\""; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.StaticMethods::TheStaticMethod", payload); Assert.True(response.IsSuccess); Assert.Equal("\"TheStaticMethod-TestData\"", response.Response); } [Fact] public async Task WithGenericParameterTest() { var payload = "[\"Value1\", \"Value2\"]"; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::WithGenericParameter", payload); Assert.True(response.IsSuccess); Assert.Equal("\"Value1,Value2\"", response.Response); } [Fact] public async Task WithEventParameterTest() { var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.InstanceMethods::WithEventParameter", null); Assert.True(response.IsSuccess); Assert.Equal("\"WithEventParameter-event-not-null\"", response.Response); } [Fact] public async Task TaskWithNoResultTest() { var payload = "\"TestData\""; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.AsyncMethods::TaskWithNoResult", payload); Assert.True(response.IsSuccess); Assert.Null(response.Response); } [Fact] public async Task TaskWithResultTest() { var payload = "\"TestData\""; var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.AsyncMethods::TaskWithResult", payload); Assert.True(response.IsSuccess); Assert.Equal("\"TaskWithResult-TestData\"", response.Response); } [Fact] public async Task AsyncNoResultThrowExceptionTest() { var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.ErrorFunctions::AsyncNoResultThrowException", null); Assert.False(response.IsSuccess); Assert.NotNull(response.Error); } [Fact] public async Task AsyncWithResultThrowExceptionTest() { var response = await ExecuteFunctionAsync( "FunctionSignatureExamples::FunctionSignatureExamples.ErrorFunctions::AsyncWithResultThrowException", null); Assert.False(response.IsSuccess); Assert.NotNull(response.Error); } #if NETCORE_3_1 [Fact] public async Task CallValuesControllerInAspNetCoreApp() { var payload = File.ReadAllText("call-valuescontroller-request.txt"); var response = await ExecuteFunctionAsync("AspNetCoreAPIExample", "AspNetCoreAPIExample::AspNetCoreAPIExample.LambdaEntryPoint::FunctionHandlerAsync", payload); Assert.True(response.IsSuccess); Assert.Contains("value1", response.Response); } #endif private async Task<ExecutionResponse> ExecuteFunctionAsync(string handler, string payload) { return await ExecuteFunctionAsync("FunctionSignatureExamples", handler, payload); } private async Task<ExecutionResponse> ExecuteFunctionAsync(string projectName, string handler, string payload) { var buildPath = TestUtils.GetLambdaFunctionBuildPath(projectName); var runtime = LocalLambdaRuntime.Initialize(buildPath); var configInfo = new LambdaFunctionInfo { Name = "TestMethod", Handler = handler }; var function = runtime.LoadLambdaFunction(configInfo); Assert.True(function.IsSuccess); var request = new ExecutionRequest() { Function = function, AWSRegion = "us-west-2", Payload = payload }; var response = await runtime.ExecuteLambdaFunctionAsync(request); return response; } } }
193
aws-lambda-dotnet
aws
C#
using System; using System.IO; using Xunit; using Amazon.Lambda.TestTool.Runtime; namespace Amazon.Lambda.TestTool.Tests { public class LoadLambdaFunctionTests { [Fact] public void LoadInstanceMethodWithAssemblySerializer() { var configFile = TestUtils.GetLambdaFunctionSourceFile("S3EventFunction", "aws-lambda-tools-defaults.json"); var buildPath = TestUtils.GetLambdaFunctionBuildPath("S3EventFunction"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile); Assert.Single(configInfo.FunctionInfos); var runtime = LocalLambdaRuntime.Initialize(buildPath); var functions = runtime.LoadLambdaFunctions(configInfo.FunctionInfos); Assert.Equal(1, functions.Count); var function = functions[0]; Assert.True(function.IsSuccess); Assert.NotNull(function.LambdaAssembly); Assert.NotNull(function.LambdaType); Assert.NotNull(function.LambdaMethod); Assert.NotNull(function.Serializer); } [Fact] public void LoadStaticMethodWithMethodSerializer() { var configFile = TestUtils.GetLambdaFunctionSourceFile("ToUpperFunc", "aws-lambda-tools-defaults.json"); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); var configInfo = LambdaDefaultsConfigFileParser.LoadFromFile(configFile); Assert.Single(configInfo.FunctionInfos); var runtime = LocalLambdaRuntime.Initialize(buildPath); var functions = runtime.LoadLambdaFunctions(configInfo.FunctionInfos); Assert.Equal(1, functions.Count); var function = functions[0]; Assert.True(function.IsSuccess); Assert.NotNull(function.LambdaAssembly); Assert.NotNull(function.LambdaType); Assert.NotNull(function.LambdaMethod); Assert.NotNull(function.Serializer); } } }
59
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using Amazon.Lambda.TestTool; namespace Amazon.Lambda.TestTool.Tests { public class NoUiStartupTests { [Fact] public void DirectFunctionCallFromConfig() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"" }, runConfiguration); Assert.Contains("HELLO WORLD", runConfiguration.OutputWriter.ToString()); } [Fact] public void DirectFunctionCallNotFromConfig() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"", "--function-handler", "ToUpperFunc::ToUpperFunc.Function::ToLower" }, runConfiguration); Assert.Contains("hello world", runConfiguration.OutputWriter.ToString()); } [Fact] public void PayloadFromFile() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "payload-sample.json" }, runConfiguration); Assert.Contains("HELLO FROM PAYLOAD FILE", runConfiguration.OutputWriter.ToString()); } [Fact] public void ServerlessTemplateFunctionCall() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ServerlessTemplateExample"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"", "--function-handler", "ServerlessTemplateExample::ServerlessTemplateExample.Functions::HelloWorld" }, runConfiguration); Assert.Contains("Hello World Test", runConfiguration.OutputWriter.ToString()); } [Fact] public void ProjectHasMultipleLambdaFunctionsAndFunctionHandlerNotGiven() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ServerlessTemplateExample"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"" }, runConfiguration); Assert.Contains("Project has more then one Lambda function defined. Use the --function-handler switch to identify the Lambda code to execute.", runConfiguration.OutputWriter.ToString()); } [Fact] public void UseProfileAndRegionFromConfigFile() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"" }, runConfiguration); Assert.Contains("HELLO WORLD", runConfiguration.OutputWriter.ToString()); Assert.Contains("Setting AWS_REGION environment variable to us-west-2.", runConfiguration.OutputWriter.ToString()); } [Fact] public void UseExplicitRegion() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("ToUpperFunc"); TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--payload", "\"hello WORLD\"", "--region", "fake-region" }, runConfiguration); Assert.Contains("HELLO WORLD", runConfiguration.OutputWriter.ToString()); Assert.Contains("Setting AWS_REGION environment variable to fake-region.", runConfiguration.OutputWriter.ToString()); } [Fact] public void NoProfileAndRegion() { var runConfiguration = CreateRunConfiguration(); var buildPath = TestUtils.GetLambdaFunctionBuildPath("FunctionSignatureExamples"); // Profile is set to a nonexisting profile because if no profile is set on the command line or config file then the default profile will be set if it exists. TestToolStartup.Startup("Unit Tests", null, new string[] { "--path", buildPath, "--no-ui", "--profile", "do-no-exist", "--payload", "\"hello WORLD\"", "--function-handler", "FunctionSignatureExamples::FunctionSignatureExamples.StaticMethods::TheStaticMethod" }, runConfiguration); Assert.Contains("Warning: Profile do-no-exist not found in the aws credential store.", runConfiguration.OutputWriter.ToString()); Assert.Contains("No default AWS region configured. The --region switch can be used to configure an AWS Region.", runConfiguration.OutputWriter.ToString()); } private TestToolStartup.RunConfiguration CreateRunConfiguration() { return new TestToolStartup.RunConfiguration { Mode = TestToolStartup.RunConfiguration.RunMode.Test, OutputWriter = new StringWriter() }; } } }
109
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using Amazon.Lambda.TestTool.SampleRequests; namespace Amazon.Lambda.TestTool.Tests { public class SampleRequestTests { [Theory] [InlineData("[email protected]", "foo")] [InlineData("[email protected]", null)] public void DetermineSampleName(string testValue, string expected) { string determined; if(SampleRequestManager.TryDetermineSampleRequestName(testValue, out determined)) { Assert.NotNull(expected); Assert.Equal(expected, determined); } else { Assert.Null(expected); } } } }
31
aws-lambda-dotnet
aws
C#
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.SQS; using Amazon.SQS.Model; namespace Amazon.Lambda.TestTool.Tests { public static class TestUtils { public static string TestProfile { get { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TEST_TOOL_TEST_PROFILE"))) return "default"; return Environment.GetEnvironmentVariable("LAMBDA_TEST_TOOL_TEST_PROFILE"); } } public static RegionEndpoint TestRegion { get { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TEST_TOOL_TEST_REGION"))) return RegionEndpoint.USEast1; var region = Environment.GetEnvironmentVariable("LAMBDA_TEST_TOOL_TEST_REGION"); return RegionEndpoint.GetBySystemName(region); } } public static AWSCredentials GetAWSCredentials() { var chain = new CredentialProfileStoreChain(); if (!chain.TryGetAWSCredentials(TestProfile, out var awsCredentials)) { throw new Exception("These tests assume a profile with the name \"default\" is registered"); } return awsCredentials; } public static async Task WaitTillQueueIsCreatedAsync(IAmazonSQS sqsClient, string queueUrl) { while (true) { var response = await sqsClient.ListQueuesAsync(new ListQueuesRequest()); if(response.QueueUrls.Contains(queueUrl)) break; else Thread.Sleep(100); } } public static bool ProfileTestsEnabled { get { var profiles = new CredentialProfileStoreChain().ListProfiles(); return profiles.Count > 0; } } public static string GetLambdaFunctionSourceFile(string projectName, string fileName) { #if NETCORE_2_1 return Path.GetFullPath($"../../../../LambdaFunctions/netcore21/{projectName}/{fileName}"); #elif NETCORE_3_1 return Path.GetFullPath($"../../../../LambdaFunctions/netcore31/{projectName}/{fileName}"); #endif } public static string GetLambdaFunctionBuildPath(string projectName) { #if NETCORE_2_1 return Path.GetFullPath($"../../../../LambdaFunctions/netcore21/{projectName}/bin/debug/netcoreapp2.1"); #elif NETCORE_3_1 return Path.GetFullPath($"../../../../LambdaFunctions/netcore31/{projectName}/bin/debug/netcoreapp3.1"); #endif } } }
89
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.Serialization.SystemTextJson; using System.Text.Json.Serialization; [assembly: LambdaSerializer(typeof(SourceGeneratorLambdaJsonSerializer<SourceGeneratorExample.CustomTypesSerializerContext>))] namespace SourceGeneratorExample; [JsonSerializable(typeof(Input))] [JsonSerializable(typeof(Output))] public partial class CustomTypesSerializerContext : JsonSerializerContext { } public class Input { public string Name { get; set; } } public class Output { public string Response { get; set;} } public class Function { public Output FunctionHandler(Input request, ILambdaContext context) { return new Output { Response = "Response = " + request.Name}; } public Task VoidReturnFunctionHandler(Input request, ILambdaContext context) { context.Logger.LogInformation("Calling function with: " + request.Name); return Task.CompletedTask; } }
40
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AspNetCoreAPIExample { public interface IFakeDependency { } public class FakeDependency : IFakeDependency { } }
17
aws-lambda-dotnet
aws
C#
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace AspNetCoreAPIExample { /// <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 /// /// AspNetCoreAPIExample::AspNetCoreAPIExample.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 AspNetCoreAPIExample { /// <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 AspNetCoreAPIExample { 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.AddScoped<IFakeDependency, FakeDependency>(); 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"); }); }); } } }
58
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace AspNetCoreAPIExample.Controllers { [Route("api/[controller]")] public class ValuesController : ControllerBase { IFakeDependency _fakeDependency; public ValuesController(IFakeDependency fakeDependency) { _fakeDependency = fakeDependency; } // 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) { } } }
52
aws-lambda-dotnet
aws
C#
using System; using System.Threading; using System.Threading.Tasks; using Amazon.Lambda.Core; namespace FunctionSignatureExamples { public class AsyncMethods { public Task TaskWithNoResult(string input, ILambdaContext context) { context.Logger.LogLine("Calling TaskWithNoResult"); return Task.Delay(100); } public async Task<string> TaskWithResult(string input, ILambdaContext context) { context.Logger.LogLine("Calling TaskWithResult"); await Task.Delay(100); return "TaskWithResult-" + input; } } }
26
aws-lambda-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; namespace FunctionSignatureExamples { public class ErrorFunctions { public void SyncThrowException() { throw new ApplicationException("Test Exception"); } public Task AsyncNoResultThrowException() { return Task.Run(() => throw new ApplicationException("Test Exception")); } public Task<string> AsyncWithResultThrowException() { return Task<string>.Run((Func<string>)(() => throw new ApplicationException("Test Exception"))); } } }
28
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; // 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 FunctionSignatureExamples { public class InstanceMethods { public string StringToStringWithContext(string input, ILambdaContext context) { context.Logger.LogLine("Calling StringToStringWithContext"); return "StringToStringWithContext-" + input; } public string NoParameters(ILambdaContext context) { context.Logger.LogLine("Calling NoParameters"); return "NoParameters"; } public void VoidReturn(ILambdaContext context) { context.Logger.LogLine("Calling VoidReturn"); } public string NoContextWithParameter(string input) { return "NoContextWithParameter-" + input; } public string WithGenericParameter(List<string> values, ILambdaContext context) { context.Logger.LogLine("Calling WithGenericParameter"); return string.Join(',', values.ToArray()); } public string WithEventParameter(S3Event evnt, ILambdaContext context) { context.Logger.LogLine("Calling WithEventParameter"); return "WithEventParameter-" + ((evnt != null) ? "event-not-null" : "event-null"); } } }
56
aws-lambda-dotnet
aws
C#
using Amazon.Lambda.Core; namespace FunctionSignatureExamples { public static class StaticMethods { public static string TheStaticMethod(string input, ILambdaContext context) { context.Logger.LogLine("Calling TheStaticMethodß"); return "TheStaticMethod-" + input; } } }
15
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 S3EventFunction { 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 void FunctionHandler(S3Event evnt, ILambdaContext context) { foreach (var record in evnt.Records) { context.Logger.LogLine($"Processing {record.S3.Object.Key}"); if (string.Equals("error.txt", record.S3.Object.Key)) { throw new Exception("Simulated Failure"); } } } } }
60
aws-lambda-dotnet
aws
C#
namespace DotNetServerless.Lambda { public class Program { public static void Main(string[] args) { } } }
10
aws-lambda-dotnet
aws
C#
using System.IO; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace DotNetServerless.Lambda { public class Startup { public static IServiceCollection BuildContainer() { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(); return ConfigureServices(configuration); } private static IServiceCollection ConfigureServices(IConfigurationRoot configurationRoot) { var services = new ServiceCollection(); return services; } } }
28
aws-lambda-dotnet
aws
C#
using System; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Microsoft.Extensions.DependencyInjection; namespace DotNetServerless.Lambda.Functions { public class CreateItemFunction { private readonly IServiceProvider _serviceProvider; public CreateItemFunction() : this(Startup .BuildContainer() .BuildServiceProvider()) { } public CreateItemFunction(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public Task<APIGatewayProxyResponse> Run(APIGatewayProxyRequest request) { return Task.FromResult(new APIGatewayProxyResponse()); } } }
31
aws-lambda-dotnet
aws
C#
using System; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Microsoft.Extensions.DependencyInjection; namespace DotNetServerless.Lambda.Functions { public class GetItemFunction { private readonly IServiceProvider _serviceProvider; public GetItemFunction() : this(Startup .BuildContainer() .BuildServiceProvider()) { } public GetItemFunction(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public Task<APIGatewayProxyResponse> Run(APIGatewayProxyRequest request) { return Task.FromResult(new APIGatewayProxyResponse()); } } }
32
aws-lambda-dotnet
aws
C#
using System; using System.Threading.Tasks; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using Microsoft.Extensions.DependencyInjection; namespace DotNetServerless.Lambda.Functions { public class UpdateItemFunction { private readonly IServiceProvider _serviceProvider; public UpdateItemFunction() : this(Startup .BuildContainer() .BuildServiceProvider()) { } public UpdateItemFunction(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public Task<APIGatewayProxyResponse> Run(APIGatewayProxyRequest request) { return Task.FromResult(new APIGatewayProxyResponse()); } } }
32
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 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 ServerlessTemplateExample { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } public void HelloWorld(ILambdaContext context) { context.Logger.LogLine("Hello World Test"); } public string ToUpper(string input, ILambdaContext context) { context.Logger.LogLine("Hello World Test"); return input?.ToUpper(); } } }
41
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 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 ServerlessTemplateYamlExample { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } public void HelloWorld(ILambdaContext context) { context.Logger.LogLine("Hello World Test"); } public string ToUpper(string input, ILambdaContext context) { context.Logger.LogLine("Hello World Test"); return input?.ToUpper(); } } }
41
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; namespace ToUpperFunc { 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> [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public static string FunctionHandler(string input, ILambdaContext context) { context.Logger.LogLine($"Executing function with input: {input}"); Console.WriteLine("Testing Console Logging"); if(string.Equals("error", input)) throw new Exception("Forced Error"); return input?.ToUpper(); } [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public static string ToLower(string input, ILambdaContext context) { return input?.ToLower(); } public static void StreamExample(Stream stream, ILambdaContext context) { var content = new StreamReader(stream).ReadToEnd(); context.Logger.LogLine(content); } } }
46
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace ConsoleSample { public class Program { public static void Main(string[] args) { var config = new AWS.Logger.AWSLoggerConfig("AspNetCore.ConsoleSample"); config.Region = "us-east-1"; LoggerFactory logFactory = new LoggerFactory(); logFactory.AddAWSProvider(config); var logger = logFactory.CreateLogger<Program>(); logger.LogInformation("Check the AWS Console CloudWatch Logs console in us-east-1"); logger.LogInformation("to see messages in the log streams for the"); logger.LogInformation("log group AspNetCore.ConsoleSample"); } } }
28
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleSample")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("49860ddf-0a02-4d51-bf75-15b336455661")]
20
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebSample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.AddAWSProvider(); // When you need logging below set the minimum level. Otherwise the logging framework will default to Informational for external providers. logging.SetMinimumLevel(LogLevel.Debug); }) .UseStartup<Startup>(); } }
32
aws-logging-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.Logging; namespace WebSample { public class Startup { public Startup(IConfiguration configuration, ILogger<Startup> logger) { Configuration = configuration; this._logger = logger; } public IConfiguration Configuration { get; } private ILogger<Startup> _logger; // 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, IHostingEnvironment env) { // Example Logging _logger.LogInformation("Check the AWS Console CloudWatch Logs console in us-east-1"); _logger.LogInformation("to see messages in the log streams for the"); _logger.LogInformation("log group AspNetCore.WebSample"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
67
aws-logging-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; using Microsoft.Extensions.Logging; namespace WebSample.Pages { public class IndexModel : PageModel { ILogger<IndexModel> Logger { get; set; } public IndexModel(ILogger<IndexModel> logger) { Logger = logger; } public void OnGet() { Logger.LogInformation("Welcome to the AWS Logger. You are viewing the home page"); } } }
26
aws-logging-dotnet
aws
C#
using Amazon.Runtime; using AWS.Logger.Log4net; using log4net; using log4net.Layout; using log4net.Repository.Hierarchy; using System; using System.Linq; namespace BasicAWSCredentialsConfigurationExample { public class Program { private static readonly ILog log = LogManager.GetLogger(nameof(Program)); private const string logLayoutPattern = "%utcdate{yyyy-MM-ddTHH:mm:ss.fffZ} [%-5level] %logger - %message%newline"; private const string logGroup = "Log4net.BasicAWSCredentialsConfigurationExample"; private const string awsRegion = "ap-southeast-1"; public static void Main(string[] args) { var credentials = CreateCredentials(args); var appender = CreateAppender(credentials); //Get a reference to an existing logger name "Program" in log4net.config var hierarchy = (Hierarchy)log.Logger.Repository; var logger = hierarchy.GetLogger(nameof(Program)) as Logger; //Attach the CloudWatch Logs appender logger.AddAppender(appender); //Start writing log to CloudWatch Logs log.Info($"Check the AWS Console CloudWatch Logs console in {awsRegion} region"); log.Info("to see messages in the log streams for the"); log.Info($"log group {logGroup}"); } private static BasicAWSCredentials CreateCredentials(string[] args) { if (args == null || !args.Any()) { throw new ArgumentNullException( "args", "Please pass AWS API key and secret key as command line arguments" ); } //Warning!!! This is only a simple example, not for a production code. var awsApiKey = args[0]; var awsSecretKey = args[1]; //Output values to verify that we have pass a values from command line arguments Console.WriteLine( $"{nameof(awsApiKey)}: {awsApiKey.Substring(0, 8)}, " + $"{nameof(awsSecretKey)}: {awsSecretKey.Substring(0, 8)}" ); return new BasicAWSCredentials(awsApiKey, awsSecretKey); } private static AWSAppender CreateAppender(AWSCredentials credentials) { var patternLayout = new PatternLayout { ConversionPattern = logLayoutPattern }; patternLayout.ActivateOptions(); var appender = new AWSAppender { Layout = patternLayout, Credentials =credentials, LogGroup = logGroup, Region = awsRegion }; appender.ActivateOptions(); return appender; } } }
80
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BasicAWSCredentialsConfigurationExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BasicAWSCredentialsConfigurationExample")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7249c7f3-a0ef-4940-9931-3096c87e009e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
36
aws-logging-dotnet
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Config; namespace ConfigExample { class Program { static void Main(string[] args) { // Log4net is configured in the log4net.config which adds the AWS appender. XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config")); ILog log = LogManager.GetLogger(typeof(Program)); log.Info("Check the AWS Console CloudWatch Logs console in us-east-1"); log.Info("to see messages in the log streams for the"); log.Info("log group Log4net.ConfigExample"); } } }
26
aws-logging-dotnet
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Log4netConfigExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Log4netConfigExample")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34419d16-c17e-48fc-aefb-d56a77c6419b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37