public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response)
        {
            var          items         = new List <ArtistModel>();
            var          client        = new AmazonDynamoDBClient();
            var          scanRequest   = new ScanRequest(new ArtistModel().GetTable());
            ScanResponse queryResponse = null;

            do
            {
                if (queryResponse != null)
                {
                    scanRequest.ExclusiveStartKey = queryResponse.LastEvaluatedKey;
                }
                queryResponse = client.ScanAsync(scanRequest).Result;
                foreach (var item in queryResponse.Items)
                {
                    var model = JsonConvert.DeserializeObject <ArtistModel>(Document.FromAttributeMap(item).ToJson());
                    items.Add(model);
                }
            } while (queryResponse.LastEvaluatedKey.Any());
            items         = items.OrderBy(x => x.Artist).ToList();
            response.Body = JsonConvert.SerializeObject(items);
        }
예제 #2
0
        /// <summary>
        /// A Lambda function that returns back a page worth of products.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The list of products</returns>
        public async Task <APIGatewayProxyResponse> GetProductsAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Getting Products");
            var search = this.DDBContext.ScanAsync <AMProducts>(null);
            var page   = await search.GetNextSetAsync();

            context.Logger.LogLine($"Found {page.Count} products");

            var myheaders = new Dictionary <string, string> {
                { "Content-Type", "application/json" }
            };

            myheaders.Add("Access-Control-Allow-Origin", "*");

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(page),
                Headers    = myheaders
            };

            return(response);
        }
예제 #3
0
        /// <summary>
        /// A Lambda function that returns the film identified by filmId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override async Task <APIGatewayProxyResponse> PerformAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string filmId = GetFilmIdFromRequest(request);

            if (string.IsNullOrEmpty(filmId))
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = $"Missing required parameter {ID_QUERY_STRING_NAME}",
                    Headers = this.GetResponseHeaders("test/plain")
                });
            }

            context.Logger.LogLine($"Getting film {filmId}");
            var film = await this.Repository.GetByIdAsync(filmId);

            context.Logger.LogLine($"Found film: {film != null}");

            if (film == null)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound,
                    Headers = this.GetResponseHeaders()
                });
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(film),
                Headers    = this.GetResponseHeaders("application/json")
            };

            return(response);
        }
        /// <summary>
        /// A Lambda function that returns the task identified by taskId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> GetTaskAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string taskId = GetTaskIdParam(request);

            if (string.IsNullOrEmpty(taskId))
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = $"Missing required parameter {ID_QUERY_STRING_NAME}"
                });
            }

            context.Logger.LogLine($"Getting task {taskId}");
            var task = await TaskService.GetTransTaskById(taskId);

            context.Logger.LogLine($"Found task: {task != null}");

            if (task == null)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound
                });
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(task),
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

            return(response);
        }
        public async Task <APIGatewayProxyResponse> Post(APIGatewayProxyRequest proxyRequest)
        {
            var statusCode = (proxyRequest != null)
                ? HttpStatusCode.OK
                : HttpStatusCode.BadRequest;

            var(request, requestError) = proxyRequest.Body.Deserialize <CreatePostRequest>();
            if (requestError != null)
            {
                statusCode = HttpStatusCode.BadRequest;
            }

            var(post, postError) = BlogPost.Create(new PostId(Guid.NewGuid()),
                                                   request.Category,
                                                   request.Title,
                                                   request.Content);
            if (postError != null)
            {
                statusCode = HttpStatusCode.BadRequest;
            }

            var(result, message) = await _postRepository.Save(post);

            var response = new APIGatewayProxyResponse()
            {
                StatusCode = (int)result,
                Headers    = new Dictionary <string, string>
                {
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accepted" },
                    { "Content-Type", "application/json" }
                },
                Body = message.ToJson()
            };

            return(response);
        }
