예제 #1
0
        public async Task DaprCall_WithApiTokenSet()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .UseDaprApiToken("test_token")
                             .Build();

            var task = daprClient.GetSecretAsync("testStore", "test_key");

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <Autogenerated.GetSecretRequest>(entry.Request);

            entry.Request.Headers.TryGetValues("dapr-api-token", out var headerValues);
            headerValues.Count().Should().Be(1);
            headerValues.First().Should().Be("test_token");
        }
예제 #2
0
        public async Task InvokeMethodWithResponseAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();

            await FluentActions.Awaiting(async() => await daprClient.InvokeMethodWithResponseAsync <Request, Response>("test", "test", new Request()
            {
                RequestParameter = "Hello "
            }, cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
예제 #3
0
        public async Task <IActionResult> SaveState([FromBody] OrderStatus status)
        {
            _logger.LogInformation($"State with order id {status.OrderId} received.");

            try
            {
                status.OrderId = Guid.NewGuid();
                var daprClient = new DaprClientBuilder().Build();
                await daprClient.SaveStateAsync(EndPoints.StateMangement, status.OrderId.ToString(), status);

                _logger.LogInformation(
                    $"State with order id {status.OrderId} saved to redis.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Something went wrong");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            return(Ok(status.OrderId));
        }
예제 #4
0
        public async Task PublishEventAsync_CanPublishTopicWithNoContent()
        {
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();


            var task = daprClient.PublishEventAsync(TestPubsubName, "test");

            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <PublishEventRequest>(entry.Request);

            var jsonFromRequest = request.Data.ToStringUtf8();

            request.PubsubName.Should().Be(TestPubsubName);
            request.Topic.Should().Be("test");
            jsonFromRequest.Should().Be("\"\"");
        }
예제 #5
0
        public async Task GetStateAsync_CanReadEmptyState_ReturnsDefault()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var task = daprClient.GetStateAsync <Widget>("testStore", "test", ConsistencyMode.Eventual);

            // Create Response & Respond
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            SendResponseWithState <Widget>(null, entry);

            // Get response and validate
            var state = await task;

            state.Should().BeNull();
        }
        public async Task InvokeMethodGrpcAsync_AppCallback_UnexpectedMethod()
        {
            // Configure Client
            var httpClient = new AppCallbackClient(new DaprAppCallbackService());
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions()
            {
                HttpClient = httpClient,
            })
                             .UseJsonSerializationOptions(this.jsonSerializerOptions)
                             .Build();

            var request = new Request()
            {
                RequestParameter = "Look, I was invoked!"
            };

            var response = await daprClient.InvokeMethodGrpcAsync <Request, Response>("test", "not-existing", request);

            response.Name.Should().Be("unexpected");
        }
예제 #7
0
        public async Task GetBulkSecretAsync_ReturnSingleSecret()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var metadata = new Dictionary <string, string>();

            metadata.Add("key1", "value1");
            metadata.Add("key2", "value2");
            var task = daprClient.GetBulkSecretAsync("testStore", metadata);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <Autogenerated.GetBulkSecretRequest>(entry.Request);

            request.StoreName.Should().Be("testStore");
            request.Metadata.Count.Should().Be(2);
            request.Metadata.Keys.Contains("key1").Should().BeTrue();
            request.Metadata.Keys.Contains("key2").Should().BeTrue();
            request.Metadata["key1"].Should().Be("value1");
            request.Metadata["key2"].Should().Be("value2");

            // Create Response & Respond
            var secrets = new Dictionary <string, string>();

            secrets.Add("redis_secret", "Guess_Redis");
            await SendBulkResponseWithSecrets(secrets, entry);

            // Get response and validate
            var secretsResponse = await task;

            secretsResponse.Count.Should().Be(1);
            secretsResponse.ContainsKey("redis_secret").Should().BeTrue();
            secretsResponse["redis_secret"]["redis_secret"].Should().Be("Guess_Redis");
        }
