Esempio n. 1
0
        public async Task <Simulate> Run(SimulateParams simulateParams)
        {
            using (var client = new AmazonLambdaClient(RegionEndpoint.USEast2))
            {
                var apirequest = new APIGatewayProxyRequest()
                {
                    QueryStringParameters = new Dictionary <string, string>()
                };

                foreach (PropertyInfo param in simulateParams.GetType().GetProperties())
                {
                    apirequest.QueryStringParameters.Add(param.Name, param.GetValue(simulateParams).ToString());
                }

                var request = new InvokeRequest
                {
                    FunctionName = "simulate",
                    Payload      = JsonConvert.SerializeObject(apirequest)
                };

                var response = await client.InvokeAsync(request);

                string result;

                using (var sr = new StreamReader(response.Payload))
                {
                    result = sr.ReadToEnd();
                    SimulateHttpResponse httpResponse = JsonConvert.DeserializeObject <SimulateHttpResponse>(result);
                    Simulate             simulation   = JsonConvert.DeserializeObject <Simulate>(httpResponse.Body);
                    return(simulation);
                }
            }
        }
Esempio n. 2
0
        public async Task TestAllHandlersAsync()
        {
            // run all test cases in one test to ensure they run serially
            using (var lambdaClient = new AmazonLambdaClient(TestRegion))
                using (var s3Client = new AmazonS3Client(TestRegion))
                    using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion))
                    {
                        var roleAlreadyExisted = false;

                        try
                        {
                            roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient);

                            await RunTestSuccessAsync(lambdaClient, "ToUpperAsync", "message", "ToUpperAsync-MESSAGE");
                            await RunTestSuccessAsync(lambdaClient, "PingAsync", "ping", "PingAsync-pong");
                            await RunTestSuccessAsync(lambdaClient, "HttpsWorksAsync", "", "HttpsWorksAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "CertificateCallbackWorksAsync", "", "CertificateCallbackWorksAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "NetworkingProtocolsAsync", "", "NetworkingProtocolsAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "HandlerEnvVarAsync", "", "HandlerEnvVarAsync-HandlerEnvVarAsync");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrappedAsync", "", "Exception", "Exception thrown from an async handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrapped", "", "Exception", "Exception thrown from a synchronous handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrappedAsync", "", "AggregateException", "AggregateException thrown from an async handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrapped", "", "AggregateException", "AggregateException thrown from a synchronous handler.");
                            await RunTestExceptionAsync(lambdaClient, "TooLargeResponseBodyAsync", "", "Function.ResponseSizeTooLarge", "Response payload size (7340060 bytes) exceeded maximum allowed payload size (6291556 bytes).");
                            await RunTestSuccessAsync(lambdaClient, "LambdaEnvironmentAsync", "", "LambdaEnvironmentAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "LambdaContextBasicAsync", "", "LambdaContextBasicAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "GetPidDllImportAsync", "", "GetPidDllImportAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "GetTimezoneNameAsync", "", "GetTimezoneNameAsync-UTC");
                        }
                        finally
                        {
                            await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted);
                        }
                    }
        }
Esempio n. 3
0
        private async Task NotifySubscribers(Subscription[] subscribers, Event @event)
        {
            using (var client = new AmazonLambdaClient())
            {
                foreach (var subscriber in subscribers)
                {
                    var request = new InvokeRequest
                    {
                        FunctionName = notifierFunctionResolver.GetNotifierFunction(),
                        Payload      = JsonConvert.SerializeObject(new LambdaInvocationPayload()
                        {
                            CompressedEvent = JsonConvert.SerializeObject(@event).ToCompressedBase64String(),
                            Subscription    = subscriber
                        }),
                        InvocationType = InvocationType.Event
                    };

                    Console.WriteLine($"NotifySubscriber MessageId: {@event.Message.Header.MessageId} Subscriber: {subscriber.Type}:{subscriber.Endpoint}");
                    var response = await client.InvokeAsync(request);

                    Console.WriteLine($"NotifySubscriberResponse MessageId: {@event.Message.Header.MessageId} Subscriber: {subscriber.Type}:{subscriber.Endpoint} Response Code: {response.StatusCode}");

                    if (response.StatusCode > 299)
                    {
                        Console.WriteLine($"MessageId: {@event.Message.Header.MessageId} Subscriber: {subscriber.Type}:{subscriber.Endpoint} Error: {response}");
                    }
                }
            }
        }