예제 #6
0
        /// <summary>
        /// A Lambda function to respond to HTTP Get methods from API Gateway
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The list of blogs</returns>
        public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var    key   = request.QueryStringParameters["Key"];
            var    token = request.QueryStringParameters["Token"];
            string mode  = request.QueryStringParameters["mode"];

            if (mode == null)
            {
                mode = "encrypt";
            }
            ;            var generator = new ecencryptstdlib.ECTokenGenerator();
            string           result    = string.Empty;

            if (mode == "encrypt")
            {
                result = generator.EncryptV3(key, token, false);
            }
            else
            {
                result = generator.DecryptV3(key, token, false);
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = result,
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" },
                    { "Access-Control-Allow-Headers", "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with" },
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Credentials", "true" },
                    { "Access-Control-Allow-Methods", "GET" }
                }
            };

            return(response);
        }
예제 #7
0
        /// <summary>
        /// A Lambda function to respond to HTTP Get methods from API Gateway
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The list of blogs</returns>
        public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request at " + DateTime.UtcNow.ToString() + "\n");
            int statusCode = (int)HttpStatusCode.OK;

            try
            {
                AWSDynamoDBConnector.DynamoConnection dynamoConnection = new AWSDynamoDBConnector.DynamoConnection(
                    accessKey: ConfigurationManager.AppSettings.DynamoDBConnector.accessKey.Value,
                    secretKey: ConfigurationManager.AppSettings.DynamoDBConnector.secretKey.Value,
                    tableName: ConfigurationManager.AppSettings.DynamoDBConnector.tableName.Value);

                SoupCrawler crawler = new SoupCrawler();
                var         soups   = crawler.GetTodaysSoups();

                dynamoConnection.AddSoups(soups);

                context.Logger.LogLine("Successfully received " + soups.Count + " soups \n");
            }
            catch (Exception e)
            {
                context.Logger.LogLine("Failted to parse/update data with Exception: " + e + "\n");

                statusCode = (int)HttpStatusCode.InternalServerError;
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = statusCode,
                Body       = "",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                }
            };

            return(response);
        }
