示例#1
0
        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 void BodyDoesntHideBase()
        {
            var sut = new InvokeResponse <SomeType>
            {
                Status = 200,
                Body   = new SomeType
                {
                    Id    = "200",
                    Value = "blah"
                }
            };

            // Assert that the Body property is not hidden when using InvokeResponse or InvokeResponse<T>.
            var sutAsInvokeResponse = (InvokeResponse)sut;

            Assert.NotNull(sutAsInvokeResponse.Body);
            Assert.Same(sut.Body, sutAsInvokeResponse.Body);
            Assert.Equal(sut.Body.Id, ((SomeType)sutAsInvokeResponse.Body).Id);
            Assert.Equal(sut.Body.Value, ((SomeType)sutAsInvokeResponse.Body).Value);
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            InvokeResponse response = new InvokeResponse();

            var ms = new MemoryStream();

            Amazon.Util.AWSSDKUtils.CopyStream(context.Stream, ms);
            ms.Seek(0, SeekOrigin.Begin);
            response.Payload = ms;
            if (context.ResponseData.IsHeaderPresent("X-Amz-Function-Error"))
            {
                response.FunctionError = context.ResponseData.GetHeaderValue("X-Amz-Function-Error");
            }
            if (context.ResponseData.IsHeaderPresent("X-Amz-Log-Result"))
            {
                response.LogResult = context.ResponseData.GetHeaderValue("X-Amz-Log-Result");
            }
            response.StatusCode = (int)context.ResponseData.StatusCode;

            return(response);
        }
        public override async Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context)
        {
            var response = new InvokeResponse();

            switch (request.Method)
            {
            case "createuser":
                var user = JsonSerializer.Deserialize <User>(System.Text.Encoding.UTF8.GetString(request.Data.Value.Memory.ToArray()));
                await CreateUserAsync(user);

                break;

            case "sendmessage":
                var message = JsonSerializer.Deserialize <Message>(System.Text.Encoding.UTF8.GetString(request.Data.Value.Memory.ToArray()));
                await SendMessageAsync(message);

                break;
            }

            return(await Task.FromResult(response));
        }
        public async Task <string> HandleIncomingCall(TwilioIncomingCall twilioCallDetails, ILambdaContext context)
        {
            string stage  = System.Environment.GetEnvironmentVariable("STAGE");
            string region = System.Environment.GetEnvironmentVariable("AWS_REGION");

            string functionName = $"telephonist-csharp-{stage}-GetDetailsForCurrentOnCallOperator";

            LambdaLogger.Log($"REQUEST: {twilioCallDetails}");

            LambdaLogger.Log($"PARAM: stage={stage}");
            LambdaLogger.Log($"PARAM: region={region}");

            LambdaLogger.Log($"functionName: {functionName}");

            using (AmazonLambdaClient client = new AmazonLambdaClient(RegionEndpoint.GetBySystemName(region)))
            {
                InvokeRequest request = new InvokeRequest()
                {
                    FunctionName = functionName
                };
                InvokeResponse response = await client.InvokeAsync(request);

                using (StreamReader reader = new StreamReader(response.Payload))
                {
                    string result = reader.ReadToEnd();

                    LambdaLogger.Log($"Lambda result: {result}");

                    OnCallOperatorDetails engineer = WebHelpers.ParseJSON <OnCallOperatorDetails>(result);

                    string justName = engineer.Name.Split(' ')[0];

                    TimeZoneInfo localTimeZone   = WebHelpers.OlsonTimeZoneToTimeZoneInfo(engineer.TimeZone);
                    DateTime     localTime       = TimeZoneInfo.ConvertTime(DateTime.Now, localTimeZone);
                    string       localTimeString = localTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);

                    return(String.Format(CultureInfo.InvariantCulture, ResponseTwiML, justName, localTimeString, engineer.PhoneNumber));
                }
            }
        }
