示例#1
0
        public async Task <APIGatewayProxyResponse> Handler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            var client = new AmazonDynamoDBClient();

            var attributes = new Dictionary <string, AttributeValue>();

            try
            {
                attributes["connectionId"] = new AttributeValue {
                    S = input.RequestContext.ConnectionId
                };
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = e.Message,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            var request = new PutItemRequest
            {
                TableName = Environment.ExpandEnvironmentVariables("%TABLE_NAME%"),
                Item      = attributes
            };

            var result = await client.PutItemAsync(request);

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)result.HttpStatusCode,
                Body = (result.HttpStatusCode == HttpStatusCode.OK) ? "connected" : "failed to connect",
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }
示例#2
0
        public APIGatewayProxyResponse Handler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            var config = new AmazonSimpleNotificationServiceConfig();

            config.ServiceURL = Environment.ExpandEnvironmentVariables("%SNSENDPOINT%");

            var client = new AmazonSimpleNotificationServiceClient(config);

            var request = new PublishRequest
            {
                TopicArn = Environment.ExpandEnvironmentVariables("%TOPICARN%"),
                Message  = input.Body,
            };

            try
            {
                client.PublishAsync(request).Wait();
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = e.Message,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            context.Logger.LogLine("PublishAsync completed\n");

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = input.Body,
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }
        /// <summary>
        ///     Populates the OwinContext with values from the proxy request.
        /// </summary>
        /// <param name="owinContext"></param>
        /// <param name="proxyRequest"></param>
        protected virtual async Task MarshalRequest(OwinContext owinContext, APIGatewayProxyRequest proxyRequest)
        {
            // The scheme is not available on the proxy request. If needed, it should be transported over custom header
            // and this MarshalRequest overridden.
            owinContext.Set(APIGatewayProxyRequestKey, proxyRequest);
            owinContext.Request.Scheme = "http";
            owinContext.Request.Method = proxyRequest.HttpMethod;
            owinContext.Request.Body   = _memoryStreamManager.GetStream(proxyRequest.Body);
            var writer = new StreamWriter(owinContext.Request.Body)
            {
                AutoFlush = true
            };
            await writer.WriteAsync(proxyRequest.Body);

            owinContext.Request.Body.Position = 0;
            if (proxyRequest.Headers != null)
            {
                foreach (var header in proxyRequest.Headers)
                {
                    owinContext.Request.Headers.AppendCommaSeparatedValues(header.Key, header.Value.Split(','));
                }
            }

            owinContext.Request.Path = new PathString(proxyRequest.Path);

            if (proxyRequest.QueryStringParameters != null)
            {
                var sb      = new StringBuilder();
                var encoder = UrlEncoder.Default;
                foreach (var kvp in proxyRequest.QueryStringParameters)
                {
                    if (sb.Length > 1)
                    {
                        sb.Append("&");
                    }
                    sb.Append($"{encoder.Encode(kvp.Key)}={encoder.Encode(kvp.Value)}");
                }
                owinContext.Request.QueryString = new QueryString(sb.ToString());
            }
            owinContext.Response.Body = _memoryStreamManager.GetStream();
        }