Esempio n. 4
0
        public InvokeResponse Invoke(string functionName, string path, string data)
        {
            JObject pathParams;
            var     template_name = Path.Combine(System.Environment.CurrentDirectory, "WhooshRequestTemplate.json");
            var     fileData      = File.ReadAllText(template_name);
            JObject payLoad       = JObject.Parse(fileData);

            payLoad.Add("path", path);
            pathParams = (JObject)payLoad["pathParameters"];
            pathParams.Add("key", data);

            var region_name = config.AwsRegionName;
            var env_id      = "v8";
            // var env_id = config.AwsNamespace;

            AmazonLambdaClient client  = new AmazonLambdaClient(RegionEndpoint.GetBySystemName(region_name));
            InvokeRequest      request = new InvokeRequest()
            {
                FunctionName = $"PY-{env_id}",
                Payload      = payLoad.ToString(),
            };

            var response = client.InvokeAsync(request).GetAwaiter().GetResult();

            return(response);
        }
    public async void ExecuteLambda()
    {
        Debug.Log("ExecuteLambda");

        AmazonLambdaClient amazonLambdaClient = new AmazonLambdaClient(_authenticationManager.GetCredentials(), AuthenticationManager.Region);

        InvokeRequest invokeRequest = new InvokeRequest
        {
            FunctionName   = _lambdaFunctionName,
            InvocationType = InvocationType.RequestResponse
        };

        InvokeResponse response = await amazonLambdaClient.InvokeAsync(invokeRequest);

        Debug.Log("Response statusCode: " + response.StatusCode);

        if (response.StatusCode == 200)
        {
            Debug.Log("Successful lambda call");

            // demonstrate we can get the users ID for use in our game
            string userId = _authenticationManager.GetUsersId();
            Debug.Log("UserId in LambdaManager: " + userId);
        }
    }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonLambdaConfig config = new AmazonLambdaConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonLambdaClient client = new AmazonLambdaClient(creds, config);

            ListFunctionsResponse resp = new ListFunctionsResponse();

            do
            {
                ListFunctionsRequest req = new ListFunctionsRequest
                {
                    Marker = resp.NextMarker
                    ,
                    MaxItems = maxItems
                };

                resp = client.ListFunctions(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Functions)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextMarker));
        }
        private static async Task <List <FunctionConfiguration> > GetLambdaVersions(FunctionVersion functionVersion, AWSEnvironment environment)
        {
            var versionNumber = functionVersion != null ? Constants.LambdaAll : Constants.LambdaLastVersion;

            Console.WriteLine($"Reading lambda function versions: {versionNumber}");

            var result = new List <FunctionConfiguration>();

            var awsConfiguration = new AmazonLambdaConfig()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(environment.Region)
            };

            var awsCredentials = new BasicAWSCredentials(environment.AccessKey, environment.SecretKey);

            string marker = null;

            using (var awsClient = new AmazonLambdaClient(awsCredentials, awsConfiguration))
            {
                do
                {
                    var response = await awsClient.ListFunctionsAsync(new ListFunctionsRequest
                    {
                        Marker          = marker,
                        FunctionVersion = functionVersion
                    });

                    //marker =Task<List<ListFunctionsRequest>> response.Result.NextMarker;
                    marker = response.NextMarker;
                    result.AddRange(response.Functions.Where(x => x.FunctionName.StartsWith($"{environment.Name.ToString()}")));
                } while (!string.IsNullOrEmpty(marker));

                return(result);
            }
        }
Esempio n. 8
0
        public async Task <String> SetPermission(AmazonLambdaClient lambda, String rulearn, String rulename)
        {
            //var RemovePermissionRequest = new RemovePermissionRequest
            //{
            //    FunctionName = "Ec2StartStop",
            //    StatementId = rulename
            //};
            try
            {
                var AddPermissionRequest = new AddPermissionRequest
                {
                    Action       = "lambda:InvokeFunction",
                    FunctionName = "Ec2StartStop",
                    Principal    = "events.amazonaws.com",
                    SourceArn    = rulearn,
                    StatementId  = rulename
                };
                var AddPermissionResponse = await lambda.AddPermissionAsync(AddPermissionRequest);

                return("sucessfully created permission");
            }
            catch (Exception e)
            {
                return("permission already exists");
            }
        }