示例#6
0
        public async Task OnTurnAsync(ITurnContext turnCtx, CancellationToken cancellationToken)
        {
            try
            {
                if (turnCtx.Activity != null && turnCtx.Activity.Type != null && turnCtx.Activity.Type == ActivityTypes.Invoke)
                {
                    ITeamsContext teamsContext = turnCtx.TurnState.Get <ITeamsContext>();

                    MessagingExtensionQuery meQuery = null;
                    if (teamsContext.IsRequestMessagingExtensionQuery())
                    {
                        meQuery = teamsContext.GetMessagingExtensionQueryData();
                    }

                    InvokeResponse ir = new InvokeResponse
                    {
                        Body = new MessagingExtensionResponse
                        {
                            ComposeExtension = await searchHandler.GetSearchResultAsync(meQuery.Parameters[0].Value.ToString())
                        },
                        Status = 200,
                    };

                    await turnCtx.SendActivityAsync(
                        new Activity
                    {
                        Value = ir,
                        Type  = ActivityTypesEx.InvokeResponse,
                    }).ConfigureAwait(false);
                }
                else
                {
                    await turnCtx.SendActivityAsync(string.Format("Sorry! As of now I'm only support an invoke command, but you're trying to execute {0}", (turnCtx.Activity != null && turnCtx.Activity.Type != null) ? turnCtx.Activity.Type.ToString() : "empty activity"));
                }
            }
            catch (Exception ex)
            {
                await turnCtx.SendActivityAsync($"Oppps, seems like an error: {ex.InnerException}. Try again or contact your IT admin");
            }
        }
        public async Task InvokeMethodGrpcAsync_CanInvokeMethodWithNoReturnTypeAndData_ThrowsErrorNonSuccess()
        {
            var client = new MockClient();
            var data   = new Response()
            {
                Name = "Look, I was invoked!"
            };
            var invokeResponse = new InvokeResponse
            {
                Data = Any.Pack(data),
            };

            var response =
                client.Call <InvokeResponse>()
                .SetResponse(invokeResponse)
                .Build();


            const string     rpcExceptionMessage = "RPC exception";
            const StatusCode rpcStatusCode       = StatusCode.Unavailable;
            const string     rpcStatusDetail     = "Non success";

            var rpcStatus    = new Status(rpcStatusCode, rpcStatusDetail);
            var rpcException = new RpcException(rpcStatus, new Metadata(), rpcExceptionMessage);

            // Setup the mock client to throw an Rpc Exception with the expected details info
            client.Mock
            .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>()))
            .Throws(rpcException);

            var ex = await Assert.ThrowsAsync <InvocationException>(async() =>
            {
                await client.DaprClient.InvokeMethodGrpcAsync <Request>("test", "test", new Request()
                {
                    RequestParameter = "Hello "
                });
            });

            Assert.Same(rpcException, ex.InnerException);
        }
        public void record_with_one_pdf_resource_test()
        {
            var record = new Record().With(r =>
            {
                r.Id        = Helpers.AddCollection("0545c14b-e7fd-472d-8575-5bb75034945f");
                r.Gemini    = Library.Example();
                r.Resources = new List <Resource>
                {
                    new Resource
                    {
                        Name         = "A pdf resource",
                        Path         = "C:\\work\\test.pdf",
                        PublishedUrl = "http://data.jncc.gov.uk/data/0545c14b-e7fd-472d-8575-5bb75034945f/test.pdf"
                    }
                };
            });

            var lambdaClientMock = new Mock <ILambdaClient>();
            var s3ClientMock     = new Mock <IS3Client>();
            var fileHelperMock   = new Mock <IFileHelper>();
            var hubService       = new HubService(env, lambdaClientMock.Object, s3ClientMock.Object, fileHelperMock.Object);

            fileHelperMock.Setup(x => x.IsPdfFile(It.IsAny <string>())).Returns(true);
            fileHelperMock.Setup(x => x.GetFileSizeInBytes(It.IsAny <string>())).Returns(100);
            fileHelperMock.Setup(x => x.GetBase64String(It.IsAny <string>())).Returns("base 64 string");
            fileHelperMock.Setup(x => x.GetFileExtensionWithoutDot(It.IsAny <string>())).Returns("pdf");
            var s3Response = new PutObjectResponse();

            s3Response.HttpStatusCode = HttpStatusCode.OK;
            s3ClientMock.Setup(x => x.SaveToS3(It.IsAny <string>(), It.IsAny <string>())).Returns(s3Response);
            var lambdaResponse = new InvokeResponse();

            lambdaResponse.StatusCode = 200;
            lambdaClientMock.Setup(x => x.SendToHub(It.IsAny <string>())).Returns(lambdaResponse);

            hubService.Publish(record);

            s3ClientMock.Verify(x => x.SaveToS3(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            lambdaClientMock.Verify(x => x.SendToHub(It.IsAny <string>()), Times.Once);
        }
示例#9
0
        public string PostData(LambdaResourceType lambdaResourceType, string postData)
        {
            postData = @"{
              ""resource"": ""/" + (lambdaResourceType == LambdaResourceType.listings ? "listings" : "areas") + @""",
              ""body"": " + postData + @"
            }";

            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "rasterizer",
                InvocationType = InvocationType.RequestResponse,
                Payload        = postData
            };

            InvokeResponse response = this.lambdaClient.InvokeAsync(ir).Result;

            string sr = new StreamReader(response.Payload).ReadToEnd();

            return(sr.Substring(sr.IndexOf("\"") + 1).Substring(0, sr.LastIndexOf("\"") - 1).Replace("\\", ""));


            //WebRequest request = WebRequest.Create(url);
            //request.Method = "POST";
            //byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = byteArray.Length;
            //Stream dataStream = request.GetRequestStream();
            //dataStream.Write(byteArray, 0, byteArray.Length);
            //dataStream.Close();
            //WebResponse response = request.GetResponse();
            //dataStream = response.GetResponseStream();
            //StreamReader reader = new StreamReader(dataStream);
            //string responseFromServer = reader.ReadToEnd();
            //reader.Close();
            //dataStream.Close();
            //response.Close();

            //return responseFromServer;
        }