예제 #8
0
        /// <summary>
        /// Get question from API Gateway
        /// </summary>
        /// <param name="request">with question Id</param>
        /// <returns>Question</returns>
        public APIGatewayProxyResponse GetQuestion(APIGatewayProxyRequest request, ILambdaContext context)
        {
            Log(context, "Get question request\n");

            request.QueryStringParameters.TryGetValue("Id", out string questionId);

            if (string.IsNullOrEmpty(questionId))
            {
                var badQuestionIdResponse = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body       = "Unknown question Id.",
                    Headers    = new Dictionary <string, string> {
                        {
                            "Content-Type", "application/json"
                        }
                    }
                };

                return(badQuestionIdResponse);
            }

            var questionIdValue = int.Parse(questionId);

            var question = QuestionsDb.GetQuestions().OfType <Question>().SingleOrDefault(q => q.Id == questionIdValue);

            if (question == null)
            {
                const string questionNotFoundText = "Question not found.";

                return(CreateAPIGatewayProxyResponse(ToJson(questionNotFoundText), HttpStatusCode.NotFound));
            }

            var body = ToJson(question);

            return(CreateAPIGatewayProxyResponse(body));
        }
        public APIGatewayProxyResponse FunctionHandler(JObject input, ILambdaContext context)
        {
            Console.WriteLine("Function started");

            try
            {
                TelegramSenderManager sender = new TelegramSenderManager();
                sender.Init();

                try
                {
                    Update webhookData = JsonConvert.DeserializeObject <Update>(input["body"].ToString());

                    sender.HandleWebhookUpdate(webhookData);
                }
                catch (Exception ex)
                {
                    sender.SendMessageToDebug(ex.ToString());
                    sender.SendMessageToDebug(input["body"].ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(new { msg = "Welcome to Belarus! :)" }),
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

            return(response);
        }
예제 #10
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            var validation = new List <string>();
            var rentalDate = request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("rentalDate")
                ? request.QueryStringParameters["rentalDate"]
                : string.Empty;
            var databaseClient = new DatabaseClient <SpotReservation>(new AmazonDynamoDBClient(), new ConsoleLogger());
            var service        = new SpotReservationService(databaseClient);

            List <SpotReservation> spotReservations;

            if (!string.IsNullOrWhiteSpace(rentalDate))
            {
                validation.AddRange(ReceiptValidation.GetRentalDateValidation(rentalDate));
                if (validation.Any())
                {
                    response.StatusCode = 400;
                    response.Body       = new JObject {
                        { "error", JArray.FromObject(validation) }
                    }.ToString();
                    return;
                }

                spotReservations = service.GetSpotReservations(rentalDate);
            }
            else
            {
                var vendorId = request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("vendorId")
                    ? request.QueryStringParameters["vendorId"]
                    : string.Empty;
                spotReservations = service.GetSpotReservationsByVendor(vendorId)
                                   .OrderBy(x => x.RentalDate)
                                   .ToList();
            }

            response.Body = JsonConvert.SerializeObject(spotReservations);
        }
예제 #11
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.Log("Starting User Get call");

            using (AwsFactory factory = new AwsFactory(context.Logger))
            {
                string userId = request.PathParameters["userId"];
                context.Logger.LogLine($"userId=\"{userId}\"");

                string firstName;

                if (request.PathParameters.ContainsKey("firstName"))
                {
                    firstName = request.PathParameters["firstName"];
                }
                else
                {
                    firstName = null;
                }

                context.Logger.LogLine($"firstName=\"{firstName}\"");

                using (GetUser getUser = new GetUser(factory))
                {
                    string jsonResponse = getUser.Retrieve(userId, firstName);

                    context.Logger.LogLine($"Response: {jsonResponse}");
                    APIGatewayProxyResponse response = new APIGatewayProxyResponse()
                    {
                        Body       = jsonResponse,
                        StatusCode = 200
                    };

                    return(response);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// A Lambda function to respond to HTTP Get methods from API Gateway
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The list of blogs</returns>
        public async Task <APIGatewayProxyResponse> Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request\n");

            var   sw        = Stopwatch.StartNew();
            Image testImage = await LoadImage(context);

            sw.Stop(); Logging("Load image time: " + sw.Elapsed.ToString(), context);

            sw.Restart();
            var resizedImage = testImage.Resize(256, 256);

            sw.Stop(); Logging("Resize image time: " + sw.Elapsed.ToString(), context);

            resizedImage.SaveAsJpeg(new FileStream("/tmp/lena_resized.jpg", FileMode.Create));

            var putReq = new PutObjectRequest
            {
                BucketName = "lambda-image-converter",
                Key        = "lena_resized.jpg",
                FilePath   = "/tmp/lena_resized.jpg"
            };

            await s3Client.PutObjectAsync(putReq);

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = "Hello AWS Serverless",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                }
            };

            globalSw.Stop(); Logging("Total time: " + globalSw.Elapsed.ToString(), context);
            return(response);
        }
예제 #13
0
        public async Task <APIGatewayProxyResponse> InvokeAPIGatewayProxyAsync(
            Func <APIGatewayProxyRequest, ILambdaContext, Task <APIGatewayProxyResponse> > asyncHandler,
            APIGatewayProxyRequest request,
            ILambdaContext context,
            string operationName = null,
            IEnumerable <KeyValuePair <string, string> > tags = null)
        {
            IHeadersCollection headersCollection = null;

            if (TelemetryConfiguration.ContextPropagationEnabled)
            {
                headersCollection = new DictionaryHeadersCollection(request.MultiValueHeaders);
            }

            using (var tracker = new TelemetryTracker(context, operationName, tags, headersCollection))
            {
                try
                {
                    APIGatewayProxyResponse apiGatewayProxyResponse = await asyncHandler(request, context);

                    if (!apiGatewayProxyResponse.IsSuccessStatusCode())
                    {
                        tracker.SetErrorCounter();

                        // Preserve the legacy logging.
                        LambdaLogger.Log($"[ERR] Invoking lambda function. Http status code: {apiGatewayProxyResponse.StatusCode}. Response body: {apiGatewayProxyResponse.Body}{Environment.NewLine}");
                    }

                    return(apiGatewayProxyResponse);
                }
                catch (Exception e)
                {
                    tracker.SetException(e);
                    throw;
                }
            }
        }
예제 #14
0
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            JObject bdy = JObject.Parse(request.Body);
            string  req = bdy["data"].ToString();
            string  res = "";

            switch (bdy["event"].ToString())
            {
            case "tolower":
                res = tolower(req);
                break;

            case "toupper":
                res = toupper(req);
                break;

            default:
                res = "what";
                break;
            }



            var data = new APIGatewayProxyResponse
            {
                StatusCode = 200,
                Headers    =
                    new Dictionary <string, string>
                {
                    { "Content-Type", "application/json" },
                    { "Access-Control-Allow-Origin", "*" }
                },
                Body = res
            };

            return(data);
        }
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            string idToken      = CookieReader.GetCookie(request, "idToken");
            string refreshToken = CookieReader.GetCookie(request, "refreshToken");

            if (string.IsNullOrWhiteSpace(idToken) || string.IsNullOrWhiteSpace(refreshToken))
            {
                response.StatusCode = 400;
                response.Body       = new JObject {
                    { "error", "idToken and refreshToken cookies are required" }
                }.ToString();
                return;
            }
            var payload     = Function.Base64Decode(idToken.Split('.')[1]);
            var email       = JObject.Parse(payload)["email"].Value <string>();
            var provider    = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            var userPool    = new CognitoUserPool(Configuration.FINANCE_API_COGNITO_USER_POOL_ID, Configuration.FINANCE_API_COGNITO_CLIENT_ID, provider);
            var cognitoUser = new CognitoUser(email, Configuration.FINANCE_API_COGNITO_CLIENT_ID, userPool, provider)
            {
                SessionTokens = new CognitoUserSession(null, null, refreshToken, DateTime.UtcNow, DateTime.UtcNow.AddHours(1))
            };
            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };
            var refreshResponse = cognitoUser.StartWithRefreshTokenAuthAsync(refreshRequest).Result;
            var expirationDate  = DateTime.UtcNow.AddDays(30).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");

            response.MultiValueHeaders = new Dictionary <string, IList <string> >
            {
                { "Set-Cookie", new List <string> {
                      $"idToken={refreshResponse.AuthenticationResult.IdToken};Path=/;Secure;HttpOnly;Expires={expirationDate}"
                  } }
            };

            response.Body = new JObject().ToString();
        }