예제 #8
0
        public async Task ExecuteStateTransactionAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();

            var operation  = new StateTransactionRequest("test", null, StateOperationType.Delete);
            var operations = new List <StateTransactionRequest>();

            operations.Add(operation);
            await FluentActions.Awaiting(async() => await daprClient.ExecuteStateTransactionAsync("testStore", operations, new Dictionary <string, string>(), cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
예제 #9
0
        public static DaprClient GetDaprClient(
            this IConfiguration config,
            string appId,
            ILogger logger = null)
        {
            var url = config.GetTyeGrpcAppUrl(appId);

            logger?.LogInformation($"Dapr Client Url: {url}");

            var client = new DaprClientBuilder()
                         .UseEndpoint(url)
                         .UseJsonSerializationOptions(new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            })
                         .UseGrpcChannelOptions(new GrpcChannelOptions {
                Credentials = ChannelCredentials.Insecure
            })
                         .Build();

            return(client);
        }
예제 #10
0
        public async Task GetSecretAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var metadata = new Dictionary <string, string>();

            metadata.Add("key1", "value1");
            metadata.Add("key2", "value2");

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();
            await FluentActions.Awaiting(async() => await daprClient.GetSecretAsync("testStore", "test_key", metadata, cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
        static async Task Main(string[] args)
        {
            var jsonOptions = new JsonSerializerOptions()
            {
                PropertyNamingPolicy        = JsonNamingPolicy.CamelCase,
                PropertyNameCaseInsensitive = true,
            };

            var client = new DaprClientBuilder()
                         .UseJsonSerializationOptions(jsonOptions)
                         .Build();

            while (true)
            {
                await Task.Delay(1000);

                var messageId = Guid.NewGuid();
                await client.PublishEventAsync(DaprSettings.PubSubName, DaprSettings.Topic, $"{messageId}");

                Console.WriteLine($"Message Id:{messageId}");
            }
        }
예제 #12
0
        static async Task Main(string[] args)
        {
            string AppId      = args[0] ?? "testGrpcDaprService";
            string MethodName = args[1] ?? "SayHello";
            string name       = args[2] ?? "Gennadii";
            var    options    = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            };
            var client = new DaprClientBuilder().UseJsonSerializationOptions(options).Build();

            var anyReply = await client.InvokeMethodAsync <HelloRequest, HelloReply>(
                AppId,
                MethodName,
                new HelloRequest
            {
                Name = name
            }
                );

            Console.WriteLine($"Reply : {anyReply.Message}");
        }
예제 #13
0
        public async Task DeleteStateAsync_ThrowsForNonSuccess()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var task = daprClient.DeleteStateAsync("testStore", "test");

            // Create Response & Respond
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var response = GrpcUtils.CreateResponse(HttpStatusCode.NotAcceptable);

            entry.Completion.SetResult(response);

            var ex = await Assert.ThrowsAsync <DaprException>(async() => await task);

            Assert.IsType <RpcException>(ex.InnerException);
        }
예제 #14
0
        public async Task InvokeMethodAsync_WithReturnTypeAndData_UsesConfiguredJsonSerializerOptions()
        {
            // Configure Client
            var httpClient  = new TestHttpClient();
            var jsonOptions = new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .UseJsonSerializationOptions(jsonOptions)
                             .Build();

            var invokeRequest = new InvokeRequest()
            {
                RequestParameter = "Hello "
            };
            var invokedResponse = new InvokedResponse {
                Name = "Look, I was invoked!"
            };

            var task = daprClient.InvokeMethodAsync <InvokeRequest, InvokedResponse>("test", "test", invokeRequest);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetEnvelopeFromRequestMessageAsync <InvokeServiceEnvelope>(entry.Request);

            envelope.Id.Should().Be("test");
            envelope.Method.Should().Be("test");
            var json = envelope.Data.Value.ToStringUtf8();

            json.Should().Be(JsonSerializer.Serialize(invokeRequest, jsonOptions));

            SendResponse(invokedResponse, entry, jsonOptions);
            var response = await task;

            response.Name.Should().Be(invokedResponse.Name);
        }
예제 #15
0
        public async Task InvokeMethodAsync_CanInvokeMethodWithNoReturnTypeAndData()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            Request request = new Request()
            {
                RequestParameter = "Hello "
            };
            var task = daprClient.InvokeMethodAsync <Request>("test", "test", request);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request);

            envelope.Id.Should().Be("test");
            envelope.Message.Method.Should().Be("test");
            envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson);

            var json            = envelope.Message.Data.Value.ToStringUtf8();
            var typeFromRequest = JsonSerializer.Deserialize <Request>(json);

            typeFromRequest.RequestParameter.Should().Be("Hello ");

            // Create Response & Respond
            var response = new Response()
            {
                Name = "Look, I was invoked!"
            };

            SendResponse(response, entry);

            FluentActions.Awaiting(async() => await task).Should().NotThrow();
        }