示例#4
0
        public override async Task <APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext lambdaContext)
        {
            if (string.IsNullOrEmpty(request.HttpMethod)) // For backward compatibility
            {
                if (request.Headers != null)
                {
                    if (request.Headers.ContainsKey(Concurrency))
                    {
                        var concurrency = int.Parse(request.Headers[Concurrency]);
                        await KeepAlive(concurrency - 1, KeepAliveInvocation);
                    }
                    if (request.Headers.ContainsKey(KeepAliveInvocation))
                    {
                        Thread.Sleep(75); // To mitigate lambda reuse
                    }
                    if (!Warm && !request.Headers.Keys.Any(key => key == Concurrency || key == KeepAliveInvocation))
                    {
                        LambdaLogger.Log($"[Info] Customer affected by coldstart");
                    }
                }

                lambdaContext.Logger.Log(JsonConvert.SerializeObject(request));

                if (Warm)
                {
                    lambdaContext.Logger.Log("ping");
                    return(new APIGatewayProxyResponse());
                }

                request.HttpMethod = "GET";
                request.Path       = "/ping";
                request.Headers    = new Dictionary <string, string> {
                    { "Host", "localhost" }
                };
                request.RequestContext = new APIGatewayProxyRequest.ProxyRequestContext();
                lambdaContext.Logger.LogLine("Keep-alive invocation");
            }

            Warm = true;
            return(await base.FunctionHandlerAsync(request, lambdaContext));
        }
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            VehicleRegistration vehicleRegistration = JsonConvert.DeserializeObject <VehicleRegistration>(request.Body);

            return(this.qldbDriver.Execute(transactionExecutor =>
            {
                context.Logger.Log($"Looking for person document ID {vehicleRegistration.Owners?.PrimaryOwner?.PersonId}.");
                string primaryOwnerPersonDocumentId = this.tableMetadataService.GetDocumentId(transactionExecutor, PersonTableName, "GovId", vehicleRegistration.Owners?.PrimaryOwner?.PersonId);

                if (string.IsNullOrWhiteSpace(primaryOwnerPersonDocumentId))
                {
                    context.Logger.Log($"No person found with GovId {vehicleRegistration.Owners?.PrimaryOwner?.PersonId}, returning not found.");
                    return new APIGatewayProxyResponse
                    {
                        StatusCode = (int)HttpStatusCode.NotFound
                    };
                }

                context.Logger.Log($"Checking vehicle registration already exists for VIN {vehicleRegistration.Vin}.");
                if (CheckIfVinAlreadyExists(transactionExecutor, vehicleRegistration.Vin))
                {
                    context.Logger.Log($"Vehicle registration does exist for VIN {vehicleRegistration.Vin}, returning not modified.");
                    return new APIGatewayProxyResponse
                    {
                        StatusCode = (int)HttpStatusCode.NotModified
                    };
                }

                context.Logger.Log($"Inserting vehicle registration for VIN {vehicleRegistration.Vin}.");
                vehicleRegistration.Owners.PrimaryOwner.PersonId = primaryOwnerPersonDocumentId;
                IIonValue ionVehicleRegistration = ConvertObjectToIonValue(vehicleRegistration);

                transactionExecutor.Execute($"INSERT INTO VehicleRegistration ?", ionVehicleRegistration);

                context.Logger.Log($"Inserted vehicle registration for VIN {vehicleRegistration.Vin}, returning OK.");
                return new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK
                };
            }));
        }
示例#6
0
        /// <summary> Internal executing (extract parameters and workaround code) </summary>
        private async Task <APIGatewayProxyResponse> InternalExecute(APIGatewayProxyRequest request,
                                                                     Func <string, Task <BasketEditResult> > executeFunc, ILogger?logger)
        {
            try
            {
                this.Basket.SetLogger(logger);

                if (request.PathParameters != null &&
                    request.PathParameters.ContainsKey("word")
                    )
                {
                    var word = request.PathParameters["word"];

                    await this.Basket.SaveStat(word, new TimeSpan());

                    var result = await executeFunc(word);

                    return(new APIGatewayProxyResponse
                    {
                        StatusCode = result.Result == BasketEditResult.EnumResult.Ok
                            ? (int)HttpStatusCode.OK
                            : (int)HttpStatusCode.InternalServerError,
                        Body = JsonConvert.SerializeObject(result)
                    });
                }

                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "'word' path not found"
                });
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Exception " + e.Message + "\n" + e.ToString()
                });
            }
        }
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var clientDomain = "https://www.primordial-software.com";
            var response     = new APIGatewayProxyResponse
            {
                Headers = new Dictionary <string, string>
                {
                    { "access-control-allow-origin", clientDomain },
                    { "Access-Control-Allow-Credentials", "true" }
                },
                StatusCode = 200
            };

            try
            {
                List <IRoute> routes = new List <IRoute>
                {
                };

                var matchedRoute = routes.FirstOrDefault(route => string.Equals(request.HttpMethod, route.HttpMethod, StringComparison.OrdinalIgnoreCase) &&
                                                         string.Equals(request.Path, route.Path, StringComparison.OrdinalIgnoreCase));
                if (matchedRoute != null)
                {
                    matchedRoute.Run(request, response);
                }
                else
                {
                    response.StatusCode = 404;
                    response.Body       = PropertyRentalManagement.Constants.JSON_EMPTY;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                response.StatusCode = 500;
                response.Body       = new JObject {
                    { "error", exception.ToString() }
                }.ToString();
            }
            return(response);
        }
