public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse Subtract(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
        {
            // Create a scope for every request,
            // this allows creating scoped dependencies without creating a scope manually.
            using var scope = serviceProvider.CreateScope();
            var simpleCalculator = scope.ServiceProvider.GetRequiredService <SimpleCalculator>();

            var validationErrors = new List <string>();

            var x = default(int);

            if (__request__.Headers?.ContainsKey("x") == true)
            {
                try
                {
                    x = (int)Convert.ChangeType(__request__.Headers["x"], typeof(int));
                }
                catch (Exception e) when(e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
                {
                    validationErrors.Add($"Value {__request__.Headers["x"]} at 'x' failed to satisfy constraint: {e.Message}");
                }
            }

            var y = default(int);

            if (__request__.Headers?.ContainsKey("y") == true)
            {
                try
                {
                    y = (int)Convert.ChangeType(__request__.Headers["y"], typeof(int));
                }
                catch (Exception e) when(e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
                {
                    validationErrors.Add($"Value {__request__.Headers["y"]} at 'y' failed to satisfy constraint: {e.Message}");
                }
            }

            var simpleCalculatorService = scope.ServiceProvider.GetRequiredService <TestServerlessApp.Services.ISimpleCalculatorService>();

            // return 400 Bad Request if there exists a validation error
            if (validationErrors.Any())
            {
                return(new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
                {
                    Body = @$ "{{" "message" ": " "{validationErrors.Count} validation error(s) detected: {string.Join(", ", validationErrors)}" "}}",
                    Headers = new Dictionary <string, string>
                    {
                        { "Content-Type", "application/json" },
                        { "x-amzn-ErrorType", "ValidationException" }
                    },
                    StatusCode = 400
                });
Esempio n. 2
0
        public void Test_GetHandler()
        {
            // Invoke the lambda function and confirm the string was upper cased.
            var function = new GetHandler();
            var context  = new TestLambdaContext();
            var request  = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest {
                RequestContext = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest.ProxyRequestContext {
                    RequestId = Guid.NewGuid().ToString()
                }
            };

            request.QueryStringParameters = new Dictionary <string, string>();
            request.Body    = "Test";
            request.Headers = new Dictionary <string, string>();
            var result = function.Handler(request);

            Assert.True(true);
        }
Esempio n. 3
0
        public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse SayHello(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
        {
            var validationErrors = new List <string>();

            var firstNames = default(System.Collections.Generic.IEnumerable <string>);

            if (__request__.MultiValueQueryStringParameters?.ContainsKey("names") == true)
            {
                firstNames = __request__.MultiValueQueryStringParameters["names"]
                             .Select(q =>
                {
                    try
                    {
                        return((string)Convert.ChangeType(q, typeof(string)));
                    }
                    catch (Exception e) when(e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
                    {
                        validationErrors.Add($"Value {q} at 'names' failed to satisfy constraint: {e.Message}");
                        return(default);
Esempio n. 4
0
        //Key thing, you get in an APIGatewayProxyRequest object since you are using API Gateway to fire the request and it expects
        //an APIGatewayProxyResponse object back
        //This code mimics the original node.js code, just ported to be in .NET for an example
        public Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse FunctionHandler(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest input, ILambdaContext context)
        {
            //Load the static list of unicorns
            LoadUnicorns();
            //pre-build the response
            Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse response = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse();
            //The node.js code has this set for CORS so we add it to the response
            response.Headers = new Dictionary <string, string>();
            response.Headers["Access-Control-Allow-Origin"] = "*";

            //if the user does not have an authorization, throw a 500 error, just like the original code
            if (input?.RequestContext?.Authorizer == null)
            {
                response.StatusCode = 500;
                var em = new ErrorReturn();
                em.Reference  = context?.AwsRequestId;
                em.Error      = "Authorization not configured";
                response.Body = Newtonsoft.Json.JsonConvert.SerializeObject(em);

                return(response);
            }
            //Make a random long key for lookups
            string rideId = Guid.NewGuid().ToString().Replace("-", "");

            //When you write to the console in Lambda the information will show up in CloudWatch Logs
            Console.WriteLine($"Received request for ride {rideId}");

            // Because we're using a Cognito User Pools authorizer, all of the claims
            // included in the authentication token are provided in the request context.
            // This includes the username as well as other attributes.
            string username = input?.RequestContext?.Authorizer?.Claims ["cognito:username"];

            // The body field of the event in a proxy integration is a raw string.
            // In order to extract meaningful values, we need to first parse this string
            // into an object. A more robust implementation might inspect the Content-Type
            // header first and use a different parsing strategy based on that value.


            try
            {
                //Use Newtonsoft to take the body of the input and make it a location object
                var requestedLocation = Newtonsoft.Json.JsonConvert.DeserializeObject <PickupLocationBody>(input.Body);

                //send in the pickuplocation attribute to the findUnicorn method to get back your unicorn
                var unicorn = findUnicorn(requestedLocation?.PickupLocation);
                //now record the ride in DynamoDB
                var ride = recordRide(rideId, username, unicorn);
                //set the status code
                response.StatusCode = 201;
                //serialize the response (ride) as the body
                response.Body = Newtonsoft.Json.JsonConvert.SerializeObject(ride);
            }
            catch (Exception ex)
            {
                //if you get an exception, just write it to console and cloudwatch logs will show it in the log
                Console.WriteLine(ex.Message);
                response.StatusCode = 500;
                var em = new ErrorReturn();
                em.Reference  = context?.AwsRequestId;
                em.Error      = ex.Message;
                response.Body = Newtonsoft.Json.JsonConvert.SerializeObject(em);
            }

            return(response);
        }