Esempio n. 9
0
        public void TestLambdaInvokeSubsegmentContainsFunctionNameForAWSSDKHandler()
        {
            String temp_path = @"JSONs\AWSRequestInfoWithLambda.json"; //registering manifest file with Lambda

            AWSSDKHandler.RegisterXRayManifest(temp_path);
            var lambda = new AmazonLambdaClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            CustomResponses.SetResponse(lambda, null, null, true);
            AWSXRayRecorder.Instance.BeginSegment("lambda", TraceId);
#if NET45
            lambda.Invoke(new InvokeRequest
            {
                FunctionName = "testFunction"
            });
#else
            lambda.InvokeAsync(new InvokeRequest
            {
                FunctionName = "testFunction"
            }).Wait();
#endif
            var segment = TraceContext.GetEntity();
            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("Invoke", segment.Subsegments[0].Aws["operation"]);
            Assert.AreEqual("testFunction", segment.Subsegments[0].Aws["function_name"]);
        }
        public async Task TestThreadingLogging()
        {
            // run all test cases in one test to ensure they run serially
            using (var lambdaClient = new AmazonLambdaClient(TestRegion))
                using (var s3Client = new AmazonS3Client(TestRegion))
                    using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion))
                    {
                        var roleAlreadyExisted = false;

                        try
                        {
                            roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient);
                            await InvokeLoggerTestController(lambdaClient);
                        }
                        catch (NoDeploymentPackageFoundException)
                        {
#if DEBUG
                            // The CodePipeline for this project doesn't currently build the deployment in the stage that runs
                            // this test. For now ignore this test in release mode if the deployment package can't be found.
                            throw;
#endif
                        }
                        finally
                        {
                            await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted);
                        }
                    }
        }
        private async Task <bool> InvokeFunction(string function, dynamic payload)
        {
            AmazonLambdaClient lambda;

            if (Debugger.IsAttached)
            {
                lambda = new AmazonLambdaClient(new BasicAWSCredentials(_configuration["AWS:AccessKey"], _configuration["AWS:SecretKey"]), RegionEndpoint.USEast1);
            }
            else
            {
                lambda = new AmazonLambdaClient(RegionEndpoint.USEast1);
            }
            var request = new InvokeRequest
            {
                FunctionName = function,
                Payload      = JsonConvert.SerializeObject(new APIGatewayProxyRequest()
                {
                    Body = JsonConvert.SerializeObject(payload)
                })
            };
            var response = await lambda.InvokeAsync(request);

            using var sr = new StreamReader(response.Payload);
            var content = await sr.ReadToEndAsync();

            var result     = JsonConvert.DeserializeObject <APIGatewayProxyRequest>(content);
            var fbResponse = JsonConvert.DeserializeObject <Response>(result.Body);

            return(fbResponse.Content.Equals(true));
        }