示例#8
0
        public async Task HandleRequestAsync_ValidRequest_InvokesVehicleDataServiceImportVehicleDataAsyncWithExpectedArgs()
        {
            // Arrange

            const int    expectedCustomerId = 1;
            const string expectedVIN        = "VIN";

            var fakeValidateVIN = A.Fake <IValidateVIN>();

            A.CallTo(() => fakeValidateVIN.IsValid(expectedVIN)).Returns(true);

            var fakeVehicleDataService = A.Fake <IVehicleDataService>();

            IServiceProvider sp = new ServiceCollection()
                                  .AddSingleton(fakeValidateVIN)
                                  .AddSingleton(fakeVehicleDataService)
                                  .BuildServiceProvider();

            var context = A.Fake <ILambdaContext>();

            A.CallTo(() => context.Logger).Returns(A.Fake <ILambdaLogger>());

            var importRequest = new ImportRequest {
                CustomerId = expectedCustomerId, VIN = expectedVIN
            };

            APIGatewayProxyRequest dummyRequestEvent = new APIGatewayProxyRequest
            {
                Body = JsonConvert.SerializeObject(importRequest)
            };

            var sut = new ImportHandler(sp);

            // Act

            await sut.HandleRequestAsync(dummyRequestEvent, context);

            // Assert

            A.CallTo(() => fakeVehicleDataService.ImportVehicleDataAsync(expectedCustomerId, expectedVIN)).MustHaveHappenedOnceExactly();
        }
示例#9
0
        /// <summary>
        /// A Lambda function that returns the bid identified by bidId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> GetBidsByProductIdAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string productId = null;

            if (request.PathParameters != null && request.PathParameters.ContainsKey(PRODUCT_ID_QUERY_STRING_NAME))
            {
                productId = request.PathParameters[PRODUCT_ID_QUERY_STRING_NAME];
            }
            else if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey(PRODUCT_ID_QUERY_STRING_NAME))
            {
                productId = request.QueryStringParameters[PRODUCT_ID_QUERY_STRING_NAME];
            }

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

            context.Logger.LogLine($"Getting bids {productId}");

            var conditions = new List <ScanCondition>();

            conditions.Add(new ScanCondition("ProductId", Amazon.DynamoDBv2.DocumentModel.ScanOperator.Equal, productId));
            var search = this.DDBContext.ScanAsync <Bid>(conditions);
            var page   = await search.GetNextSetAsync();

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

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

            return(response);
        }
示例#10
0
        public APIGatewayProxyResponse CreateOrder(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("CreateOrder Request\n");

            var createOrderRequest = CreateOrderRequest.FromJson(request.Body);

            using ServiceProvider serviceProvider = _services.BuildServiceProvider();
            var createOrderService = serviceProvider.GetService <ICreateOrderService>();
            var mapper             = serviceProvider.GetService <IMapper>();

            try
            {
                var order = mapper.Map <OrderModel>(createOrderRequest.Order);

                var createdOrder = createOrderService.CreateOrderAsync(order)
                                   .GetAwaiter()
                                   .GetResult();

                var responseOrder = mapper.Map <Order>(createdOrder);

                var body     = responseOrder.ToJson();
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.Created,
                    Body       = body,
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                };

                return(response);
            }
            catch (FluentValidation.ValidationException exception)
            {
                return(exception.CreateResponse());
            }
            catch (Exception exception)
            {
                return(exception.CreateResponse());
            }
        }