예제 #16
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest req, ILambdaContext context)
        {
            context.Logger.LogLine(JsonConvert.SerializeObject(req));
            var baseUrl                = req.Headers["Host"];
            var stage                  = req.RequestContext.Stage;
            var soarS3Base             = req.StageVariables["soar_s3_base"];
            var soarPreviewsBucketName = req.StageVariables["soar_previews_bucket_name"];

            var    reqDetails = JsonConvert.DeserializeObject <UploadDetailsReq>(req.Body);
            string extension  = GetExtensionForContentType(reqDetails.contentType);

            using (var storageService = _storageService == null ? new DynamoDbStorageService() : _storageService)
            {
                var fileName = $"{reqDetails.fileHash}.{extension}";
                var details  = new UploadDetailsRes()
                {
                    challenge   = Guid.NewGuid().To32CharactesString(),
                    secret      = Guid.NewGuid().To32CharactesString(),
                    uploadUrl   = $"https://{baseUrl}/{stage}/upload/{fileName}",
                    previewUrl  = $"{soarS3Base}/{soarPreviewsBucketName}/{fileName}",
                    downloadUrl = $"https://{baseUrl}/{stage}/download/{fileName}"
                };
                var success = await storageService.PutSecret(details.secret, details.challenge, reqDetails.address, reqDetails.fileHash);

                if (!success)
                {
                    throw new SoarException("Error during storing verification secret in db");
                }
                var res = new APIGatewayProxyResponse()
                {
                    Headers    = APIGatewayHelpers.GetResponseHeaders(),
                    Body       = JsonConvert.SerializeObject(details),
                    StatusCode = 200
                };
                return(res);
            }
        }