示例#10
0
        public override Task <InvokeResponse> InvokeService(InvokeServiceRequest request, ServerCallContext context)
        {
            switch (request.Message.Method)
            {
            case "SayHello":

                Console.WriteLine("Inside DaprImpl! InvokeService");
                var response = new InvokeResponse()
                {
                    Data = new Any()
                    {
                        Value = ByteString.CopyFrom(
                            Encoding.UTF8.GetBytes($"Hello from {request.Message?.Data?.Value?.ToStringUtf8()}"))
                    }
                };

                return(Task.FromResult(response));

            default:
                throw new Exception($"Unknown method invocation {request.Message.Method}");
            }
        }
示例#11
0
        public async Task <InvokeResponse> ServiceInvokeMethod(InvokeRequest parameters)
        {
            InvokeResponse res = null;

            try
            {
                res = await InvokeMethod(parameters);
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }
                res = new InvokeResponse {
                    result = null,
                    error  = new ErrorInfo(ex.GetFullMessage(), ex.GetType().Name)
                };
                _OnError(ex);
            }
            return(res);
        }
示例#12
0
        public void testGetResultForInvoke()
        {
            XooaClient xooaClient = new XooaClient();

            xooaClient.setApiToken(XooaConstants.API_TOKEN);

            string resultId = "63dc6290-053d-4469-8461-dcdf705d0943";

            try {
                InvokeResponse invokeResponse = xooaClient.getResultForInvoke(resultId);

                Assert.IsNotEmpty(invokeResponse.getPayload());

                Assert.IsNotEmpty(invokeResponse.getTxnId());
            } catch (XooaRequestTimeoutException xrte) {
                Assert.IsNotEmpty(xrte.getResultUrl());

                Assert.IsNotEmpty(xrte.getResultId());

                Assert.AreEqual(resultId, xrte.getResultId());
            }
        }
示例#13
0
        static void Main(string[] args)
        {
            AmazonLambdaClient client = new AmazonLambdaClient("key", "key", RegionEndpoint.USWest1);

            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "MyHelloWorld",
                InvocationType = InvocationType.RequestResponse,
                Payload        = "\"Ramesh\""
            };

            InvokeResponse response = client.Invoke(ir);

            var        sr     = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(sr);

            var serilizer = new JsonSerializer();
            var op        = serilizer.Deserialize(reader);

            Console.WriteLine(op);
            Console.ReadLine();
        }
