private async Task sendkeystroke(int stroke) { try { if (address != "" && pinc != "") { var channel = GrpcChannel.ForAddress(address); var control = new GControl.GControlClient(channel); HelloReply reply = await control.DoSomethingAsync( new HelloRequest { Keycode = stroke, Authkey = pinc }); if (!reply.Back) { showerror(string.Format("Can't execute stroke {0}, look at server for logs!", stroke)); } } else { showerror("This Should not happend! You call without init"); } } catch (Exception e) { showerror(e.Message); } }
protected virtual byte[] GetMessageData(HelloReply message) { var ms = new MemoryStream(); MessageHelpers.WriteMessage(ms, message); return(ms.ToArray()); }
public async Task AsyncUnaryCall_Success_RequestContentSent() { // Arrange HttpContent?content = null; var httpClient = ClientTestHelpers.CreateTestClient(async request => { content = request.Content; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest { Name = "World" }); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(content); var requestContent = await content !.ReadAsStreamAsync().DefaultTimeout(); var requestMessage = await requestContent.ReadSingleMessageAsync(NullLogger.Instance, ClientTestHelpers.ServiceMethod.RequestMarshaller.Deserializer, CancellationToken.None).DefaultTimeout(); Assert.AreEqual("World", requestMessage.Name); }
/// <summary> /// Server side handler of the Hello RPC /// </summary> public override Task <HelloReply> Hello(HelloRequest req, ServerCallContext context) { HelloReply reply = new HelloReply(); reply.Message = Reverse(req.Message); return(Task.FromResult(reply)); }
public async Task AsyncUnaryCall_SuccessAfterRetry_AccessResponseHeaders_SuccessfullyResponseHeadersReturned() { // Arrange HttpContent?content = null; var syncPoint = new SyncPoint(runContinuationsAsynchronously: true); var callCount = 0; var httpClient = ClientTestHelpers.CreateTestClient(async request => { callCount++; content = request.Content !; if (callCount == 1) { await content.CopyToAsync(new MemoryStream()); await syncPoint.WaitForSyncPoint(); return(ResponseUtils.CreateHeadersOnlyResponse( HttpStatusCode.OK, StatusCode.Unavailable, customHeaders: new Dictionary <string, string> { ["call-count"] = callCount.ToString() })); } syncPoint.Continue(); var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse( HttpStatusCode.OK, streamContent, customHeaders: new Dictionary <string, string> { ["call-count"] = callCount.ToString() })); }); var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig(); var invoker = HttpClientCallInvokerFactory.Create(httpClient, serviceConfig: serviceConfig); // Act var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest { Name = "World" }); var headersTask = call.ResponseHeadersAsync; // Wait until the first call has failed and the second is on the server await syncPoint.WaitToContinue().DefaultTimeout(); // Assert Assert.AreEqual(2, callCount); Assert.AreEqual("Hello world", (await call.ResponseAsync.DefaultTimeout()).Message); var headers = await headersTask.DefaultTimeout(); Assert.AreEqual("2", headers.GetValue("call-count")); }
public async Task CallCredentialsWithHttps_MetadataOnRequest() { // Arrange string?authorizationValue = null; var httpClient = ClientTestHelpers.CreateTestClient(async request => { authorizationValue = request.Headers.GetValues("authorization").Single(); var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var callCredentials = CallCredentials.FromInterceptor(async(context, metadata) => { // The operation is asynchronous to ensure delegate is awaited await Task.Delay(50); metadata.Add("authorization", "SECRET_TOKEN"); }); var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest()); await call.ResponseAsync.DefaultTimeout(); // Assert Assert.AreEqual("SECRET_TOKEN", authorizationValue); }
public async Task AsyncUnaryCall_HasWinHttpHandler_ContentLengthOnHttpRequestMessagePopulated() { // Arrange HttpRequestMessage?httpRequestMessage = null; long?requestContentLength = null; var handler = TestHttpMessageHandler.Create(async request => { httpRequestMessage = request; requestContentLength = httpRequestMessage !.Content !.Headers !.ContentLength; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); // Just need to have a type called WinHttpHandler to activate new behavior. var winHttpHandler = new WinHttpHandler(handler); var invoker = HttpClientCallInvokerFactory.Create(winHttpHandler, "https://localhost"); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>( ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest { Name = "Hello world" }).ResponseAsync.DefaultTimeout(); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual(18, requestContentLength); }
public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context) { HelloReply response = new HelloReply(); response.Message = this.HelloService.SayHello(request.Name); return(Task.FromResult(response)); }
public async Task AsyncUnaryCall_SendHeaders_RequestMessageContainsHeaders() { // Arrange HttpRequestMessage httpRequestMessage = null; var httpClient = TestHelpers.CreateTestClient(async request => { httpRequestMessage = request; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await TestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = new HttpClientCallInvoker(httpClient); var headers = new Metadata(); headers.Add("custom", "ascii"); headers.Add("custom-bin", Encoding.UTF8.GetBytes("Hello world")); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(TestHelpers.ServiceMethod, null, new CallOptions(headers : headers), new HelloRequest()); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual("ascii", httpRequestMessage.Headers.GetValues("custom").Single()); Assert.AreEqual("Hello world", Encoding.UTF8.GetString(Convert.FromBase64String(httpRequestMessage.Headers.GetValues("custom-bin").Single()))); }
public async Task ResolverReturnsNoAddresses_DeadlineWhileWaitForReady_Error() { // Arrange var testMessageHandler = TestHttpMessageHandler.Create(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var services = new ServiceCollection(); services.AddSingleton <TestResolver>(); services.AddSingleton <ResolverFactory, TestResolverFactory>(); services.AddSingleton <ISubchannelTransportFactory>(new TestSubchannelTransportFactory()); var invoker = HttpClientCallInvokerFactory.Create(testMessageHandler, "test:///localhost", configure: o => { o.Credentials = ChannelCredentials.Insecure; o.ServiceProvider = services.BuildServiceProvider(); }); // Act var callOptions = new CallOptions(deadline: DateTime.UtcNow.AddSeconds(0.2)).WithWaitForReady(); var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, callOptions, new HelloRequest()); var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.ResponseAsync).DefaultTimeout(); Assert.AreEqual(StatusCode.DeadlineExceeded, ex.StatusCode); Assert.AreEqual(string.Empty, ex.Status.Detail); }
static async Task Main(string[] args) { var serverAddress = "https://localhost:5001"; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // The following statement allows you to call insecure services. To be used only in development environments. AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); serverAddress = "http://localhost:5000"; } GrpcChannel channel = GrpcChannel.ForAddress(serverAddress); Greeter.GreeterClient greetingClient = new Greeter.GreeterClient(channel); HelloRequest greeterRequest = new HelloRequest { Name = "Dhafi" }; HelloReply greeterResponse = await greetingClient.SayHelloAsync(greeterRequest); Console.WriteLine(greeterResponse.Message); CreditRatingCheck.CreditRatingCheckClient creditRatingClient = new CreditRatingCheck.CreditRatingCheckClient(channel); CreditRequest creditRequest = new CreditRequest { CustomerId = "id0201", Credit = 7000 }; CreditReply creditRatingResponse = await creditRatingClient.CheckCreditRequestAsync(creditRequest); Console.WriteLine($"Credit for customer {creditRequest.CustomerId} {(creditRatingResponse.IsAccepted ? "approved" : "rejected")}!"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
/// <summary> /// Basic client implementation of simple gRPC /// Overall it has 3 steps: /// 1. Initiate client (in the constructor) /// 2. Prepare request object (as defined in proto file) /// 3. Execute rpc and handle response (as defined in proto file) /// </summary> /// <param name="name">Name that will be sent as a request</param> /// <returns>Message that is received back from rpc</returns> public async Task <string> DoTheGreet(string name) { // Prepare rpc request object HelloRequest request = new HelloRequest { Name = name }; try { // Execute rpc and handle response HelloReply response = await client.SayHelloAsync(request); return(response.Message); } catch (RpcException ex) { // Any exception coming from RPC will be in object RpcException Console.WriteLine($"Error making GRPC request: {ex}"); } catch (Exception ex) { Console.WriteLine(ex); } return(null); }
public async Task AsyncUnaryCall_AuthInterceptorSuccess_ResponseHeadersPopulated() { // Arrange var httpClient = ClientTestHelpers.CreateTestClient(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); var response = ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent); response.Headers.Add("custom", "ABC"); return(response); }); var credentialsSyncPoint = new SyncPoint(runContinuationsAsynchronously: true); var credentials = CallCredentials.FromInterceptor(async(context, metadata) => { await credentialsSyncPoint.WaitToContinue(); metadata.Add("Authorization", $"Bearer TEST"); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient, configure: options => options.Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)); // Act var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest()); var responseHeadersTask = call.ResponseHeadersAsync; await credentialsSyncPoint.WaitForSyncPoint().DefaultTimeout(); credentialsSyncPoint.Continue(); var responseHeaders = await responseHeadersTask.DefaultTimeout(); // Assert Assert.AreEqual("ABC", responseHeaders.GetValue("custom")); }
public async Task AsyncUnaryCall_Success_ResponseHeadersPopulated() { // Arrange var httpClient = ClientTestHelpers.CreateTestClient(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); var response = ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent); response.Headers.Server.Add(new ProductInfoHeaderValue("TestName", "1.0")); response.Headers.Add("custom", "ABC"); response.Headers.Add("binary-bin", Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello world"))); return(response); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest()); var responseHeaders1 = await call.ResponseHeadersAsync.DefaultTimeout(); var responseHeaders2 = await call.ResponseHeadersAsync.DefaultTimeout(); // Assert Assert.AreSame(responseHeaders1, responseHeaders2); Assert.AreEqual("TestName/1.0", responseHeaders1.GetValue("server")); Assert.AreEqual("ABC", responseHeaders1.GetValue("custom")); var header = responseHeaders1.Get("binary-bin") !; Assert.AreEqual(true, header.IsBinary); CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("Hello world"), header.ValueBytes); }
public async Task ClientStreamWriter_WriteAfterResponseHasFinished_ErrorThrown() { // Arrange var httpClient = ClientTestHelpers.CreateTestClient(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions()); var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.RequestStream.WriteAsync(new HelloRequest())).DefaultTimeout(); var result = await call.ResponseAsync.DefaultTimeout(); // Assert Assert.AreEqual(StatusCode.OK, ex.StatusCode); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.AreEqual(string.Empty, call.GetStatus().Detail); Assert.AreEqual("Hello world", result.Message); }
public async Task AsyncUnaryCall_NoHeaders_RequestMessageHasNoHeaders() { // Arrange HttpRequestMessage httpRequestMessage = null; var httpClient = TestHelpers.CreateTestClient(async request => { httpRequestMessage = request; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await TestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = new HttpClientCallInvoker(httpClient); var headers = new Metadata(); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(TestHelpers.ServiceMethod, null, new CallOptions(headers : headers), new HelloRequest()); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(httpRequestMessage); // User-Agent is always sent Assert.AreEqual(0, httpRequestMessage.Headers.Count(h => !string.Equals(h.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))); }
public async Task CallCredentials_AuthContextPopulated(string target, string expectedServiceUrl) { // Arrange var httpClient = ClientTestHelpers.CreateTestClient(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }, new Uri(target)); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act string?serviceUrl = null; string?methodName = null; var callCredentials = CallCredentials.FromInterceptor((context, metadata) => { serviceUrl = context.ServiceUrl; methodName = context.MethodName; return(Task.CompletedTask); }); var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest()); await call.ResponseAsync.DefaultTimeout(); // Assert Assert.AreEqual(expectedServiceUrl, serviceUrl); Assert.AreEqual("MethodName", ClientTestHelpers.ServiceMethod.Name); }
public override Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context) { _logger.LogInformation("called SayHellow ({Request})", request); var response = new HelloReply { Message = "Hello " + request.Name, Info = new HellowInfo { Id = 1, InnerA = new HellowInfo.Types.InnerA { B = new HellowInfo.Types.InnerA.Types.InnerB { Type = HellowInfo.Types.InnerA.Types.InnerB.Types.TypeB.B } }, Name = "Say Hellow", Type = HellowInfo.Types.TypeInfo.B }, InfoArray = { new HellowInfo[] { new HellowInfo() } }, Keywords = { new[] { "", "" } }, Date = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow), Time = Google.Protobuf.WellKnownTypes.Duration.FromTimeSpan(TimeSpan.Parse("01:05:00")), }; return(Task.FromResult(response)); }
public async Task AsyncServerStreamingCall_NoContent_NoMessagesReturned() { // Arrange HttpRequestMessage httpRequestMessage = null; var httpClient = TestHelpers.CreateTestClient(request => { httpRequestMessage = request; HelloReply reply = new HelloReply { Message = "Hello world" }; return(Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.OK, new ByteArrayContent(Array.Empty <byte>())))); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var call = invoker.AsyncServerStreamingCall <HelloRequest, HelloReply>(TestHelpers.ServiceMethod, null, new CallOptions(), new HelloRequest()); var responseStream = call.ResponseStream; // Assert Assert.IsNull(responseStream.Current); Assert.IsFalse(await responseStream.MoveNext(CancellationToken.None).DefaultTimeout()); Assert.IsNull(responseStream.Current); }
public async Task GreeterServiceTest() { //服务信息 var serviceInfo = new ServiceInformation() { Host = "127.0.0.1", Port = 1234, Description = "我的小服务, 老火了", Key = "Foo.Services", Name = "我的小服务", ServiceType = ServiceType.Grpc, }; //启动服务 Server server = new Server { Services = { Greeter.BindService(new GreeterImpl()) }, Ports = { new ServerPort(serviceInfo.Host, serviceInfo.Port, ServerCredentials.Insecure) } }; server.Start(); //注册服务 using (var zon = await ServiceBus.Register(serviceInfo)) { //发现服务 string serviceKey = serviceInfo.Key; ServiceInformation service = ServiceBus.Get(serviceKey).Result.FeelingLucky(); //使用服务 string target = $"{service.Host}:{service.Port}"; Channel channel = new Channel(target, ChannelCredentials.Insecure); Greeter.GreeterClient client = new Greeter.GreeterClient(channel); HelloRequest request = new HelloRequest() { Name = "徐云金", SecretSignal = "天王盖地虎", }; request.Gifts.AddRange(new List <Gift>() { new Gift { Name = "兔子" }, new Gift { Name = "橘猫" }, }); Console.WriteLine($"request: \n{JsonConvert.SerializeObject(request)}"); HelloReply reply = client.SayHello(request); Console.WriteLine($"reply: \n{JsonConvert.SerializeObject(reply)}"); Assert.AreEqual(request.Name, reply.Name); channel.ShutdownAsync().Wait(); } }
public async Task AsyncUnaryCall_AwaitMultipleTimes_SameMessageReturned() { // Arrange var httpClient = TestHelpers.CreateTestClient(async request => { HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await TestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(TestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest { Name = "World" }); var response1 = await call; var response2 = await call; var response3 = await call.ResponseAsync.DefaultTimeout(); var response4 = await call.ResponseAsync.DefaultTimeout(); // Assert Assert.AreEqual("Hello world", response1.Message); Assert.AreEqual(response1, response2); Assert.AreEqual(response1, response3); Assert.AreEqual(response1, response4); }
private static async Task callClientStreaming(Greeter.GreeterClient client) { using var clientStreamingCall = client.SayHelloClientStreaming(); for (int i = 0; i < 5; i++) { string name = $"John #{i}"; Console.WriteLine($"Sending name: {name}"); try { await clientStreamingCall.RequestStream.WriteAsync(new HelloRequest { Name = name }); } catch (InvalidOperationException ex) { Console.WriteLine($"InvalidOperationException: {ex.Message}"); // Can't write the message because the call is complete. return; } await Task.Delay(500); } await clientStreamingCall.RequestStream.CompleteAsync(); HelloReply reply = await clientStreamingCall; reply.WriteToConsole(); }
public async Task AsyncClientStreamingCall_Success_HttpRequestMessagePopulated() { // Arrange HttpRequestMessage?httpRequestMessage = null; var httpClient = TestHelpers.CreateTestClient(async request => { httpRequestMessage = request; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await TestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var call = invoker.AsyncClientStreamingCall <HelloRequest, HelloReply>(TestHelpers.ServiceMethod, string.Empty, new CallOptions()); await call.RequestStream.CompleteAsync().DefaultTimeout(); var response = await call; // Assert Assert.AreEqual("Hello world", response.Message); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual(new Version(2, 0), httpRequestMessage !.Version); Assert.AreEqual(HttpMethod.Post, httpRequestMessage.Method); Assert.AreEqual(new Uri("https://localhost/ServiceName/MethodName"), httpRequestMessage.RequestUri); Assert.AreEqual(new MediaTypeHeaderValue("application/grpc"), httpRequestMessage.Content.Headers.ContentType); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService <GreeterService>(); endpoints.MapPost("/", async context => { using var memStream = StreamPool.GetStream(); await context.Request.Body.CopyToAsync(memStream); memStream.Position = 0; var request = HelloRequest.Parser.ParseDelimitedFrom(memStream); var response = new HelloReply { Message = "Hello " + request.Name }; memStream.Position = 0; memStream.SetLength(0); response.WriteDelimitedTo(memStream); memStream.Position = 0; context.Response.StatusCode = (int)HttpStatusCode.Accepted; await memStream.CopyToAsync(context.Response.Body); }); }); }
public async Task AsyncUnaryCall_Success_RequestContentSent() { // Arrange HttpContent?content = null; var callCount = 0; var httpClient = ClientTestHelpers.CreateTestClient(async request => { callCount++; content = request.Content; var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var serviceConfig = ServiceConfigHelpers.CreateRetryServiceConfig(); var invoker = HttpClientCallInvokerFactory.Create(httpClient, serviceConfig: serviceConfig); // Act var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest { Name = "World" }); // Assert Assert.AreEqual(1, callCount); Assert.AreEqual("Hello world", (await call.ResponseAsync.DefaultTimeout()).Message); }
public async Task CallCredentialsWithHttps_WhenAsyncAuthInterceptorThrow_ShouldThrow() { // Arrange var services = new ServiceCollection(); services.AddNUnitLogger(); var loggerFactory = services.BuildServiceProvider().GetRequiredService <ILoggerFactory>(); var httpClient = ClientTestHelpers.CreateTestClient(async request => { var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create(httpClient, loggerFactory); // Act var expectedException = new Exception("Some AsyncAuthInterceptor Exception"); var callCredentials = CallCredentials.FromInterceptor((context, metadata) => { return(Task.FromException(expectedException)); }); var call = invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(credentials: callCredentials), new HelloRequest()); var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call.ResponseAsync).DefaultTimeout(); // Assert Assert.AreSame(expectedException, ex.Status.DebugException); }
public async Task AsyncUnaryCall_SendDeadlineHeaderAndDeadlineValue_DeadlineValueIsUsed() { // Arrange HttpRequestMessage?httpRequestMessage = null; var httpClient = ClientTestHelpers.CreateTestClient(async request => { httpRequestMessage = request; HelloReply reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var invoker = HttpClientCallInvokerFactory.Create( httpClient, systemClock: new TestSystemClock(new DateTime(2019, 11, 29, 1, 1, 1, DateTimeKind.Utc))); var headers = new Metadata(); headers.Add("grpc-timeout", "1D"); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(headers : headers, deadline : invoker.Channel.Clock.UtcNow.AddSeconds(1)), new HelloRequest()); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual("1S", httpRequestMessage !.Headers.GetValues(GrpcProtocolConstants.TimeoutHeader).Single()); }
public async Task AsyncUnaryCall_SubdirectoryHandlerConfigured_RequestUriChanged() { // Arrange HttpRequestMessage?httpRequestMessage = null; var handler = TestHttpMessageHandler.Create(async r => { httpRequestMessage = r; var reply = new HelloReply { Message = "Hello world" }; var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return(ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent)); }); var httpClient = new HttpClient(new SubdirectoryHandler(handler, "/TestSubdirectory")); httpClient.BaseAddress = new Uri("https://localhost"); var invoker = HttpClientCallInvokerFactory.Create(httpClient); // Act var rs = await invoker.AsyncUnaryCall <HelloRequest, HelloReply>(ClientTestHelpers.ServiceMethod, string.Empty, new CallOptions(), new HelloRequest()); // Assert Assert.AreEqual("Hello world", rs.Message); Assert.IsNotNull(httpRequestMessage); Assert.AreEqual(new Version(2, 0), httpRequestMessage !.Version); Assert.AreEqual(HttpMethod.Post, httpRequestMessage.Method); Assert.AreEqual(new Uri("https://localhost/TestSubdirectory/ServiceName/MethodName"), httpRequestMessage.RequestUri); }
private async void writeout(object send, EventArgs xx) { try { string stroke = textinputW.Text; if (address != "" && pinc != "") { var channel = GrpcChannel.ForAddress(address); var control = new GControl.GControlClient(channel); HelloReply reply = await control.typeitAsync( new typesomething { Totype = stroke, Authkey = pinc }); if (!reply.Back) { showerror(string.Format("Can't execute type \"{0}\", look at server for logs!", stroke)); } else { textinputW.Text = ""; } } else { showerror("This Should not happend! You call without init"); } } catch (Exception e) { showerror(e.Message); } }
public static TestHttpMessageHandler CreateTestMessageHandler(HelloReply reply) { return(TestHttpMessageHandler.Create(async r => { var streamContent = await ClientTestHelpers.CreateResponseContent(reply).DefaultTimeout(); return ResponseUtils.CreateResponse(HttpStatusCode.OK, streamContent); })); }