예제 #17
0
    public async Task Can_Solve_Puzzle_With_Input_File(int year, int day, int[] expected)
    {
        // Arrange
        var(body, contentType) = await GetFormContentAsync(
            (content) => content.Add(new StringContent(GetPuzzleInput(year, day)), "resource", "input.txt"));

        var request = new APIGatewayProxyRequest()
        {
            Body            = body,
            IsBase64Encoded = true,
            Headers         = new Dictionary <string, string>()
            {
                ["content-type"] = contentType,
            },
            HttpMethod = HttpMethods.Post,
            Path       = $"/api/puzzles/{year}/{day}/solve",
        };

        // Act
        APIGatewayProxyResponse actual = await AssertApiGatewayRequestIsHandledAsync(request);

        actual.ShouldNotBeNull();
        actual.StatusCode.ShouldBe(StatusCodes.Status200OK);
        actual.MultiValueHeaders.ShouldContainKey("Content-Type");
        actual.MultiValueHeaders["Content-Type"].ShouldBe(new[] { "application/json; charset=utf-8" });

        using var solution = JsonDocument.Parse(actual.Body);

        solution.RootElement.GetProperty("year").GetInt32().ShouldBe(year);
        solution.RootElement.GetProperty("day").GetInt32().ShouldBe(day);
        solution.RootElement.GetProperty("timeToSolve").GetDouble().ShouldBeGreaterThan(0);
        solution.RootElement.GetProperty("visualizations").GetArrayLength().ShouldBe(0);

        solution.RootElement.TryGetProperty("solutions", out var solutions).ShouldBeTrue();
        solutions.GetArrayLength().ShouldBe(expected.Length);
        solutions.EnumerateArray().ToArray().Select((p) => p.GetInt32()).ToArray().ShouldBe(expected);
    }
예제 #18
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            context.Logger.Log("MYSTART\n");
            context.Logger.Log(input.Body);
            context.Logger.Log("MYEND\n");

            if (input.HttpMethod == "POST")
            {
                var shitstick = JsonConvert.DeserializeObject <Contract1>(input.Body);
                APIGatewayProxyResponse response = new APIGatewayProxyResponse()
                {
                    Body = shitstick.First
                };

                return(response);
            }
            else
            {
                return(new APIGatewayProxyResponse()
                {
                    Body = input.HttpMethod
                });
            }
        }
예제 #19
0
        /// <summary>
        /// API Gateway Proxy Response
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            APIGatewayProxyResponse response;

            try
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = JsonConvert.SerializeObject(
                        new ServerSuccess
                    {
                        ResponseMessage = $"Bjj Buddy Response - {DateTime.Now.ToString("hh:mm:ss")}",
                        Data            = string.Empty
                    }),
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                };
            }
            catch (Exception exception)
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body       = JsonConvert.SerializeObject(
                        new ServerError
                    {
                        ExceptionMessage = $"Bjj Buddy Error - {exception.Message}"
                    })
                };
            }

            AmazonDynamoDbQuery("tablename", "context");
            return(response);
        }