示例#11
0
        /// <summary>
        /// A Lambda function that downloads the image from S3 Bucket by s3ObjectKey.
        /// path for http request: download/{s3ObjectKey}
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> GetImageAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            string s3ObjectKey = GetRequestParams(request);

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

            context.Logger.LogLine($"Getting object {s3ObjectKey}");
            try
            {
                using GetObjectResponse objectResponse = await _S3Client.GetObjectAsync("conqlimabucket", s3ObjectKey);

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

                var response = new APIGatewayProxyResponse
                {
                    IsBase64Encoded = true,
                    StatusCode      = (int)HttpStatusCode.OK,
                    Body            = Convert.ToBase64String(ReadStream(objectResponse.ResponseStream)),
                    Headers         = new Dictionary <string, string> {
                        { "Content-Type", "*/*" }
                    }
                };

                return(response);
            }
            catch (Exception e)
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.NotFound,
                    Body = e.Message
                });
            }
        }
示例#12
0
        public AuthenticationResult Authenticate(APIGatewayProxyRequest input)
        {
            if (!input.Headers.TryGetValue(XHubSignatureHeaderKey, out var signature) ||
                string.IsNullOrWhiteSpace(signature))
            {
                if (!bool.TryParse(
                    Environment.GetEnvironmentVariable(RequireSignatureEnvironmentVariableName),
                    out var requireSignature))
                {
                    // Require signature by default
                    requireSignature = true;
                }

                return requireSignature ?
                    AuthenticationResult.InvalidSignature :
                    AuthenticationResult.SignatureNotRequired;
            }

            var secretToken = Environment.GetEnvironmentVariable(SecretTokenEnvironmentVariableName);
            if (string.IsNullOrWhiteSpace(secretToken))
            {
                return AuthenticationResult.HasSignatureButMissingSecretToken;
            }

            if (!signature.StartsWith(SignaturePrefix))
            {
                return AuthenticationResult.InvalidSignature;
            }

            if (string.IsNullOrWhiteSpace(input.Body))
            {
                return AuthenticationResult.InvalidPayload;
            }

            if (!GenerateAndCompareSignature(secretToken, signature, input.Body))
            {
                return AuthenticationResult.MismatchedSignature;
            }

            return AuthenticationResult.Success;
        }
示例#13
0
        public async Task <bool> SendAlerts(APIGatewayProxyRequest request, string guid)
        {
            var fields = await ParseAlert(request);

            foreach (var alert in _alerts)
            {
                var sourceIp = request.RequestContext.Identity.SourceIp;
                var res      = await alert.SendAlert(fields, sourceIp, request.Path, guid);

                if (fields.Item1 != null)
                {
                    await alert.StoreLogs(fields.Item1, res);
                }
                else
                {
                    await alert.StoreLogs(sourceIp, res);
                }
            }

            return(fields.Item1 == null);
        }
示例#14
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
        {
            IBitcoinPriceCheck price   = new BitcoinPriceCheck();
            ITwitterProvider   twitter = new TwitterProvider();

            var res = await twitter.SendTweet(await price.Execute());

            var body = new Dictionary <string, string>
            {
                { "tweet", res.Url },
            };

            return(new APIGatewayProxyResponse
            {
                Body = JsonConvert.SerializeObject(body),
                StatusCode = 204,
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            });
        }
示例#15
0
        public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
            LambdaLogger.Log("body " + request.Body);
            if (request.Resource == "KeepWarm")
            {
                LambdaLogger.Log("Keeping warm run");
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = 200
                };
                return(response);
            }
            else
            {
                LambdaLogger.Log("Regular run");
            }

            var result = processor.CurrentTimeUTC();

            return(CreateResponse(result));
        }
示例#16
0
        public APIGatewayProxyResponse Hello(APIGatewayProxyRequest request, ILambdaContext context)
        {
            try{
                context.Logger.LogLine("START");


                context.Logger.LogLine("STOP");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine(ex.Message);
            }
            return(new APIGatewayProxyResponse()
            {
                StatusCode = 200,
                Body = JsonConvert.SerializeObject(new { msg = "Hello World!" }),
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "application/json" }
                }
            });
        }
示例#17
0
        public async Task <APIGatewayProxyResponse> Scrape(APIGatewayProxyRequest request, ILambdaContext context)
        {
            Scraper Scraper = JsonConvert.DeserializeObject <Scraper>(request.Body);

            Scraper.Start();

            var body = new Dictionary <string, string>()
            {
                { "title", Scraper.title }, { "body", Scraper.body }
            };

            return(new APIGatewayProxyResponse
            {
                StatusCode = 200,
                Body = JsonConvert.SerializeObject(body),
                Headers = new Dictionary <string, string>()
                {
                    { "Content-Type", "application/json" }, { "Access-Control-Allow-Origin", "*" }
                }
            });
        }