Esempio n. 12
0
        public static string UpdateLambdaFunction(string functionName, string javaScript)
        {
            var ms = new MemoryStream();

            File.WriteAllText(Properties.Settings.Default.RuleFilePath, javaScript);

            using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                zipArchive.CreateEntryFromFile(Properties.Settings.Default.IndexFilePath, Path.GetFileName(Properties.Settings.Default.IndexFilePath), CompressionLevel.Fastest);
                zipArchive.CreateEntryFromFile(Properties.Settings.Default.RuleFilePath, Path.GetFileName(Properties.Settings.Default.RuleFilePath), CompressionLevel.Fastest);
            }

            string responseText;

            try
            {
                var client = new AmazonLambdaClient(Properties.Settings.Default.AwsAccessKeyId, Properties.Settings.Default.AwsSecretKey, Amazon.RegionEndpoint.USEast1);

                var response = client.UpdateFunctionCode(new UpdateFunctionCodeRequest
                {
                    FunctionName = functionName,
                    Publish      = false,
                    ZipFile      = ms
                });

                responseText = response.ToString();
            }
            catch (Exception ex)
            {
                responseText = ex.ToString();
            }

            return(responseText);
        }
        public void PrintPosts()
        {
            using (AmazonLambdaClient client = new AmazonLambdaClient())
            {
                GetPostsRequest postsRequest = new GetPostsRequest()
                {
                    SortBy = "timestamp", SortOrder = "descending", PostsToGet = postsToGet
                };
                string payload = GetJson(typeof(GetPostsRequest), postsRequest);

                InvokeRequest iRequest = new InvokeRequest()
                {
                    FunctionName = "GetPosts",
                    Payload      = payload
                };
                InvokeResponse response = client.Invoke(iRequest);
                var            sr       = new StreamReader(response.Payload);
                string         result   = sr.ReadToEnd();
                if (result.Contains("\"result\":\"failure\""))
                {
                    GetPostsFail(result);
                    return;
                }



                download = ProcessPostDataJson(result);
                IList <GridItem> items = download.Values;
                dataGrid.ItemsSource = items;
                dataGrid.ColumnWidth = DataGridLength.SizeToCells;
                int itemCount = dataGrid.Items.Count;
                dataGrid.ScrollIntoView(dataGrid.Items[itemCount - 1]);
            }
        }
        public async UniTask <ConnectionConfig> GetConnectionConfig(string roomName, string playerId)
        {
            RegionEndpoint        regionEndpoint = RegionEndpoint.GetBySystemName(_Config.Region);
            CognitoAWSCredentials credentials    = new CognitoAWSCredentials(_Config.IdentityPoolId, regionEndpoint);

            AmazonLambdaClient lambdaClient = new AmazonLambdaClient(credentials, regionEndpoint);
            string             jsonStr      = JsonUtility.ToJson(new ConnectionConfigRequest(roomName, playerId));

            var response = await InvokeLambdaFunctionAsync(lambdaClient, _Config.LambdaFunctionName, InvocationType.RequestResponse, jsonStr);

            if (response.FunctionError == null)
            {
                if (response.StatusCode == 200)
                {
                    var payload = Encoding.ASCII.GetString(response.Payload.ToArray()) + "\n";
                    var session = JsonUtility.FromJson <ConnectionConfigResponse>(payload);

                    if (session == null)
                    {
                        Debug.LogError($"[LambdaClient] Error in Lambda: {payload}");
                    }
                    else
                    {
                        return(new ConnectionConfig(session.IpAddress, session.Port, session.SystemUserId));
                    }
                }
            }

            Debug.LogError(response.FunctionError);
            return(ConnectionConfig.GetDefault());
        }