예제 #20
0
        /// <summary>
        /// A Lambda function that returns back a page worth of SesEvent posts.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The list of SesEvents</returns>
        public async Task <APIGatewayProxyResponse> GetSesEventsAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Getting SesEvents");
            var allowedCorsOrigin = Environment.GetEnvironmentVariable("AllowedCorsOrigin");

            var events = await _dbContext.GetAsync <SesEvent>();

            // var search = this.DDBContext.ScanAsync<SesEvent>(null);
            // var page = await search.GetNextSetAsync();
            context.Logger.LogLine($"Found {events.Count()} SesEvents");

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(events),
                Headers    = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json" },
                    { "Access-Control-Allow-Origin", allowedCorsOrigin }
                }
            };

            return(response);
        }
        public void TestHelloWorldFunctionHandler()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            request = new APIGatewayProxyRequest();
            context = new TestLambdaContext();
            string location = GetCallingIP().Result;
            Dictionary <string, string> body = new Dictionary <string, string>
            {
                { "message", "Hello .Net lambda world" },
                { "location", location },
            };

            var ExpectedResponse = new APIGatewayProxyResponse
            {
                Body       = JsonConvert.SerializeObject(body),
                StatusCode = 200,
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" },
                    { "Access-Control-Allow-Origin", "*" }
                }
            };

            var function = new Function();

            response = function.FunctionHandler(request, context);

            Console.WriteLine("Lambda Response: \n" + response.Body);
            Console.WriteLine("Expected Response: \n" + ExpectedResponse.Body);

            Assert.Equal(ExpectedResponse.Body, response.Body);
            Assert.Equal(ExpectedResponse.Headers, response.Headers);
            Assert.Equal(ExpectedResponse.StatusCode, response.StatusCode);
        }
예제 #22
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.Log("Starting User Post call");

            using (AwsFactory factory = new AwsFactory(context.Logger))
            {
                using (PostUser postUser = new PostUser(factory))
                {
                    context.Logger.Log($"Request body: {request.Body}");

                    string jsonResponse = postUser.Save(request.Body);

                    context.Logger.LogLine($"Response: {jsonResponse}");

                    APIGatewayProxyResponse response = new APIGatewayProxyResponse()
                    {
                        Body       = jsonResponse,
                        StatusCode = 200
                    };

                    return(response);
                }
            }
        }
예제 #23
0
        public void Should_return_404_for_not_matching_input()
        {
            var context  = new TestLambdaContext();
            var function = new Function();
            var response = function.FunctionHandler(new APIGatewayProxyRequest {
                Body = "TeaList"
            }, context);

            var expectedResponse = new APIGatewayProxyResponse
            {
                Body       = JsonConvert.SerializeObject("Not found"),
                StatusCode = 404,
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

            _testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
            _testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body);

            Assert.Equal(expectedResponse.Body, response.Body);
            Assert.Equal(expectedResponse.Headers, response.Headers);
            Assert.Equal(expectedResponse.StatusCode, response.StatusCode);
        }
예제 #24
0
        public async Task <APIGatewayProxyResponse> isExisting(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string          name      = JsonConvert.DeserializeObject <string>(request?.Body);
            DynamoDBContext dbContext = new DynamoDBContext(new AmazonDynamoDBClient(RegionEndpoint.APSoutheast2));

            try
            {
                AmazonDynamoDBClient client = new AmazonDynamoDBClient(RegionEndpoint.APSoutheast2);
                var req = new ScanRequest
                {
                    TableName = "identityONE_Card_Layouts",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                        { ":val", new AttributeValue {
                              S = name
                          } }
                    },
                    FilterExpression     = "TemplateName = :val",
                    ProjectionExpression = "ID",
                };
                var resp = await client.ScanAsync(req);

                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = JsonConvert.SerializeObject(resp.Items.Count > 0),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" }
                    }
                };
                return(response);
            }
            catch (Exception ex)
            {
                return(ReturnResponse(ex));
            }
        }
예제 #25
0
        public async Task <APIGatewayProxyResponse> GetItemFromCartWithId(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var requestBody = JsonConvert.DeserializeObject <Basket>(request.PathParameters["itemName"]);
            var results     = await shop.GetItemFromBasketID(requestBody);

            if (results.HttpStatusCode.ToString() != "200")
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)results.HttpStatusCode,
                    Body       = $"Request was not successfull"
                };
                return(response);
            }
            else
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)results.HttpStatusCode,
                    Body       = $"Successfully retyrieved item: {results}"
                };
                return(response);
            }
        }