예제 #16
0
        public async Task InvokeBindingAsync_WithNullPayload_ValidateRequest()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var task = daprClient.InvokeBindingAsync <InvokeRequest>("test", "create", null);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeBindingRequest>(entry.Request);

            request.Name.Should().Be("test");
            request.Metadata.Count.Should().Be(0);
            var json = request.Data.ToStringUtf8();

            Assert.Equal("null", json);
        }
예제 #17
0
        public async Task InvokeMethodAsync_AppCallback_SayHello()
        {
            // Configure Client
            var jsonOptions = new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            var httpClient = new AppCallbackClient(new DaprAppCallbackService(jsonOptions));
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .UseJsonSerializationOptions(jsonOptions)
                             .Build();

            var request = new Request()
            {
                RequestParameter = "Look, I was invoked!"
            };

            var response = await daprClient.InvokeMethodAsync <Request, Response>("test", "SayHello", request);

            response.Name.Should().Be("Hello Look, I was invoked!");
        }
예제 #18
0
        static async Task StartMessageGeneratorAsync()
        {
            var daprClientBuilder = new DaprClientBuilder();
            var client            = daprClientBuilder.Build();

            while (true)
            {
                var message = GenerateNewMessage();
                Console.WriteLine("Publishing: {0}", message);

                try
                {
                    await client.PublishEventAsync <SampleMessage>("sampletopic", message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

                // Delay 10 seconds
                await Task.Delay(TimeSpan.FromSeconds(10.0));
            }
        }
예제 #19
0
        public async Task InvokeRawMethodAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();

            var body = new Request()
            {
                RequestParameter = "Hello "
            };
            var bytes = JsonSerializer.SerializeToUtf8Bytes(body);
            await FluentActions.Awaiting(async() => await daprClient.InvokeMethodRawAsync("test", "testMethod", bytes, cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
예제 #20
0
        public async Task PublishEventAsync_CanPublishTopicWithContent()
        {
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var publishContent = new PublishContent()
            {
                PublishObjectParameter = "testparam"
            };
            var task = daprClient.PublishEventAsync <PublishContent>("test", publishContent);

            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetEnvelopeFromRequestMessageAsync <PublishEventEnvelope>(entry.Request);

            var jsonFromRequest = envelope.Data.Value.ToStringUtf8();

            envelope.Topic.Should().Be("test");
            jsonFromRequest.Should().Be(JsonSerializer.Serialize(publishContent));
        }
예제 #21
0
        public async Task <string> Get()
        {
            using var client = new DaprClientBuilder()
                               .UseHttpEndpoint(DAPR_SIDECAR_HTTP)
                               .Build();

            try
            {
                var res = await client.GetStateAsync <OrderDto>(STATE_STORE_NAME, STATE_KEY);

                if (res == null)
                {
                    return("获取订单失败!");
                }

                return(JsonConvert.SerializeObject(res));
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, "获取订单出现错误!");
                return(ex.Message);
            }
        }
예제 #22
0
        public async Task PublishEventAsync_CanPublishTopicWithData_WithMetadata()
        {
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var metadata = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };

            var publishData = new PublishData()
            {
                PublishObjectParameter = "testparam"
            };
            var task = daprClient.PublishEventAsync <PublishData>(TestPubsubName, "test", publishData, metadata);

            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <PublishEventRequest>(entry.Request);

            var jsonFromRequest = request.Data.ToStringUtf8();

            request.DataContentType.Should().Be("application/json");
            request.PubsubName.Should().Be(TestPubsubName);
            request.Topic.Should().Be("test");
            jsonFromRequest.Should().Be(JsonSerializer.Serialize(publishData, daprClient.JsonSerializerOptions));

            request.Metadata.Count.Should().Be(2);
            request.Metadata.Keys.Contains("key1").Should().BeTrue();
            request.Metadata.Keys.Contains("key2").Should().BeTrue();
            request.Metadata["key1"].Should().Be("value1");
            request.Metadata["key2"].Should().Be("value2");
        }
예제 #23
0
        public async Task GetStateEntryAsync_CanDeleteState()
        {
            // Configure client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var task = daprClient.GetStateEntryAsync <Widget>("testStore", "test");

            // Create Response & Respond
            var data = new Widget()
            {
                Size = "small", Color = "yellow",
            };

            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            SendResponseWithState(data, entry);

            var state = await task;

            state.Key.Should().Be("test");
            state.Value.Size.Should().Be("small");
            state.Value.Color.Should().Be("yellow");

            state.Value.Color = "green";
            var task2 = state.DeleteAsync();

            // Get Request and validate
            httpClient.Requests.TryDequeue(out entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <Autogenerated.DeleteStateRequest>(entry.Request);

            request.StoreName.Should().Be("testStore");
            request.Key.Should().Be("test");
        }
예제 #24
0
        public async Task InvokeMethodAsync_ValidateRequest()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var queryString = new Dictionary <string, string>();

            queryString.Add("key1", "value1");
            queryString.Add("key2", "value2");

            var httpExtension = new Http.HTTPExtension()
            {
                Verb        = HTTPVerb.Post,
                QueryString = queryString
            };

            var task = daprClient.InvokeMethodAsync <Response>("app1", "mymethod", httpExtension);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request);

            envelope.Id.Should().Be("app1");
            envelope.Message.Method.Should().Be("mymethod");
            envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson);
            envelope.Message.HttpExtension.Verb.Should().Be(Autogen.Grpc.v1.HTTPExtension.Types.Verb.Post);
            envelope.Message.HttpExtension.Querystring.Count.Should().Be(2);
            envelope.Message.HttpExtension.Querystring.ContainsKey("key1").Should().BeTrue();
            envelope.Message.HttpExtension.Querystring.ContainsKey("key2").Should().BeTrue();
            envelope.Message.HttpExtension.Querystring["key1"].Should().Be("value1");
            envelope.Message.HttpExtension.Querystring["key2"].Should().Be("value2");
        }