示例#14
0
        // GET: Register
        public ActionResult Register()
        {
            AmazonLambdaClient client = new AmazonLambdaClient("", "", RegionEndpoint.USEast1);


            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "RandomNumber",
                InvocationType = InvocationType.RequestResponse
            };

            InvokeResponse response = client.Invoke(ir);

            var        sr     = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(sr);

            var serilizer = new JsonSerializer();
            var op        = serilizer.Deserialize(reader);

            ViewData["number"] = op;
            return(View());
        }
示例#15
0
        public void testInvoke()
        {
            string functionName = "set";

            string[] args = { "args1", "9000" };

            XooaClient xooaClient = new XooaClient();

            xooaClient.setApiToken(XooaConstants.API_TOKEN);

            try {
                InvokeResponse invokeResponse = xooaClient.invoke(functionName, args);

                Assert.IsNotEmpty(invokeResponse.getTxnId());

                Assert.IsNotEmpty(invokeResponse.getPayload());
            } catch (XooaRequestTimeoutException xrte) {
                Assert.IsNotEmpty(xrte.getResultId());

                Assert.IsNotEmpty(xrte.getResultUrl());
            }
        }
示例#16
0
文件: DeputyBase.cs 项目: yanex/jsii
        static T InvokeMethodCore <T>(
            JsiiMethodAttribute methodAttribute,
            object[] arguments,
            Func <IClient, object[], BeginResponse> beginFunc,
            Func <IClient, object[], InvokeResponse> invokeFunc
            )
        {
            IServiceProvider          serviceProvider = ServiceContainer.ServiceProvider;
            IClient                   client          = serviceProvider.GetRequiredService <IClient>();
            IJsiiToFrameworkConverter converter       = serviceProvider.GetRequiredService <IJsiiToFrameworkConverter>();
            IReferenceMap             referenceMap    = serviceProvider.GetRequiredService <IReferenceMap>();

            object result = GetResult();

            if (!converter.TryConvert(methodAttribute.Returns, typeof(T), referenceMap, result, out object frameworkValue))
            {
                throw new ArgumentException($"Could not convert result '{result}' for method '{methodAttribute.Name}'", nameof(result));
            }

            return((T)frameworkValue);

            object GetResult()
            {
                object[] args = ConvertArguments(methodAttribute.Parameters, arguments);

                if (methodAttribute.IsAsync)
                {
                    BeginResponse beginResponse = beginFunc(client, args);

                    InvokeCallbacks();

                    return(client.End(beginResponse.PromiseId).Result);
                }

                InvokeResponse invokeResponse = invokeFunc(client, args);

                return(invokeResponse.Result);
            }
        }
示例#17
0
        public async Task InvokeMethodAsync_CanInvokeMethodWithResponse_CalleeSideHttp()
        {
            var client = new MockClient();
            var data   = new Response()
            {
                Name = "Look, I was invoked!"
            };
            var invokeResponse = new InvokeResponse
            {
                Data = TypeConverters.ToAny(data)
            };

            var response =
                client.Call <InvokeResponse>()
                .SetResponse(invokeResponse)
                .AddHeader("dapr-http-status", "200")
                .Build();


            client.Mock
            .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>()))
            .Returns(response);

            var body = new Request()
            {
                RequestParameter = "Hello "
            };
            var task = client.DaprClient.InvokeMethodWithResponseAsync <Request, Response>("test", "testMethod", body);

            // Validate Response
            var invokedResponse = await task;

            invokedResponse.Body.Name.Should().Be("Look, I was invoked!");
            invokedResponse.Headers.ContainsKey("dapr-http-status").Should().BeTrue();
            invokedResponse.ContentType.Should().Be(Constants.ContentTypeApplicationJson);
            invokedResponse.GrpcStatusInfo.Should().BeNull();
            invokedResponse.HttpStatusCode.Should().NotBeNull();
            invokedResponse.HttpStatusCode.Should().Be(HttpStatusCode.OK);
        }
