public override void invoke(InvokeRequest req) { Console.WriteLine(req); // send in s1.onentry if ("Some string content" == req.getContent()) { returnEvent(new Event("received1")); return; } }
public InvokeResponse Invoke(InvokeRequest request) { InvokeResponse response = new InvokeResponse(); if (!string.IsNullOrEmpty(request.ComponentType)) { IServiceComponentManager componentManager = Container.Resolve<IServiceComponentManager>(); IServiceComponent component = componentManager.ServiceComponents.FirstOrDefault(c => c != null && c.GetType().GetInterface(request.ComponentType) != null); if (component != null) { MethodInfo operation = component.GetType().GetMethod(request.OperationName, request.OperationParameters.Select(op => DataContractUtility.GetType(op.AssemblyQualifiedTypeName, op.TypeName, op.IsEnumerable)).ToArray()); if (operation != null) { try { List<object> parameters = new List<object>(); foreach (InvokeParameter parameter in request.OperationParameters) parameters.Add(DataContractUtility.Deserialize(DataContractUtility.GetType(parameter.AssemblyQualifiedTypeName, parameter.TypeName, parameter.IsEnumerable), parameter.SerializedParameter)); object result; try { result = operation.Invoke(component, parameters.ToArray()); if (result != null) response.OperationResult = DataContractUtility.Serialize(result.GetType(), result); } catch (Exception ex) { response.Error = new Exception("An exception occurred trying to invoke operation.", ex); } } catch (Exception ex) { response.Error = new InvalidRequestException("An exception occurred trying to deserialize operation parameters.", ex); } } else response.Error = new InvalidRequestException("Operation not found."); } else response.Error = new InvalidRequestException("Component not found."); } else response.Error = new InvalidRequestException("Component type not provided."); return response; }
public Task <InvokeResponse> Invoke(Method[] methods, InvokeOptions options = null) { var invokeRequest = new InvokeRequest { i = methods.Select(v => new Invocation { i = v.Object.Id.ToString(), v = v.Object.Version.ToString(), m = v.MethodType.IdAsString, }).ToArray(), o = options, }; return(this.database.Invoke(invokeRequest)); }
private async Task InvokeLambdaAndDeleteMessage(Message sqsMessage) { var request = new InvokeRequest { FunctionName = EnvironmentVariables.SendEmailLambdaName, Payload = sqsMessage.Body }; var invokeResponse = await _lambdaClient.InvokeAsync(request); if (WasCorrectlySent(invokeResponse)) { await DeleteMessage(sqsMessage, invokeResponse); } }
/// <summary> /// 新增交易 /// </summary> /// <param name="req"><see cref="InvokeRequest"/></param> /// <returns><see cref="InvokeResponse"/></returns> public InvokeResponse InvokeSync(InvokeRequest req) { JsonResponseModel <InvokeResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "Invoke"); rsp = JsonConvert.DeserializeObject <JsonResponseModel <InvokeResponse> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return(rsp.Response); }
public async Task <State> InvokeLambda(State state, ILambdaContext context) { var client = new AmazonLambdaClient(RegionEndpoint.APSoutheast2); var invokeRequest = new InvokeRequest { FunctionName = state.FunctionName }; var response = await client.InvokeAsync(invokeRequest); state.Index += state.Step; state.Continue = state.Index < state.Count; return(state); }
/// <inheritdoc/> public override Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context) { return(request.Method switch { "Notify" => ProxyGrpc <NotificationRequest, Response>(request, context, _notificationService.Notify), _ => Task.FromResult(new InvokeResponse { Data = AnyConverter.ToAny(new Response { Status = Response.Types.Status.Failure, Message = $"Unexpected service method: {request.Method}" }, Config.jsonSerializerOptions) }) });
public InvokeResponse SendToHub(string assetMessage) { using (var client = new AmazonLambdaClient( new BasicAWSCredentials(env.HUB_AWS_ACCESSKEY, env.HUB_AWS_SECRETACCESSKEY), RegionEndpoint.GetBySystemName(env.HUB_AWS_REGION))) { var request = new InvokeRequest { FunctionName = env.HUB_LAMBDA_FUNCTION, Payload = assetMessage }; return(client.InvokeAsync(request).Result); } }
public async Task Handler(S3Event @event, ILambdaContext context) { if (@event == null || @event.Records == null) { return; } foreach (var record in @event.Records) { try { var awsS3Bucket = record.S3.Bucket.Name; var awsS3Key = record.S3.Object.Key; if (!Regex.IsMatch(awsS3Key, "^TranscriptionJob-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.json$")) { throw new Exception("S3 key '" + awsS3Key + "' is not an expected file name for transcribe output"); } var transcribeJobUuid = awsS3Key.Substring(awsS3Key.IndexOf("-") + 1, awsS3Key.LastIndexOf(".") - awsS3Key.IndexOf("-") - 1); var jobAssignmentId = StageVariables.PublicUrl + "/job-assignments/" + transcribeJobUuid; var invokeParams = new InvokeRequest { FunctionName = StageVariables.WorkerLambdaFunctionName, InvocationType = "Event", LogType = "None", Payload = new { action = "ProcessTranscribeJobResult", stageVariables = StageVariables.ToDictionary(), jobAssignmentId, outputFile = new S3Locator { AwsS3Bucket = awsS3Bucket, AwsS3Key = awsS3Key } }.ToMcmaJson().ToString() }; var lambda = new AmazonLambdaClient(); await lambda.InvokeAsync(invokeParams); } catch (Exception error) { Logger.Error($"Failed processing record.\r\nRecord:\r\n{record.ToMcmaJson()}\r\nError:\r\n{error}"); } } }
/// <summary> /// Calls a remote method via gRPC commadable protocol. /// </summary> /// <typeparam name="T">the class type</typeparam> /// <param name="name">a name of the command to call.</param> /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param> /// <param name="requestEntity">body object.</param> /// <returns>result of the command.</returns> public async Task <T> CallCommandAsync <T>(string name, string correlationId, object requestEntity) where T : class { var method = _name + '.' + name; var request = new InvokeRequest { Method = method, CorrelationId = correlationId, ArgsEmpty = requestEntity == null, ArgsJson = requestEntity == null ? null : JsonConverter.ToJson(requestEntity) }; InvokeReply response; var timing = Instrument(correlationId, method); try { response = await CallAsync <InvokeRequest, InvokeReply>("invoke", request); } catch (Exception ex) { InstrumentError(correlationId, method, ex); throw ex; } finally { timing.EndTiming(); } // Handle error response if (response.Error != null) { var errorDescription = ObjectMapper.MapTo <Commons.Errors.ErrorDescription>(response.Error); throw ApplicationExceptionFactory.Create(errorDescription); } // Handle empty response if (response.ResultEmpty || response.ResultJson == null) { return(null); } // Handle regular response var result = JsonConverter.FromJson <T>(response.ResultJson); return(result); }
/* * 継承先のHandlerのreturn直前で * Task.WaitAll(PostProcess(m_data, context)); * とすること。 * * @todo エラーハンドリング * https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/API_Invoke.html */ protected async Task PostProcess(T_ARG data, ILambdaContext ctx) { // 環境変数から、呼び出すLambda名をFIX var env = System.Environment.GetEnvironmentVariable("LAMBDA_ENV"); var service = System.Environment.GetEnvironmentVariable("LAMBDA_SERVICE"); if ((data.postLambda == "") || (env == null) || (service == null)) { return; } var funcName = service + "-" + env + "-" + data.postLambda; ctx.Log("PostProcess Lambda : " + funcName); // base64endoed json を decode して jsonとして引数にセット var payload = new PostLambdaArg() { role = "server", mode = data.postLambdaMode, dataBody = data.postLambdaArg }; using (var client = new AmazonLambdaClient(Amazon.RegionEndpoint.APNortheast1)) { // base64endoed => json をそのままバイパス if (data.isWaitPostProcess) { var request = new InvokeRequest() { FunctionName = funcName, InvocationType = InvocationType.RequestResponse, Payload = JsonSerializer.ToJsonString(payload) }; var response = await client.InvokeAsync(request); } else { var request = new InvokeRequest() { FunctionName = funcName, InvocationType = InvocationType.Event, Payload = JsonSerializer.ToJsonString(payload) }; var response = await client.InvokeAsync(request); } } }
public static async Task AddJobAssignmentAsync(ApiGatewayRequest request, McmaApiResponse response) { Logger.Debug(nameof(AddJobAssignmentAsync)); Logger.Debug(request.ToMcmaJson().ToString()); var jobAssignment = request.JsonBody?.ToMcmaObject <JobAssignment>(); if (jobAssignment == null) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.StatusMessage = "Missing request body."; return; } var jobAssignmentId = request.StageVariables["PublicUrl"] + "/job-assignments/" + Guid.NewGuid(); jobAssignment.Id = jobAssignmentId; jobAssignment.Status = "NEW"; jobAssignment.DateCreated = DateTime.UtcNow; jobAssignment.DateModified = jobAssignment.DateCreated; var table = new DynamoDbTable(request.StageVariables["TableName"]); await table.PutAsync <JobAssignment>(jobAssignmentId, jobAssignment); response.StatusCode = (int)HttpStatusCode.Created; response.Headers["Location"] = jobAssignment.Id; response.JsonBody = jobAssignment.ToMcmaJson(); Logger.Debug(response.ToMcmaJson().ToString()); // invoking worker lambda function that will create a jobAssignment assignment for this new jobAssignment var lambdaClient = new AmazonLambdaClient(); var invokeRequest = new InvokeRequest { FunctionName = request.StageVariables["WorkerLambdaFunctionName"], InvocationType = "Event", LogType = "None", Payload = new { action = "ProcessJobAssignment", stageVariables = request.StageVariables, jobAssignmentId = jobAssignmentId }.ToMcmaJson().ToString() }; await lambdaClient.InvokeAsync(invokeRequest); }
private TaskCompletionSource <T> CreateInvokeTaskSrc <T>(MethodInfo targetMethod, object[] args) { var taskCompletionSrc = new TaskCompletionSource <T>(); var request = new InvokeRequest { MethodName = targetMethod.Name, Arguments = args }; request.Id = Guid.NewGuid().GetHashCode(); SendRequestAsync(taskCompletionSrc, request); return(taskCompletionSrc); }
/// <summary> /// Method that creates an object of <c>InvokeRequest</c> (request) to be sent to database and return filtered data. /// data is fetched from form (dropdown lists and input textbox) if not null. /// </summary> /// <param name="invokeRequest">Object of Model <c>InvokeRequest</c></param> /// <returns>redirection to the same page but with filtered data using a request object.</returns> public IActionResult Filter(InvokeRequest invokeRequest) { InvokeRequest request = new InvokeRequest { }; if (invokeRequest.StatusId != null && invokeRequest.StatusId != "Välj alla") { request.StatusId = invokeRequest.StatusId; } if (!string.IsNullOrWhiteSpace(invokeRequest.RefNumber)) { request.RefNumber = invokeRequest.RefNumber; } return(RedirectToAction("StartInvestigator", request)); }
public override Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context) { switch (request.Method) { case "SayHello": { return(Task.FromResult(new InvokeResponse() { ContentType = "text/plain; charset=UTF-8", Data = Any.Parser.ParseFrom(ByteString.CopyFromUtf8("Hello, world!")) })); } default: return(base.OnInvoke(request, context)); } }
private void CreateNotification(InvokeRequest request) { string title = request.Parameters["title"].Value <string>(); string message = request.Parameters["message"].Value <string>(); int notificationID = _notificationID++; CrossLocalNotifications.Current.Show(title, message, notificationID); request.UpdateTable(new Table { new Row { notificationID } }); request.Close(); }
public async Task <string> InsertEmailAsync(InsertEmailModel insertEmailModelModel) { insertEmailModelModel.From = _emailClientConfig.FromMailAddress; var lambdaRequest = new InvokeRequest { FunctionName = _insertEmailLambdaName, Payload = JsonConvert.SerializeObject(insertEmailModelModel) }; var invokeResult = await _lambdaClient.Value.InvokeAsync(lambdaRequest); CheckLambdaResult(invokeResult); return(invokeResult.Payload.Deserialize <string>()); }
static CallbackResult InvokeMethod(InvokeRequest request, IReferenceMap referenceMap) { request = request ?? throw new ArgumentNullException(nameof(request)); DeputyBase deputy = referenceMap.GetOrCreateNativeReference(request.ObjectReference); MethodInfo methodInfo = ReflectionUtils.GetNativeMethod(deputy.GetType(), request.Method); if (methodInfo == null) { throw new InvalidOperationException($"Received callback for {deputy.GetType().Name}.{request.Method} getter, but this method does not exist"); } JsiiMethodAttribute attribute = methodInfo.GetCustomAttribute <JsiiMethodAttribute>(); return(new CallbackResult(attribute?.Returns, methodInfo.Invoke(deputy, request.Arguments))); }
private static void InvokeLambda(Message message) { AmazonLambdaClient client = new AmazonLambdaClient(); string serializedMessage = JsonConvert.SerializeObject(message); SQSEvent.MessageAttribute typeAttribute = new SQSEvent.MessageAttribute { DataType = "String", StringValue = message.GetType().Name }; SQSEvent.SQSMessage fakeSqsMessage = new SQSEvent.SQSMessage { Body = serializedMessage, Attributes = new Dictionary <string, string> { { "SentTimestamp", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString() } }, MessageAttributes = new Dictionary <string, SQSEvent.MessageAttribute> { { "Type", typeAttribute } } }; SQSEvent fakeSqsEvent = new SQSEvent { Records = new List <SQSEvent.SQSMessage> { fakeSqsMessage } }; string serializedFakeSqsEvent = JsonConvert.SerializeObject(fakeSqsEvent, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); InvokeRequest invokeRequest = new InvokeRequest { FunctionName = FunctionName, Payload = serializedFakeSqsEvent }; InvokeResponse response = client.InvokeAsync(invokeRequest).GetAwaiter().GetResult(); string responseString = Encoding.UTF8.GetString(response.Payload.GetBuffer()); Console.WriteLine(responseString); }
static void Main(string[] args) { AmazonLambdaClient client = new AmazonLambdaClient("Your Client ID", "Your Client Secert", RegionEndpoint.USWest2); InvokeRequest request = new InvokeRequest() { FunctionName = "Udemy", Payload = "\"test\"" }; InvokeResponse response = client.Invoke(request); if (response != null && response.StatusCode == 200) { var sr = new StreamReader(response.Payload); string result = sr.ReadToEnd(); Console.WriteLine($"Results: {result}"); } Console.ReadLine(); }
// calls our game service Lambda function to get connection info for the Realtime server private void ConnectToGameLiftServer() { Debug.Log("Reaching out to client service Lambda function"); AWSConfigs.AWSRegion = "us-east-1"; // Your region here AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; // paste this in from the Amazon Cognito Identity Pool console CognitoAWSCredentials credentials = new CognitoAWSCredentials( "us-east-1:a00a0aa0-a000-0000-0aa0-0aa00a0009a0", // Your identity pool ID here RegionEndpoint.USEast1 // Your region here ); AmazonLambdaClient client = new AmazonLambdaClient(credentials, RegionEndpoint.USEast1); InvokeRequest request = new InvokeRequest { FunctionName = "ConnectClientToServer", InvocationType = InvocationType.RequestResponse }; client.InvokeAsync(request, (response) => { if (response.Exception == null) { if (response.Response.StatusCode == 200) { var payload = Encoding.ASCII.GetString(response.Response.Payload.ToArray()) + "\n"; var playerSessionObj = JsonUtility.FromJson <PlayerSessionObject>(payload); if (playerSessionObj.FleetId == null) { Debug.Log($"Error in Lambda: {payload}"); } else { QForMainThread(ActionConnectToServer, playerSessionObj.IpAddress, Int32.Parse(playerSessionObj.Port), playerSessionObj.PlayerSessionId); } } } else { Debug.LogError(response.Exception); } }); }
public async void SetParkState(InvokeRequest request) { JToken stateToken = request.Parameters["state"]; if (stateToken.Type == JTokenType.Boolean) { if (stateToken.Value <bool>()) { _robot.DeployKickstands(); } else { _robot.RetractKickstands(); } } await request.Close(); }
public async Task InvokeMethodAsync_WithNoReturnTypeAndData_UsesConfiguredJsonSerializerOptions() { var httpClient = new TestHttpClient(); var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var invokeClient = new InvokeHttpClient(httpClient, jsonOptions); var invokeRequest = new InvokeRequest() { RequestParameter = "Hello" }; var task = invokeClient.InvokeMethodAsync <InvokeRequest, InvokedResponse>("test", "test", invokeRequest); httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); (await entry.Request.Content.ReadAsStringAsync()).Should().Be(JsonSerializer.Serialize(invokeRequest, jsonOptions)); }
public async Task TestPowerShellLambdaParallelTestCommand() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestPowerShellParallelTest"); var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.S3Bucket = this._testFixture.Bucket; command.S3Prefix = "TestPowerShellParallelTest/"; command.Region = "us-east-1"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "{}" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var logTail = Encoding.UTF8.GetString(Convert.FromBase64String(response.LogResult)); Assert.Equal(200, response.StatusCode); Assert.Contains("Running against: 1 for SharedVariable: Hello Shared Variable", logTail); Assert.Contains("Running against: 10 for SharedVariable: Hello Shared Variable", logTail); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } }
private async void PickPicture(InvokeRequest request) { var result = await CrossMedia.Current.PickPhotoAsync(); if (result == null) { await request.UpdateTable(new Table { new JArray { result.GetStream().ReadAllBytes() } }); } await request.Close(); }
public async Task FunctionHandler() { var connection = DbHelper.Connection; var sqsClient = new AmazonSQSClient(); var sqsResponse = await sqsClient.ReceiveMessageAsync(QueueHelper.RequestQueueUrl); var lambdaClient = new AmazonLambdaClient(); foreach (var message in sqsResponse.Messages) { var body = message.Body; var handler = message.ReceiptHandle; var queueRequest = JsonConvert.DeserializeObject <QueueRequest>(body); var invokeRequest = new InvokeRequest() { FunctionName = Enum.GetName(typeof(Service), queueRequest.TargetService), Payload = JsonConvert.SerializeObject(queueRequest) }; var lambdaResponse = await lambdaClient.InvokeAsync(invokeRequest); var response = new StreamReader(lambdaResponse.Payload).ReadToEnd(); if (!string.IsNullOrEmpty(queueRequest.CallbackUrl)) { var httpClient = new HttpClient(); await httpClient.PostAsync( queueRequest.CallbackUrl, new StringContent(response) ); } await sqsClient.DeleteMessageAsync(QueueHelper.RequestQueueUrl, handler); var processed = await sqsClient.SendMessageAsync( QueueHelper.ProcessedQueueUrl, response ); connection.Execute($"UPDATE {DbHelper.GetTableName<QueueProcess>()} SET ProcessId = @PId WHERE QueueId = @QId", new { PId = processed.MessageId, QId = message.MessageId }); } }
public async Task <HypeConstants> GetHypeConstants(IEnumerable <MasterGameYear> allMasterGameYears) { string fileName = "LiveData.csv"; File.Delete(fileName); CreateCSVFile(allMasterGameYears, fileName); await UploadMasterGameYearStats(fileName); var requestParams = new { bucket = _bucket, key = "HypeFactor/LiveData.csv" }; var jsonRequest = JsonConvert.SerializeObject(requestParams); AmazonLambdaClient lambdaClient = new AmazonLambdaClient(); InvokeRequest request = new InvokeRequest() { FunctionName = "getHypeFactor", InvocationType = InvocationType.RequestResponse, Payload = jsonRequest }; InvokeResponse response = await lambdaClient.InvokeAsync(request); if (response.HttpStatusCode != HttpStatusCode.OK || !string.IsNullOrWhiteSpace(response.FunctionError)) { _logger.Error(response.HttpStatusCode); _logger.Error(response.FunctionError); _logger.Error(response.LogResult); throw new Exception("Lambda function failed."); } var stringReader = new StreamReader(response.Payload); var responseString = stringReader.ReadToEnd().Trim('"').Replace("\\", ""); var entity = JsonConvert.DeserializeObject <HypeConstantsEntity>(responseString); if (entity is null) { throw new Exception("Invalid hype constants."); } return(entity.ToDomain()); }
public void ConnectToGameLiftServer() { Debug.Log("Reaching out to client service Lambda function"); AWSConfigs.AWSRegion = "EUCentral1"; AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest; // paste this in from the Amazon Cognito Identity Pool console CognitoAWSCredentials credentials = new CognitoAWSCredentials( // die der GameLift-Instanz ist arn:aws:gamelift:eu-central-1:289499586032:fleet/fleet-2f620a33-1536-4732-afb9-a1d1fe7f390e "eu-central-1:60219201-5b2b-4a81-a80b-8ddaf311d0be", RegionEndpoint.EUCentral1); // Region is EUCentral1 AmazonLambdaClient client = new AmazonLambdaClient(credentials, RegionEndpoint.EUCentral1); InvokeRequest request = new InvokeRequest { //FunctionName = "InvokeAsync",//name of lambda function //Dem Lambda-Skript muss mittels Query-String das Spiel mitgeteilt werden ("game" = "SSPS" oder "M3") FunctionName = "matchmaker", InvocationType = InvocationType.RequestResponse, Payload = "{\"queryStringParameters\":{\"game\":\"M3\"}}" }; //create gameLift session client.InvokeAsync(request, (response) => { if (response.Exception == null) { if (response.Response.StatusCode == 200) { var payload = Encoding.ASCII.GetString(response.Response.Payload.ToArray()) + "\n"; var playerSessionObj = JsonUtility.FromJson <PlayerSessionObject>(payload); if (playerSessionObj.FleetId == null) { Debug.Log($"Error in Lambda: {payload}"); } else { //connect JoinMatch(playerSessionObj.IpAddress, playerSessionObj.Port, playerSessionObj.PlayerSessionId); } } } }); }
public async Task RunDeployCommandWithCustomConfigAndProjectLocation() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location)); var command = new DeployFunctionCommand(new ConsoleToolLogger(), fullPath, new string[] { "--config-file", "custom-config.json", "--project-location", "../../../../../testapps/TestFunction" }); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "TestFunction::TestFunction.Function::ToUpper"; command.Timeout = 10; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.Runtime = "dotnetcore2.1"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal("\"HELLO WORLD\"", payload); var log = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(response.LogResult)); Assert.Contains("Memory Size: 320 MB", log); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } }
public async Task Can_invoke_simple_lambda_function() { var invokeRequest = new InvokeRequest { InvocationType = InvocationType.RequestResponse, Payload = "\"string\"", FunctionName = "ReverseStringFunction", }; var invokeResponse = await _lambdaClient.InvokeAsync(invokeRequest); invokeResponse.StatusCode.ShouldBe(200); invokeResponse.Payload.Length.ShouldBeGreaterThan(0); var streamReader = new StreamReader(invokeResponse.Payload); var payload = await streamReader.ReadToEndAsync(); payload.ShouldBe("\"gnirts\""); }
public override async Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context) { var response = new InvokeResponse(); switch (request.Method) { case "sayhello": var input = request.Data.Unpack <HelloRequest>(); var output = await SayHello(input, context); response.Data = Any.Pack(output); break; default: break; } return(response); }
public async Task <InvokeResponse> Invoke(Method method) { var invokeRequest = new InvokeRequest { i = method.Object.Id.ToString(), v = method.Object.Version.ToString(), m = method.Name, }; var uri = new Uri("Database/Invoke", UriKind.Relative); var response = await this.Client.PostAsJsonAsync(uri, invokeRequest); response.EnsureSuccessStatusCode(); var invokeResponse = await response.Content.ReadAsAsync <InvokeResponse>(); return(invokeResponse); }