예제 #26
0
        public async Task <APIGatewayProxyResponse> DeleteItemInCart(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var requestBody = JsonConvert.DeserializeObject <Basket>(request.Body);
            var results     = await shop.RemoveItemFromBasket(requestBody);

            if (results.HttpStatusCode.ToString() != "200")
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)results.HttpStatusCode,
                    Body       = $"Request was not successfull"
                };
                return(response);
            }
            else
            {
                response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)results.HttpStatusCode,
                    Body       = $"Successfully deleted item: {requestBody.itemName}"
                };
                return(response);
            }
        }
예제 #27
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            String     expression             = input.Body;
            List <Row> rows                   = JsonConvert.DeserializeObject <List <Row> >(expression);
            int        changes                = 0;
            MySqlConnectionStringBuilder anta = new MySqlConnectionStringBuilder
            {
                Server   = "rea.cvawub2b2icc.eu-central-1.rds.amazonaws.com",
                Database = "rea",
                UserID   = "root",
                Password = "******"
            };
            String addstring = "INSERT INTO @table VALUES(@datum,@dauer);";

            using (MySqlConnection conn = new MySqlConnection(anta.ConnectionString))
            {
                foreach (Row my in rows)
                {
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = addstring;
                        cmd.Parameters.AddWithValue("@table", my.UID);
                        cmd.Parameters.AddWithValue("@datum", my.Datum);
                        cmd.Parameters.AddWithValue("@dauer", my.Dauer);
                        conn.Open();
                        changes += cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
            }

            APIGatewayProxyResponse result = new APIGatewayProxyResponse();

            result.Body = changes.ToString() + " Rows have been added";
            return(result);
        }
예제 #28
0
        public async Task Live_TestGetDataAsync()
        {
            // ARRANGE
            Entrypoint ep = new Entrypoint();

            APIGatewayProxyRequest request = new APIGatewayProxyRequest()
            {
                QueryStringParameters = new Dictionary <string, string>()
                {
                    { "output", "None" }
                }
            };

            TestLambdaLogger  logger  = new TestLambdaLogger();
            TestLambdaContext context = new TestLambdaContext();

            context.Logger = logger;

            // ACT
            APIGatewayProxyResponse response = await ep.GetData(request, context);

            // ASSERT
            Assert.Equal(200, response.StatusCode);
        }
예제 #29
0
        /// <summary>
        /// A Lambda function to respond to HTTP Post method from API Gateway from IoT
        /// </summary>
        /// <param name="request"></param>
        /// <returns>The response from the state machine: CurretState and Response</returns>
        public APIGatewayProxyResponse IoTEvent(APIGatewayProxyRequest request, ILambdaContext context)
        {
            // Using AWS CloudWatch to log
            context.Logger.LogLine("IoT Event\n");
            // JsonMachine is the state machine class
            JsonMachine jsonMachine = new JsonMachine(request?.Body);

            if (jsonMachine.Log != "")
            {
                context.Logger.LogLine(jsonMachine.Log);
            }

            // ApiResponse is a class defined in ApiBody.cs, a response data model toward IoT
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = JsonConvert.SerializeObject(jsonMachine.ApiResponse),
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            };

            return(response);
        }
예제 #30
0
        public async Task NotOverwriteCacheControlHeaderIfAlreadySet()
        {
            var middleware = new HttpCorsMiddleware(new CorsOptions
            {
                CacheControl = "max-age=3600, s-maxage=3600, proxy-revalidate"
            });

            var previousResponse = new APIGatewayProxyResponse
            {
                Headers = new Dictionary <string, string>
                {
                    { "Cache-Control", "max-age=1200" }
                }
            };

            request.HttpMethod = "OPTIONS";

            await middleware.Before(request, context);

            var response = await middleware.After(previousResponse, context);

            response.Headers.Should().Contain("Access-Control-Allow-Origin", "*");
            response.Headers.Should().Contain("Cache-Control", "max-age=1200");
        }