Esempio n. 15
0
        public async Task <object> FunctionHandler(ILambdaContext context)
        {
            try
            {
                using (AmazonLambdaClient client = new AmazonLambdaClient(RegionEndpoint.APSoutheast1))
                {
                    var request = new Amazon.Lambda.Model.InvokeRequest
                    {
                        FunctionName = "test_call_rest_api",
                        Payload      = ""
                    };

                    var response = await client.InvokeAsync(request);

                    using (var sr = new StreamReader(response.Payload))
                    {
                        var unit = JsonConvert.DeserializeObject(sr.ReadToEndAsync().Result,
                                                                 new JsonSerializerSettings {
                            NullValueHandling = NullValueHandling.Ignore
                        });

                        return(unit);
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Esempio n. 16
0
        // ADD TO MIDDLE
        public async Task <bool> IsReferencePhotoValid(string filePath)
        {
            Object emotResult = new ArrayList();

            // Uploading file to S3
            await uploadReferencePhoto(filePath);

            // Calling our Lambda function
            AmazonLambdaClient amazonLambdaClient = new AmazonLambdaClient(accessKey, privateKey, Amazon.RegionEndpoint.EUWest2);
            InvokeRequest      ir = new InvokeRequest();

            ir.InvocationType = InvocationType.RequestResponse;
            ir.FunctionName   = "IsReferencePhotoValid";

            // Selecting which file from S3 should our function use
            ir.Payload = "\"" + "referencePhoto.jpg" + "\"";

            // Getting the result
            var resultAWS = await amazonLambdaClient.InvokeAsync(ir);

            // Picking up the result value
            string response = Encoding.ASCII.GetString(resultAWS.Payload.ToArray());

            response = response.Replace("\"", "");
            bool result = bool.Parse(response);

            if (result == false)
            {
                throw new InvalidReferencePictureException("test");
            }

            return(bool.Parse(response));
        }
        public static async Task <string> InvokeAWSLambda(string functionName, string payLoad, RegionEndpoint regionEndpoint)
        {
            try
            {
                if (!String.IsNullOrEmpty(functionName) && !String.IsNullOrEmpty(payLoad))
                {
                    var newPayload = new RoutingLambdaRequestModel()
                    {
                        body = payLoad
                    };
                    var lambdaClient = new AmazonLambdaClient(IdentifierEnvironmentConstants.IdentifierConfigurations.RoutingLambdaCredentials.AccessKey, IdentifierEnvironmentConstants.IdentifierConfigurations.RoutingLambdaCredentials.Secret, regionEndpoint);

                    var response = await lambdaClient.InvokeAsync(new InvokeRequest
                    {
                        FunctionName   = functionName,
                        InvocationType = InvocationType.RequestResponse,
                        LogType        = LogType.None,
                        Payload        = JsonConvert.SerializeObject(newPayload)
                    });

                    using (var reader = response.Payload)
                    {
                        return(new StreamReader(reader).ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Esempio n. 18
0
        // ADD TO MIDDLE
        public async Task <string> WhatEmot(string filePath, string fileName)
        {
            Object emotResult = new ArrayList();

            // Uploading file to S3
            await UploadToS3(filePath, fileName);

            // Calling our Lambda function
            AmazonLambdaClient amazonLambdaClient = new AmazonLambdaClient(accessKey, privateKey, Amazon.RegionEndpoint.EUWest2);
            InvokeRequest      ir = new InvokeRequest();

            ir.InvocationType = InvocationType.RequestResponse;
            ir.FunctionName   = "MyAWS";

            // Selecting which file from S3 should our function use
            ir.Payload = "\"" + fileName + "\"";

            // Getting the result
            var result = await amazonLambdaClient.InvokeAsync(ir);

            // Picking up the result value
            string response = Encoding.ASCII.GetString(result.Payload.ToArray());

            return(response);
        }
        private static async Task <bool> DeleteLambda(FunctionConfiguration lambda, AWSEnvironment environment)
        {
            try
            {
                var awsConfiguration = new AmazonLambdaConfig()
                {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(environment.Region)
                };

                var awsCredentials = new BasicAWSCredentials(environment.AccessKey, environment.SecretKey);

                using (var awsClient = new AmazonLambdaClient(awsCredentials, awsConfiguration))
                {
                    var response = await awsClient.DeleteFunctionAsync(new DeleteFunctionRequest
                    {
                        FunctionName = lambda.FunctionName,
                        Qualifier    = lambda.Version //ARN
                    });

                    Console.WriteLine($"Lamba {lambda.FunctionName} deleted.");
                    return(response.HttpStatusCode == HttpStatusCode.NoContent); //204
                };
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine($"Error: {ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            return(false);
        }
        public static async Task DeleteJobAsync(ApiGatewayRequest request, McmaApiResponse response)
        {
            Logger.Debug(nameof(DeleteJobAsync));
            Logger.Debug(request.ToMcmaJson().ToString());

            var table = new DynamoDbTable(request.StageVariables["TableName"]);

            var jobId = request.StageVariables["PublicUrl"] + request.Path;

            var job = await table.GetAsync <Job>(jobId);

            if (job == null)
            {
                response.StatusCode    = (int)HttpStatusCode.NotFound;
                response.StatusMessage = "No resource found on path '" + request.Path + "'.";
                return;
            }

            await table.DeleteAsync <Job>(jobId);

            // invoking worker lambda function that will delete the JobProcess created for this Job
            if (!string.IsNullOrEmpty(job.JobProcess))
            {
                var lambdaClient  = new AmazonLambdaClient();
                var invokeRequest = new InvokeRequest
                {
                    FunctionName   = request.StageVariables["WorkerLambdaFunctionName"],
                    InvocationType = "Event",
                    LogType        = "None",
                    Payload        = new { action = "deleteJobProcess", request = request, jobProcessId = job.JobProcess }.ToMcmaJson().ToString()
                };

                await lambdaClient.InvokeAsync(invokeRequest);
            }
        }
Esempio n. 21
0
    void Awake()
    {
        UnityInitializer.AttachToGameObject(gameObject);

        credentials = new CognitoAWSCredentials("eu-west-2:793871cb-c8a9-45bf-b20d-97df75ddbce7", RegionEndpoint.EUWest2);
        lambda      = new AmazonLambdaClient(credentials, RegionEndpoint.EUWest2);
    }
Esempio n. 22
0
        async static Task InvokeViaSdk(Stream fileStream)
        {
            var lambdaConfig = new AmazonLambdaConfig
            {
                ServiceURL = "http://localhost:4566"
            };

            using var lambda       = new AmazonLambdaClient(lambdaConfig);
            using var memoryStream = new MemoryStream();
            fileStream.CopyTo(memoryStream);

            var getFunctionRequest = new GetFunctionRequest
            {
                FunctionName = "ConverterTronStack-ConverterTronLambda-V6ZBU97Z5XM0"
            };

            var invokeRequest = new InvokeRequest
            {
                FunctionName   = "ConverterTronStack-ConverterTronLambda-V6ZBU97Z5XM0",
                InvocationType = InvocationType.RequestResponse,
                PayloadStream  = memoryStream
            };

            var getThings = await lambda.GetFunctionAsync(getFunctionRequest);

            var response = await lambda.InvokeAsync(invokeRequest);
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            //Create a new AmazonLambdaClient
            AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USEast2);

            //Create new InvokeRequest with published function name.
            InvokeRequest invoke = new InvokeRequest
            {
                FunctionName   = "MyNewFunction",
                InvocationType = InvocationType.RequestResponse,
                Payload        = "\"Test\""
            };

            //Get the InvokeResponse from client InvokeRequest.
            InvokeResponse response = client.Invoke(invoke);

            //Read the response stream
            var        stream       = new StreamReader(response.Payload);
            JsonReader reader       = new JsonTextReader(stream);
            var        serilizer    = new JsonSerializer();
            var        responseText = serilizer.Deserialize(reader);

            //Convert Base64String into PDF document
            byte[]       bytes      = Convert.FromBase64String(responseText.ToString());
            FileStream   fileStream = new FileStream("Sample.pdf", FileMode.Create);
            BinaryWriter writer     = new BinaryWriter(fileStream);

            writer.Write(bytes, 0, bytes.Length);
            writer.Close();
            System.Diagnostics.Process.Start("Sample.pdf");
        }
        public static async Task ProcessNotificationAsync(ApiGatewayRequest request, McmaApiResponse response)
        {
            var table = new DynamoDbTable(request.StageVariables["TableName"]);

            var jobAssignmentId = request.StageVariables["PublicUrl"] + "/job-assignments/" + request.PathVariables["id"];

            var jobAssignment = await table.GetAsync <JobAssignment>(jobAssignmentId);

            if (jobAssignment == null)
            {
                response.StatusCode    = (int)HttpStatusCode.NotFound;
                response.StatusMessage = "No resource found on path '" + request.Path + "'";
                return;
            }

            var notification = request.JsonBody?.ToMcmaObject <Notification>();

            if (notification == null)
            {
                response.StatusCode    = (int)HttpStatusCode.BadRequest;
                response.StatusMessage = "Missing notification in request body";
                return;
            }

            var lambdaClient  = new AmazonLambdaClient();
            var invokeRequest = new InvokeRequest
            {
                FunctionName   = request.StageVariables["WorkerLambdaFunctionName"],
                InvocationType = "Event",
                LogType        = "None",
                Payload        = new { action = "ProcessNotification", request = request, jobAssignmentId = jobAssignmentId, notification = notification }.ToMcmaJson().ToString()
            };

            await lambdaClient.InvokeAsync(invokeRequest);
        }
Esempio n. 25
0
        /// <summary>
        /// Clean up all test resources.
        /// Also cleans up any resources that might be left from previous failed/interrupted tests.
        /// </summary>
        /// <param name="s3Client"></param>
        /// <param name="lambdaClient"></param>
        /// <returns></returns>
        private async Task CleanUpTestResources(AmazonS3Client s3Client, AmazonLambdaClient lambdaClient,
                                                AmazonIdentityManagementServiceClient iamClient, bool roleAlreadyExisted)
        {
            await DeleteFunctionIfExistsAsync(lambdaClient);

            var listBucketsResponse = await s3Client.ListBucketsAsync();

            foreach (var bucket in listBucketsResponse.Buckets)
            {
                if (bucket.BucketName.StartsWith(TestBucketRoot))
                {
                    await DeleteDeploymentZipAndBucketAsync(s3Client, bucket.BucketName);
                }
            }

            if (!roleAlreadyExisted)
            {
                try
                {
                    var deleteRoleRequest = new DeleteRoleRequest
                    {
                        RoleName = ExecutionRoleName
                    };
                    await iamClient.DeleteRoleAsync(deleteRoleRequest);
                }
                catch (Exception)
                {
                    // no problem - it's best effort
                }
            }
        }
        public async Task Given_valid_payload_when_lambda_invoked_synchronously_then_should_return_expected_response()
        {
            // Given
            var client   = new AmazonLambdaClient();
            var sqsEvent = new SQSEvent
            {
                Records = new List <SQSEvent.SQSMessage>
                {
                    new SQSEvent.SQSMessage
                    {
                        Body = "Hello Lambda!"
                    }
                }
            };

            var request = new InvokeRequest
            {
                FunctionName = "1-direct-invocation",
                // force sync lambda invocation
                InvocationType = InvocationType.RequestResponse,
                LogType        = LogType.Tail,
                Payload        = JsonSerializer.Serialize(sqsEvent)
            };

            // When
            var result = await client.InvokeAsync(request);

            // Then
            Assert.Null(result.FunctionError);

            using var sr = new StreamReader(result.Payload);
            var response = await sr.ReadToEndAsync();

            Assert.Equal("HELLO LAMBDA!", response.Replace("\"", ""));
        }
Esempio n. 27
0
        public override async Task <APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request,
                                                                                  ILambdaContext lambdaContext)
        {
            Console.WriteLine("In overridden FunctionHandlerAsync...");

            if (request.Resource == "WarmingLambda")
            {
                int.TryParse(request.Body, out var concurrencyCount);

                if (concurrencyCount > 1)
                {
                    Console.WriteLine($"Warming instance {concurrencyCount}.");
                    var client = new AmazonLambdaClient();
                    await client.InvokeAsync(new Amazon.Lambda.Model.InvokeRequest
                    {
                        FunctionName   = lambdaContext.FunctionName,
                        InvocationType = InvocationType.RequestResponse,
                        Payload        = JsonConvert.SerializeObject(new APIGatewayProxyRequest
                        {
                            Resource = request.Resource,
                            Body     = (concurrencyCount - 1).ToString()
                        })
                    });
                }

                return(new APIGatewayProxyResponse {
                });
            }

            return(await base.FunctionHandlerAsync(request, lambdaContext));
        }
Esempio n. 28
0
        async Task ConfigureLambdaWithQueueAsync(string queueName)
        {
            string queueArn = null;

            AmazonSQSClient sqsClient = AwsFactory.CreateClient <AmazonSQSClient>();

            GetQueueUrlRequest queueUrlReq = new GetQueueUrlRequest();

            queueUrlReq.QueueName = queueName;

            GetQueueUrlResponse getQueueUrlResp = await sqsClient.GetQueueUrlAsync(queueUrlReq);

            GetQueueAttributesRequest queueAttribReq = new GetQueueAttributesRequest();

            queueAttribReq.AttributeNames.Add(QueueAttributeName.QueueArn);
            queueAttribReq.QueueUrl = getQueueUrlResp.QueueUrl;

            var queueAttribResp = await sqsClient.GetQueueAttributesAsync(queueAttribReq);

            queueArn = queueAttribResp.QueueARN;

            AmazonLambdaClient lambdaClient = AwsFactory.CreateClient <AmazonLambdaClient>();

            CreateEventSourceMappingRequest eventMappingReq = new CreateEventSourceMappingRequest();

            eventMappingReq.FunctionName   = "WebhookDispatcher";
            eventMappingReq.BatchSize      = 10;
            eventMappingReq.Enabled        = true;
            eventMappingReq.EventSourceArn = queueArn;

            await lambdaClient.CreateEventSourceMappingAsync(eventMappingReq);
        }
        private static LambdaWorkerExecutor CreateExecutor()
        {
            var lambda       = new AmazonLambdaClient();
            var functionName = Environment.GetEnvironmentVariable("WORKER_FUNCTION_NAME");

            return(new LambdaWorkerExecutor(lambda, functionName));
        }
        internal static async Task <UpdateFunctionCodeResponse> UpdateFunctionCodeAsync
        (
            this AmazonLambdaClient client,
            AppPackage package,

            ASPNetServerLessPublishAWSLambdaConfigSection lambdaConfig,
            CancellationToken cancellationToken = default(CancellationToken)
        )
        {
            var response = (UpdateFunctionCodeResponse)null;

            using (var packageStream = new MemoryStream(package.PackageBytes))
            {
                var updateCodeRequest = new UpdateFunctionCodeRequest()
                {
                    FunctionName = lambdaConfig.FunctionName,
                    ZipFile      = packageStream
                };

                response = await client.UpdateFunctionCodeAsync(updateCodeRequest, cancellationToken).ConfigureAwait(false);

                updateCodeRequest = null;
            }

            return(response);
        }