示例#18
0
        public void TestGetMethod()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions();

            var car = new Model.Car()
            {
                Model = "Passat", Mileage = 150000, Make = "VW", Year = 1999
            };

            request  = new APIGatewayProxyRequest();
            context  = new TestLambdaContext();
            response = functions.Get(request, context);
            Assert.Equal(200, response.StatusCode);
            string result = JsonConvert.SerializeObject(car);

            Assert.Equal(result, response.Body);
        }
        public async Task <APIGatewayProxyResponse> EventGet(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = context.Logger;

            logger.Log(JsonConvert.SerializeObject(request));
            var messageId = request.PathParameters.ContainsKey("messageId") ? request.PathParameters["messageId"] : throw new HttpRequestException("Bad Request");

            var businessEventStore = GetContainer(context).Resolve <IBusinessEventStore>();

            var item = await businessEventStore.QueryByMessageId(messageId, 1);

            return(new APIGatewayProxyResponse()
            {
                StatusCode = 200,
                Headers = new Dictionary <string, string>()
                {
                    { "Context-Type", "application/json" }
                },
                Body = JsonConvert.SerializeObject(item)
            });
        }
示例#20
0
        public void ListTransaction()
        {
            var function   = new FunctionListTransaction();
            var context    = new TestLambdaContext();
            var apiGateway = new APIGatewayProxyRequest
            {
                HttpMethod = "GET",
                Path       = "list-transaction",
                Resource   = "/dev/",
                Headers    = new Dictionary <string, string>()
                {
                    { "Content-Type", "application/json" }
                },
                QueryStringParameters = new Dictionary <string, string> {
                    { "id", "fgbOPGsBfKkxXf3E4Z5y" }
                }
            };
            var _return = function.FunctionHandler(apiGateway, context);

            Assert.Equal(200, _return.StatusCode);
        }
示例#21
0
        public void GetMessage()
        {
            var function   = new FunctionGetMessage();
            var context    = new TestLambdaContext();
            var apiGateway = new APIGatewayProxyRequest
            {
                HttpMethod = "GET",
                Path       = "get-message",
                Resource   = "/dev/",
                Headers    = new Dictionary <string, string>()
                {
                    { "Content-Type", "application/json" }
                },
                QueryStringParameters = new Dictionary <string, string> {
                    { "id", "bwZ2NGsBfKkxXf3Ebp6g" }
                }
            };
            var _return = function.FunctionHandler(apiGateway, context);

            Assert.Equal(200, _return.StatusCode);
        }
示例#22
0
        public APIGatewayProxyResponse GetStatusTraining(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request\n");
            var resp = request.Body;

            if (string.IsNullOrEmpty(resp))
            {
                return(RetornaBadRequest("Debe enviar contenido en el Body"));
            }

            GetStatusTrainingReq createTrainingJobReq = JsonConvert.DeserializeObject <GetStatusTrainingReq>(resp);

            context.Logger.LogLine("Req " + resp);

            GetStatusTrainingRes createTrainingJobRes = new GetStatusTrainingRes();

            createTrainingJobRes.Status = "COMPLETED";

            //return RetornaOk<CreateTrainingJobRes>(createTrainingJobRes);
            return(RetornaOk(createTrainingJobRes));
        }