示例#18
0
        public async Task <InvokeResponse> HandleAppBasedLinkQueryAsync(
            ITurnContext <IInvokeActivity> turnContext,
            AppBasedLinkQuery query,
            CancellationToken cancellationToken)
        {
            var url = query?.Url?.Trim() ?? string.Empty;

            var result = new InvokeResponse {
                Status = (int)HttpStatusCode.OK
            };

            if (url.Contains("OpenPositionsPersonalTab"))
            {
                var positionIdParam = HttpUtility.ParseQueryString(new Uri(url).Query).Get("positionId");
                if (int.TryParse(positionIdParam, out var positionId))
                {
                    result = await PositionMessagingExtensionResponse(turnContext, positionId);
                }
            }

            return(result);
        }
示例#19
0
        private async Task <string> Recognize(IFormFile file)
        {
            var lambdaRequest = new OcrLambdaRequest(this.ConvertImageToBase64(file));

            var payload = JsonConvert.SerializeObject(lambdaRequest, new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                }
            });

            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "x1",
                InvocationType = InvocationType.RequestResponse,
                Payload        = payload
            };

            InvokeResponse response = await this.awsLambdaClient.InvokeAsync(ir);

            using (var sr = new StreamReader(response.Payload))
            {
                JsonReader reader    = new JsonTextReader(sr);
                var        serilizer = new JsonSerializer();
                var        op        = serilizer.Deserialize(reader);
                var        text      = op as string;
                //TODO add proper error handling
                if (text != null)
                {
                    return(text);
                }
                else
                {
                    throw new Exception("Something went wrong!");
                }
            }
        }
示例#20
0
            public override Task <InvokeResponse <T> > PostActivityAsync <T>(string fromBotId, string toBotId, Uri toUrl, Uri serviceUrl, string conversationId, Activity activity, CancellationToken cancellationToken = default)
            {
                var responseActivity = activity;

                if (activity.Text.Contains("skill"))
                {
                    responseActivity = new Activity()
                    {
                        Type = "message",
                        Text = "This is the skill talking: hello"
                    };
                }

                if (activity.Text.Contains("end"))
                {
                    responseActivity = new Activity()
                    {
                        Type = "endOfConversation"
                    };
                }

                var response = new InvokeResponse <ExpectedReplies>()
                {
                    Status = 200,
                    Body   = new ExpectedReplies
                    {
                        Activities = new List <Activity>()
                        {
                            responseActivity
                        }
                    }
                };

                var casted = (InvokeResponse <T>)Convert.ChangeType(response, typeof(InvokeResponse <T>), new System.Globalization.CultureInfo("en-US"));
                var result = Task.FromResult(casted);

                return(result);
            }
示例#21
0
        public void invoke()
        {
            AmazonLambdaClient client = new AmazonLambdaClient("AKIAJHTR2OYL3LKMA7TA", "FugS3+bephKimPa9orSL7Ox2+mv1RreS4IFPK0oJ"
                                                               , RegionEndpoint.USWest2);


            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "myfirstfunction",
                InvocationType = InvocationType.RequestResponse,
                Payload        = "\"Hello Du\""
            };

            InvokeResponse response = client.InvokeAsync(ir).Result;

            var        sr     = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(sr);

            var serilizer = new JsonSerializer();
            var op        = serilizer.Deserialize(reader);

            Console.WriteLine(op);
        }