예제 #25
0
        /// <summary>
        /// This method is called whenever an actor is activated.
        /// An actor is activated the first time any of its methods are invoked.
        /// </summary>
        /// <returns>Async task.</returns>
        protected override async Task OnActivateAsync()
        {
            Console.WriteLine($"Activate ShapeActor {this.Id.GetId()}");
            var actorIdParts = this.Id.GetId().Split('_');
            var clientId     = actorIdParts[0];
            var shapeId      = actorIdParts[1];

            // this is the first time the actor is activated --> initiate the actor state
            await StateManager.TryAddStateAsync(shapeStateName, CreateNewShape());

            // start a reminder for calculating new positions
            await RegisterReminderAsync(
                calculateNewPositionReminderName,
                null,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100));

            // add this shape instance to list (via publish)
            var client = new DaprClientBuilder().UseJsonSerializationOptions(_jsonOptions).Build();
            await client.PublishEventAsync <object>("addShape", new { ClientId = Guid.Parse(clientId), ShapeId = Guid.Parse(shapeId) });

            // base
            await base.OnActivateAsync();
        }
예제 #26
0
        public async Task InvokeBindingAsync_ValidateRequest_WithMetadata()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var metadata = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };
            var invokeRequest = new InvokeRequest()
            {
                RequestParameter = "Hello "
            };
            var task = daprClient.InvokeBindingAsync <InvokeRequest>("test", "create", invokeRequest, metadata);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeBindingRequest>(entry.Request);

            request.Name.Should().Be("test");
            request.Metadata.Count.Should().Be(2);
            request.Metadata.Keys.Contains("key1").Should().BeTrue();
            request.Metadata.Keys.Contains("key2").Should().BeTrue();
            request.Metadata["key1"].Should().Be("value1");
            request.Metadata["key2"].Should().Be("value2");
            var json            = request.Data.ToStringUtf8();
            var typeFromRequest = JsonSerializer.Deserialize <InvokeRequest>(json, daprClient.JsonSerializerOptions);

            typeFromRequest.RequestParameter.Should().Be("Hello ");
        }