示例#23
0
        public APIGatewayProxyResponse ValidateUser(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request\n");
            var resp = request.Body;

            if (string.IsNullOrEmpty(resp))
            {
                return(RetornaBadRequest("Debe enviar contenido en el Body"));
            }

            ValidateUserReq createTrainingJobReq = JsonConvert.DeserializeObject <ValidateUserReq>(resp);

            context.Logger.LogLine("Req " + resp);

            ValidateUserRes createTrainingJobRes = new ValidateUserRes();

            createTrainingJobRes.Token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI3MWNlNWUwYi1kMzViLTQ5NDUtYWNhNy1hMzA4Y2I5MzhjNGUiLCJ1c2VybmFtZSI6InRlc3QiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJpc3MiOiJodHRwczovL2NvZ25pdG8taWRwLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tL3VzLWVhc3QtMV9lWEY2T1B3NDUiLCJpYXQiOjE1MzcxOTgzNjAsIm5iZiI6MTUzNzE5ODM2MCwiZXhwIjoxNTM3MjAxOTYwLCJqdGkiOiI2ZGUyNzA5ZjlmNGQ0MmZkYTFiOTE5Y2JlZDBkNjA4NCJ9.QMddu_77AUR7kn0TBwpDKJoVH7QOcLCOR9nlbRledNma7zSIqISFWHQsDXg0IaLnhkruCUsILwxg4fg9KFSyIckk_xb75YgOdVcgbR1CV_kHRiNJcRn42HmORFqf_AzFCOqTGSpjMWTtAOqRfFLr0sIIu8tHx5ogj6_sT-1I7L8urTNgDRlsd1SGn_Xt1UVQkSgQ-PUCnxf7sdFSOq6jvOpH44uTTLsP3g9TxAQyMkpJGWLwcMqXQlS1N8SlG-xzlTIoKN7Kz5TA73F7C9z1Wifg_A2SrOKY1OdN6F6K-hQK2t2D4fMXQWyhXUqoXEaWq_dROgfL1oi0Mlm2LGFPDw";

            //return RetornaOk<CreateTrainingJobRes>(createTrainingJobRes);
            return(RetornaOk(createTrainingJobRes));
        }
示例#24
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 CreateTrainingJob(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request\n");
            var resp = request.Body;

            if (string.IsNullOrEmpty(resp))
            {
                return(RetornaBadRequest("Debe enviar contenido en el Body CreateTrainingJob"));
            }

            CreateTrainingJobReq createTrainingJobReq = JsonConvert.DeserializeObject <CreateTrainingJobReq>(resp);

            context.Logger.LogLine("Req " + resp);

            CreateTrainingJobRes createTrainingJobRes = new CreateTrainingJobRes();

            createTrainingJobRes.BankId = createTrainingJobReq.BankId;

            //return RetornaOk<CreateTrainingJobRes>(createTrainingJobRes);
            return(RetornaOk(createTrainingJobRes));
        }
示例#25
0
        public async Task Register_Valid_Test()
        {
            var handler = new Function(_MockSP.Object);
            var request = new APIGatewayProxyRequest()
            {
                HttpMethod = "POST",
                Body       = JsonConvert.SerializeObject(new Models.Endpoint()
                {
                    UserId      = "Test",
                    EndpointUrl = "google.com",
                    Token       = "123456"
                })
            };


            var response = await handler.RegisterHandler(request, _MockContext.Object);

            Assert.AreEqual(200, response.StatusCode);
            _MockSP.Verify(f => f.GetService(typeof(IEndpointService)), Times.Once);
            _MockEndpoint.Verify(f => f.SaveEndpoint(It.IsAny <Models.Endpoint>()), Times.Once);
        }
示例#26
0
        public async Task <APIGatewayProxyResponse> Handle(APIGatewayProxyRequest request)
        {
            var idStr = request.PathParameters["id"];

            if (!Guid.TryParse(idStr, out var id))
            {
                return(Response.CreateError(HttpStatusCode.BadRequest, "Invalid photograph id"));
            }

            var photographTable = Table.LoadTable(_dynamoDb, TableNames.Photograph);
            var document        = await photographTable.GetItemAsync(id);

            if (document == null)
            {
                return(Response.CreateError(HttpStatusCode.NotFound, "No photograph with the requested id was found"));
            }

            var model = PhotographSerialization.FromDocument(document);

            return(BuildResponseFromModel(model));
        }
        /// <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 Handler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext apigProxyContext)
        {
            try
            {
                var users = new List <User>();

                int counter = 0;
                while (counter < 25)
                {
                    users.Add(GetUser());
                    counter++;
                }

                return(JsonResponse.Send(true, "Success", users));
            }
            catch (Exception e)
            {
                LambdaLogger.Log("Handler Error - " + e.Message);
                return(JsonResponse.Send(false, e.Message));
            }
        }