示例#22
0
        private static string PostPredicitionViaInvokeRequest(string serializedPrediction)
        {
            AmazonLambdaClient client = new AmazonLambdaClient("awsaccessKeyID", "awsSecreteAccessKey", RegionEndpoint.USWest1);

            InvokeRequest ir = new InvokeRequest
            {
                FunctionName   = "HelloLambdaWorld",
                InvocationType = InvocationType.RequestResponse,
                Payload        = "\"Vikram\""
            };

            InvokeResponse response = null; // client.Invoke(ir);

            var        sr     = new StreamReader(response.Payload);
            JsonReader reader = new JsonTextReader(sr);

            var serilizer = new JsonSerializer();
            var op        = serilizer.Deserialize(reader);

            Console.WriteLine(op);
            Console.ReadLine();

            return(serializedPrediction);
        }
        /// <summary>
        /// Primary adapter method for processing activities sent from calling bot.
        /// </summary>
        /// <param name="activity">The activity to process.</param>
        /// <param name="callback">The BotCallBackHandler to call on completion.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>The response to the activity.</returns>
        public async Task <InvokeResponse> ProcessActivityAsync(Activity activity, BotCallbackHandler callback, CancellationToken cancellationToken)
        {
            // Ensure the Activity has been retrieved from the HTTP POST
            BotAssert.ActivityNotNull(activity);

            _botTelemetryClient.TrackTrace($"SkillHttpBotAdapter: Received an incoming activity. Activity id: {activity.Id}", Severity.Information, null);

            // Process the Activity through the Middleware and the Bot, this will generate Activities which we need to send back.
            using (var context = new TurnContext(this, activity))
            {
                await RunPipelineAsync(context, callback, default(CancellationToken));
            }

            _botTelemetryClient.TrackTrace($"SkillHttpBotAdapter: Batching activities in the response. ReplyToId: {activity.ReplyToId}", Severity.Information, null);

            // Any Activity responses are now available (via SendActivitiesAsync) so we need to pass back for the response
            var response = new InvokeResponse
            {
                Status = (int)HttpStatusCode.OK,
                Body   = GetReplies(),
            };

            return(response);
        }
        public override async Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context)
        {
            Console.WriteLine($"Method {request.Method}");

            var response = new InvokeResponse();

            switch (request.Method)
            {
            case "reserve":
                var input  = request.Data.Unpack <Generated.Item>();
                var output = await Task.FromResult <Generated.Item>(new Generated.Item()
                {
                    SKU = input.SKU, Quantity = -input.Quantity
                });

                response.Data = Any.Pack(output);
                break;

            default:
                Console.WriteLine("Method not supported");
                break;
            }
            return(response);
        }
        protected override async Task <InvokeResponse> OnInvokeActivityAsync(ITurnContext <IInvokeActivity> turnContext, CancellationToken cancellationToken)
        {
            JObject valueObject = JObject.FromObject(turnContext.Activity.Value);

            if (valueObject["authentication"] != null)
            {
                JObject authenticationObject = JObject.FromObject(valueObject["authentication"]);
                if (authenticationObject["token"] != null)
                {
                    //If the token is NOT exchangeable, then return 412 to require user consent
                    if (await TokenIsExchangeable(turnContext, cancellationToken))
                    {
                        return(await base.OnInvokeActivityAsync(turnContext, cancellationToken).ConfigureAwait(false));
                    }
                    else
                    {
                        var response = new InvokeResponse();
                        response.Status = 412;
                        return(response);
                    }
                }
            }
            return(await base.OnInvokeActivityAsync(turnContext, cancellationToken).ConfigureAwait(false));
        }
示例#26
0
        public async Task InvokeMethodAsync_CanInvokeMethodWithReturnTypeAndData_ThrowsExceptionForNonSuccess()
        {
            var client = new MockClient();
            var data   = new Response()
            {
                Name = "Look, I was invoked!"
            };
            var invokeResponse = new InvokeResponse
            {
                Data = TypeConverters.ToAny(data)
            };

            var response =
                client.Call <InvokeResponse>()
                .SetResponse(invokeResponse)
                .Build();


            const string     rpcExceptionMessage = "RPC exception";
            const StatusCode rpcStatusCode       = StatusCode.Unavailable;
            const string     rpcStatusDetail     = "Non success";

            var rpcStatus    = new Status(rpcStatusCode, rpcStatusDetail);
            var rpcException = new RpcException(rpcStatus, new Metadata(), rpcExceptionMessage);

            // Setup the mock client to throw an Rpc Exception with the expected details info
            client.Mock
            .Setup(m => m.InvokeServiceAsync(It.IsAny <Autogen.Grpc.v1.InvokeServiceRequest>(), It.IsAny <CallOptions>()))
            .Throws(rpcException);

            await FluentActions.Awaiting(async() => await client.DaprClient.InvokeMethodAsync <Request, Response>("test", "test", new Request()
            {
                RequestParameter = "Hello "
            }))
            .Should().ThrowAsync <InvocationException>();
        }