예제 #27
0
        public async Task InvokeBindingAsync_WrapsJsonException()
        {
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var response = new Autogen.Grpc.v1.InvokeBindingResponse();
            var bytes    = JsonSerializer.SerializeToUtf8Bytes <Widget>(new Widget()
            {
                Color = "red",
            }, new JsonSerializerOptions(JsonSerializerDefaults.Web));

            response.Data = ByteString.CopyFrom(bytes.Take(10).ToArray()); // trim it to make invalid JSON blog

            var task = daprClient.InvokeBindingAsync <InvokeRequest, Widget>("test", "test", new InvokeRequest()
            {
                RequestParameter = "Hello "
            });

            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var request = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeBindingRequest>(entry.Request);

            var streamContent = await GrpcUtils.CreateResponseContent(response);

            entry.Completion.SetResult(GrpcUtils.CreateResponse(HttpStatusCode.OK, streamContent));

            var ex = await Assert.ThrowsAsync <DaprException>(async() =>
            {
                await task;
            });

            Assert.IsType <JsonException>(ex.InnerException);
        }
예제 #28
0
        public async Task InvokeMethodAsync_NoVerbSpecifiedByUser_ValidateRequest()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            // httpOptions not specified
            var task = daprClient.InvokeMethodAsync <Response>("app1", "mymethod");

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request);

            envelope.Id.Should().Be("app1");
            envelope.Message.Method.Should().Be("mymethod");
            envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson);

            envelope.Message.HttpExtension.Verb.Should().Be(Autogen.Grpc.v1.HTTPExtension.Types.Verb.Post);
            envelope.Message.HttpExtension.Querystring.Count.Should().Be(0);
        }
예제 #29
0
        public async Task InvokeMethodAsync_CanInvokeMethodWithReturnTypeAndData_EmptyResponseReturnsNull()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            var task = daprClient.InvokeMethodAsync <Request, Response>("test", "test", new Request()
            {
                RequestParameter = "Hello "
            });

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request);

            envelope.Id.Should().Be("test");
            envelope.Message.Method.Should().Be("test");
            envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson);

            var json            = envelope.Message.Data.Value.ToStringUtf8();
            var typeFromRequest = JsonSerializer.Deserialize <Request>(json);

            typeFromRequest.RequestParameter.Should().Be("Hello ");

            // Create Response & Respond
            await SendResponse <Response>(null, entry);

            // Validate Response.
            var invokedResponse = await task;

            invokedResponse.Should().BeNull();
        }
예제 #30
0
        public async Task InvokeMethodAsync_AppCallback_RepeatedField()
        {
            // Configure Client
            var jsonOptions = new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            var httpClient = new AppCallbackClient(new DaprAppCallbackService(jsonOptions));
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .UseJsonSerializationOptions(jsonOptions)
                             .Build();

            var testRun = new TestRun();

            testRun.Tests.Add(new TestCase()
            {
                Name = "test1"
            });
            testRun.Tests.Add(new TestCase()
            {
                Name = "test2"
            });
            testRun.Tests.Add(new TestCase()
            {
                Name = "test3"
            });

            var response = await daprClient.InvokeMethodAsync <TestRun, TestRun>("test", "TestRun", testRun);

            response.Tests.Count.Should().Be(3);
            response.Tests[0].Name.Should().Be("test1");
            response.Tests[1].Name.Should().Be("test2");
            response.Tests[2].Name.Should().Be("test3");
        }