示例#27
0
        public override async Task <InvokeResponse> OnInvoke(InvokeRequest request, ServerCallContext context)
        {
            var response = new InvokeResponse();

            using var scope = _serviceLoader.CreateScope();
            var service = _serviceLoader.Create(request.Method, scope);
            var method  = _serviceLoader.GetMethod(request.Method, service);

            try
            {
                var requestData = GetRequestData(request.Data, method.GetParameters()[0].ParameterType);

                var   task = (Task)method.Invoke(service, new[] { requestData }) !;
                await task !.ConfigureAwait(false);

                var resultProperty = task.GetType().GetProperty("Result");
                response.Data = Any.Pack((IMessage)resultProperty !.GetValue(task) !);
            }
            catch (System.Exception e)
            {
                throw;
            }
            return(response);
        }
示例#28
0
        public IResponse Request(IRequest request, IRecipientCallback callback)
        {
            try
            {
                switch (request)
                {
                case GetBindingDescriptionsRequest getBindingsReq:
                    var getBindingsResp = new GetBindingDescriptionsResponse();
                    foreach (var obj in _registeredObjects)
                    {
                        getBindingsResp.bindings.Add(obj.Key, obj.Value.Description);
                    }
                    return(getBindingsResp);

                case SubscribeRequest subscribeReq:
                    var subscribeObj = _registeredObjects[subscribeReq.objectId];
                    subscribeObj.Subscribe(subscribeReq.eventId, callback);
                    var subscribeResponse = new SubscribeResponse()
                    {
                        objectId = subscribeReq.objectId,
                        eventId  = subscribeReq.eventId
                    };
                    return(subscribeResponse);

                case UnsubscribeRequest unsubscribeReq:
                    var unsubscribeObj = _registeredObjects[unsubscribeReq.objectId];
                    unsubscribeObj.Unsubscribe(unsubscribeReq.eventId, callback);
                    var unsubscribeResponse = new UnsubscribeResponse()
                    {
                        objectId = unsubscribeReq.objectId,
                        eventId  = unsubscribeReq.eventId
                    };
                    return(unsubscribeResponse);

                case PropertyGetRequest propertyGetReq:
                    var    propertyGetObj      = _registeredObjects[propertyGetReq.objectId];
                    object propertyGetValue    = propertyGetObj.GetValue(propertyGetReq.propertyId);
                    var    propertyGetResponse = new PropertyGetResponse()
                    {
                        objectId   = propertyGetReq.objectId,
                        propertyId = propertyGetReq.propertyId,
                        value      = propertyGetValue
                    };
                    return(propertyGetResponse);

                case PropertySetRequest propertySetReq:
                    var propertySetObj = _registeredObjects[propertySetReq.objectId];
                    propertySetObj.SetValue(propertySetReq.propertyId, propertySetReq.value);
                    var propertySetResponse = new PropertySetResponse()
                    {
                        objectId   = propertySetReq.objectId,
                        propertyId = propertySetReq.propertyId
                    };
                    return(propertySetResponse);

                case InvokeRequest invokeReq:
                    var    invokeObj      = _registeredObjects[invokeReq.objectId];
                    object invokeResult   = invokeObj.Invoke(invokeReq.methodId, invokeReq.methodArgs);
                    var    invokeResponse = new InvokeResponse()
                    {
                        objectId = invokeReq.objectId,
                        methodId = invokeReq.methodId,
                        result   = invokeResult
                    };
                    return(invokeResponse);

                default:
                    if (request != null)
                    {
                        throw new RecipientBindingException($"Unsupported request type: {request.requestType}");
                    }
                    else
                    {
                        throw new RecipientBindingException($"Request failed to deserialize.");
                    }
                }
            }
            catch (RecipientBindingException ex)
            {
                var exceptionResponse = new ExceptionResponse()
                {
                    exception = ex
                };

#pragma warning disable EA003 // Catch block swallows an exception
                return(exceptionResponse);
            }
#pragma warning restore EA003 // Catch block swallows an exception
        }
示例#29
0
        private bool Invoke(Invocation invocation, InvokeResponse invokeResponse)
        {
            if (invocation.M == null || invocation.I == null || invocation.V == null)
            {
                throw new ArgumentException();
            }

            var obj = this.session.Instantiate(invocation.I);

            if (obj == null)
            {
                invokeResponse.AddMissingError(invocation.I);
                return(true);
            }

            var composite   = (Composite)obj.Strategy.Class;
            var methodTypes = composite.WorkspaceMethodTypes;
            var methodType  = methodTypes.FirstOrDefault(x => x.Name.Equals(invocation.M));

            if (methodType == null)
            {
                throw new Exception("Method " + invocation.M + " not found.");
            }

            if (!invocation.V.Equals(obj.Strategy.ObjectVersion.ToString()))
            {
                invokeResponse.AddVersionError(obj);
                return(true);
            }

            var acl = new AccessControlList(obj, this.user);

            if (!acl.CanExecute(methodType))
            {
                invokeResponse.AddAccessError(obj);
                return(true);
            }

            var method = obj.GetType().GetMethod(methodType.Name, new Type[] { });

            try
            {
                method.Invoke(obj, null);
            }
            catch (Exception e)
            {
                var innerException = e;
                while (innerException.InnerException != null)
                {
                    innerException = innerException.InnerException;
                }

                invokeResponse.ErrorMessage = innerException.Message;
                return(true);
            }

            var validation = this.session.Derive(false);

            if (validation.HasErrors)
            {
                invokeResponse.AddDerivationErrors(validation);
                return(true);
            }

            return(false);
        }
示例#30
0
        public InvokeResponse Build()
        {
            var invokeResponse = new InvokeResponse();

            if (this.isolated)
            {
                foreach (var invocation in this.invocations)
                {
                    var error = this.Invoke(invocation, invokeResponse);
                    if (!error)
                    {
                        var validation = this.session.Derive(false);
                        if (validation.HasErrors)
                        {
                            error = true;
                            invokeResponse.AddDerivationErrors(validation);
                        }
                    }

                    if (error)
                    {
                        this.session.Rollback();
                        if (!this.continueOnError)
                        {
                            break;
                        }
                    }
                    else
                    {
                        this.session.Commit();
                    }
                }
            }
            else
            {
                var error = false;
                foreach (var invocation in this.invocations)
                {
                    error = this.Invoke(invocation, invokeResponse);
                    if (error)
                    {
                        break;
                    }
                }

                if (error)
                {
                    this.session.Rollback();
                }
                else
                {
                    var validation = this.session.Derive(false);
                    if (validation.HasErrors)
                    {
                        invokeResponse.AddDerivationErrors(validation);
                    }
                    else
                    {
                        this.session.Commit();
                    }
                }
            }

            return(invokeResponse);
        }
示例#31
0
        public InvokeResponse Build()
        {
            if (this.invokeRequest.M == null || this.invokeRequest.I == null || this.invokeRequest.V == null)
            {
                throw new ArgumentException();
            }

            var obj         = this.session.Instantiate(this.invokeRequest.I);
            var composite   = (Composite)obj.Strategy.Class;
            var methodTypes = composite.MethodTypesByGroup[this.@group];
            var methodType  = methodTypes.FirstOrDefault(x => x.Name.Equals(this.invokeRequest.M));

            if (methodType == null)
            {
                throw new Exception("Method " + this.invokeRequest.M + " not found.");
            }

            var invokeResponse = new InvokeResponse();

            if (!this.invokeRequest.V.Equals(obj.Strategy.ObjectVersion.ToString()))
            {
                invokeResponse.AddVersionError(obj);
            }
            else
            {
                var acl = new AccessControlList(obj, this.user);
                if (acl.CanExecute(methodType))
                {
                    var method = obj.GetType().GetMethod(methodType.Name, new Type[] { });

                    try
                    {
                        method.Invoke(obj, null);
                    }
                    catch (Exception e)
                    {
                        var innerException = e;
                        while (innerException.InnerException != null)
                        {
                            innerException = innerException.InnerException;
                        }

                        invokeResponse.ErrorMessage = innerException.Message;
                    }

                    var validation = this.session.Derive();
                    if (!validation.HasErrors)
                    {
                        this.session.Commit();
                    }
                    else
                    {
                        invokeResponse.AddDerivationErrors(validation);
                    }
                }
                else
                {
                    invokeResponse.AddAccessError(obj);
                }
            }

            return(invokeResponse);
        }