示例#1
0
        private async Task TestTelemetryHeaderIsSet(HttpMessageHandler?handler)
        {
            string?telemetryHeader = null;

            Task <HelloReply> UnaryTelemetryHeader(HelloRequest request, ServerCallContext context)
            {
                telemetryHeader = context.RequestHeaders.GetValue(
#if NET5_0
                    "traceparent"
#else
                    "request-id"
#endif
                    );

                return(Task.FromResult(new HelloReply()));
            }

            // Arrange
            var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(UnaryTelemetryHeader);

            var options = new GrpcChannelOptions
            {
                LoggerFactory = LoggerFactory,
                HttpHandler   = handler
            };

            // Want to test the behavior of the default, internally created handler.
            // Only supply the URL to a manually created GrpcChannel.
            var channel = GrpcChannel.ForAddress(Fixture.GetUrl(TestServerEndpointName.Http2), options);
            var client  = TestClientFactory.Create(channel, method);

            // Act
            await client.UnaryCall(new HelloRequest());

            // Assert
            Assert.IsNotNull(telemetryHeader);
        }
示例#2
0
        static async Task Main(string[] args)
        {
            //var input = new HelloRequest { Name = "Ferdeen " };
            //var channel = GrpcChannel.ForAddress("https://localhost:5001");
            //var client = new Greeter.GreeterClient(channel);

            //var reply = await client.SayHelloAsync(input);

            //Console.WriteLine(reply.Message);

            var channel        = GrpcChannel.ForAddress("https://localhost:5001");
            var customerClient = new Customer.CustomerClient(channel);

            var clientRequested = new CustomerLookupModel
            {
                UserId = 1
            };

            var customer = await customerClient.GetCustomerInfoAsync(clientRequested);

            Console.WriteLine($"{ customer.FirstName } { customer.LastName }");

            Console.WriteLine();
            Console.WriteLine("New Customer List");
            Console.WriteLine();

            using (var call = customerClient.GetNewCustomers(new NewCustomerRequest()))
            {
                while (await call.ResponseStream.MoveNext(new System.Threading.CancellationToken()))
                {
                    var currentCustomer = call.ResponseStream.Current;
                    Console.WriteLine($"{ currentCustomer.FirstName } { currentCustomer.LastName } {currentCustomer.EmailAddress}");
                }
            }

            Console.ReadLine();
        }
        public void GrpcClientCallsAreCollectedSuccessfully(string baseAddress, bool shouldEnrich = true)
        {
            var uri             = new Uri($"{baseAddress}:{this.server.Port}");
            var uriHostNameType = Uri.CheckHostName(uri.Host);

            var expectedResource = Resources.Resources.CreateServiceResource("test-service");
            var processor        = new Mock <BaseProcessor <Activity> >();

            var parent = new Activity("parent")
                         .Start();

            using (Sdk.CreateTracerProviderBuilder()
                   .SetSampler(new AlwaysOnSampler())
                   .AddGrpcClientInstrumentation(options =>
            {
                if (shouldEnrich)
                {
                    options.Enrich = ActivityEnrichment;
                }
            })
                   .SetResource(expectedResource)
                   .AddProcessor(processor.Object)
                   .Build())
            {
                var channel = GrpcChannel.ForAddress(uri);
                var client  = new Greeter.GreeterClient(channel);
                var rs      = client.SayHello(new HelloRequest());
            }

            Assert.Equal(4, processor.Invocations.Count); // OnStart/OnEnd/OnShutdown/Dispose called.
            var activity = (Activity)processor.Invocations[1].Arguments[0];

            ValidateGrpcActivity(activity, expectedResource);
            Assert.Equal(parent.TraceId, activity.Context.TraceId);
            Assert.Equal(parent.SpanId, activity.ParentSpanId);
            Assert.NotEqual(parent.SpanId, activity.Context.SpanId);
            Assert.NotEqual(default, activity.Context.SpanId);
示例#4
0
        public async Task WaitForStateChangedAsync_CancellationTokenBeforeEvent_StateChanges()
        {
            // Arrange
            var services = new ServiceCollection();

            services.AddSingleton <ResolverFactory, ChannelTestResolverFactory>();
            services.AddSingleton <ISubchannelTransportFactory, TestSubchannelTransportFactory>();

            var handler        = new TestHttpMessageHandler();
            var channelOptions = new GrpcChannelOptions
            {
                ServiceProvider = services.BuildServiceProvider(),
                HttpHandler     = handler
            };
            var cts = new CancellationTokenSource();

            // Act
            var channel = GrpcChannel.ForAddress("https://localhost", channelOptions);

            var waitForNonIdleTask = channel.WaitForStateChangedAsync(ConnectivityState.Idle);
            var waitForNonIdleWithCancellationTask     = channel.WaitForStateChangedAsync(ConnectivityState.Idle, cts.Token);
            var waitForNonIdleWithCancellationDupeTask = channel.WaitForStateChangedAsync(ConnectivityState.Idle, cts.Token);

            // Assert
            Assert.IsFalse(waitForNonIdleTask.IsCompleted);
            Assert.IsFalse(waitForNonIdleWithCancellationTask.IsCompleted);
            Assert.IsFalse(waitForNonIdleWithCancellationDupeTask.IsCompleted);

            cts.Cancel();
            await ExceptionAssert.ThrowsAsync <OperationCanceledException>(() => waitForNonIdleWithCancellationTask).DefaultTimeout();

            await ExceptionAssert.ThrowsAsync <OperationCanceledException>(() => waitForNonIdleWithCancellationDupeTask).DefaultTimeout();

            await channel.ConnectAsync().DefaultTimeout();

            await waitForNonIdleTask.DefaultTimeout();
        }
示例#5
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            //var c = GrpcChannel.ForAddress("https://localhost:5001");
            //var c = GrpcChannel.ForAddress("http://localhost:5000");
            //var p = NManager.CreateClientProxy<IService>(c);
            //await p.Proxy.Call("hello world.");

            //var channel = Grpc.Net.Client.GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions() { });
            var channel = GrpcChannel.ForAddress("http://localhost:5000");

            //var client = new Greeter.GreeterClient(channel);
            //var r = client.SayHello(new HelloRequest() { Name = "n1" });
            //r = client.SayHello(new HelloRequest() { Name = "n2" });

            //var client = new MessageCall.MessageCallClient(channel);
            //var m = client.DuplexStreamingServerMethod();
            //await m.RequestStream.WriteAsync(new StreamBuffer() { Body = ByteString.CopyFrom("123", Encoding.UTF8) });
            //Console.WriteLine("delay 1000");
            //await Task.Delay(1000);
            //Console.WriteLine("CompleteAsync");
            //await m.RequestStream.CompleteAsync();
            //Console.WriteLine("end");



            //var clientProxy = NetRpc.Grpc.NManager.CreateClientProxy<IService>(new GrpcClientOptions()
            //{
            //    Url = "http://localhost:5000"
            //});

            //await clientProxy.Proxy.Call("1111");

            Console.Read();
        }
示例#6
0
 /*
  * Returns a channel to use
  * The user must call the clean method when it
  * has finished using the channel
  */
 public ChannelBase ForUrl(string url)
 {
     // Only one channel can be created at a time to avoid concurrency issues
     lock (this) {
         if (channels.TryGetValue(url, out LinkedListNode <UrlChannelPair> node))
         {
             channelsPairs.Remove(node);
             channelsPairs.AddLast(node);
             node.Value.Channel.AddRef();
             return(node.Value.Channel);
         }
         else
         {
             // Channel does not exist.
             // Create new channel and delete old one if necessary
             if (channelsPairs.Count == maxOpenChannels)
             {
                 LinkedListNode <UrlChannelPair> oldestNode = channelsPairs.First;
                 // Drop self reference
                 oldestNode.Value.Channel.DropRef();
                 channels.TryRemove(oldestNode.Value.Url, out _);
                 channelsPairs.RemoveFirst();
             }
             GrpcChannel    innerChannel = GrpcChannel.ForAddress(url);
             UrlChannelPair pair         = new UrlChannelPair {
                 Channel = new SharedChannel(innerChannel),
                 Url     = url
             };
             LinkedListNode <UrlChannelPair> newNode = new LinkedListNode <UrlChannelPair>(pair);
             channelsPairs.AddLast(newNode);
             channels.TryAdd(url, newNode);
             // Add ref for new client
             pair.Channel.AddRef();
             return(pair.Channel);
         }
     }
 }
示例#7
0
        public static IServiceCollection AddGrpc(this IServiceCollection services)
        {
            // Channels
            services.RegisterOutputChannel();

            // Internal logging
            services.AddLogging(logging =>
            {
                logging.Services.AddSingleton <ILoggerProvider, GrpcFunctionsHostLoggerProvider>();
                logging.Services.AddSingleton <IWorkerDiagnostics, GrpcWorkerDiagnostics>();
            });

            // gRPC Core services
            services.AddSingleton <IWorker, GrpcWorker>();
            services.AddSingleton <FunctionRpcClient>(p =>
            {
                IOptions <GrpcWorkerStartupOptions> argumentsOptions = p.GetService <IOptions <GrpcWorkerStartupOptions> >()
                                                                       ?? throw new InvalidOperationException("gRPC Serivces are not correctly registered.");

                GrpcWorkerStartupOptions arguments = argumentsOptions.Value;

                GrpcChannel grpcChannel = GrpcChannel.ForAddress($"http://{arguments.Host}:{arguments.Port}", new GrpcChannelOptions()
                {
                    Credentials = ChannelCredentials.Insecure
                });

                return(new FunctionRpcClient(grpcChannel));
            });

            services.AddOptions <GrpcWorkerStartupOptions>()
            .Configure <IConfiguration>((arguments, config) =>
            {
                config.Bind(arguments);
            });

            return(services);
        }
示例#8
0
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            //using var channel = GrpcChannel.ForAddress("https://localhost:5000");


            var client = new  Inventor.InventorClient(channel);

            var NewClient = new CartService.CartServiceClient(channel);

            try
            {
                var reply = await client.SayHelloAsync(
                    new InventorRequest { Name = "InventorRequest" });

                Console.WriteLine("Greeting: " + reply.Message);
            }
            catch
            {
                Console.WriteLine("Error Inventory Client ");
            }
            try
            {
                var reply = NewClient.EmptyCart(
                    new  EmptyCartRequest {
                    UserId = "InventorRequest"
                });
                Console.WriteLine("Greeting: " + reply.ToString());
            }
            catch
            {
                Console.WriteLine("Cart  Client Error ");
            }
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        public CallInvoker CreateCallInvoker(HttpMessageHandler httpHandler, string name, Type type, GrpcClientFactoryOptions clientFactoryOptions)
        {
            if (httpHandler == null)
            {
                throw new ArgumentNullException(nameof(httpHandler));
            }

            var channelOptions = new GrpcChannelOptions();

            channelOptions.HttpHandler   = httpHandler;
            channelOptions.LoggerFactory = _loggerFactory;

            if (clientFactoryOptions.ChannelOptionsActions.Count > 0)
            {
                foreach (var applyOptions in clientFactoryOptions.ChannelOptionsActions)
                {
                    applyOptions(channelOptions);
                }
            }

            var address = clientFactoryOptions.Address;

            if (address == null)
            {
                throw new InvalidOperationException($@"Could not resolve the address for gRPC client '{name}'. Set an address when registering the client: services.AddGrpcClient<{type.Name}>(o => o.Address = new Uri(""https://localhost:5001""))");
            }

            var channel = GrpcChannel.ForAddress(address, channelOptions);

            var httpClientCallInvoker = channel.CreateCallInvoker();

            var resolvedCallInvoker = clientFactoryOptions.Interceptors.Count == 0
                ? httpClientCallInvoker
                : httpClientCallInvoker.Intercept(clientFactoryOptions.Interceptors.ToArray());

            return(resolvedCallInvoker);
        }
示例#10
0
        static async Task Main(string[] args)
        {
            string method = "";

            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Service.ITDS.ITDSClient(channel);

            while (method != "X")
            {
                Console.WriteLine("Choose method [1/2/X]:");
                method = Console.ReadLine();

                if (method == "1")
                {
                    var response = await client.FilterMovieByYearAsync(new MovieByYearRequest
                    {
                        YearLowerBand = 1982,
                        YearUpperBand = 1983
                    });

                    Console.WriteLine(response.Data);
                }
                else if (method == "2")
                {
                    var response = await client.FilterMovieByYearStronglyTypedAsync(new MovieByYearRequest
                    {
                        YearLowerBand = 1982,
                        YearUpperBand = 1983
                    });

                    foreach (var movie in response.Movie)
                    {
                        Console.WriteLine(movie.Title);
                    }
                }
            }
        }
示例#11
0
        public GrpcEngine(string engineAddress)
        {
            // Allow for insecure HTTP/2 transport (only needed for netcoreapp3.x)
            // https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-6.0#call-insecure-grpc-services-with-net-core-client
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            // maxRpcMessageSize raises the gRPC Max Message size from `4194304` (4mb) to `419430400` (400mb)
            const int maxRpcMessageSize = 400 * 1024 * 1024;
            if (_engineChannels.TryGetValue(engineAddress, out var engineChannel))
            {
                // A channel already exists for this address
                this._engine = new Engine.EngineClient(engineChannel);
            }
            else 
            {
                lock (_channelsLock)
                {
                    if (_engineChannels.TryGetValue(engineAddress, out var existingChannel))
                    {
                        // A channel already exists for this address
                        this._engine = new Engine.EngineClient(existingChannel);
                    }
                    else 
                    {
                        // Inititialize the engine channel once for this address
                        var channel = GrpcChannel.ForAddress(new Uri($"http://{engineAddress}"), new GrpcChannelOptions
                        {
                            MaxReceiveMessageSize = maxRpcMessageSize,
                            MaxSendMessageSize = maxRpcMessageSize,
                            Credentials = Grpc.Core.ChannelCredentials.Insecure,
                        });

                        _engineChannels[engineAddress] = channel;
                        this._engine = new Engine.EngineClient(channel);
                    }
                }
            }
        }
示例#12
0
        public async Task SendCompressedMessage_ServiceCompressionConfigured_ResponseGzipEncoding(string algorithmName)
        {
            // Arrange
            var compressionMetadata = CreateClientCompressionMetadata(algorithmName);

            string?requestMessageEncoding  = null;
            string?responseMessageEncoding = null;

            using var httpClient = Fixture.CreateClient(new TestDelegateHandler(
                                                            r =>
            {
                requestMessageEncoding = r.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single();
            },
                                                            r =>
            {
                responseMessageEncoding = r.Headers.GetValues(GrpcProtocolConstants.MessageEncodingHeader).Single();
            }
                                                            ));

            var channel = GrpcChannel.ForAddress(httpClient.BaseAddress, new GrpcChannelOptions
            {
                LoggerFactory = LoggerFactory,
                HttpClient    = httpClient
            });
            var client = new CompressionService.CompressionServiceClient(channel);

            // Act
            var call = client.SayHelloAsync(new HelloRequest {
                Name = "World"
            }, headers: compressionMetadata);
            var response = await call.ResponseAsync.DefaultTimeout();

            // Assert
            Assert.AreEqual("Hello World", response.Message);
            Assert.AreEqual(algorithmName, requestMessageEncoding);
            Assert.AreEqual("gzip", responseMessageEncoding);
        }
示例#13
0
        protected async void AddPhoto()
        {
            Response3         = string.Empty; //清空前台显示
            using var channel = GrpcChannel.ForAddress(ServerAdderss);
            var client = new EmployeeService.EmployeeServiceClient(channel);

            // 调用这个存根方法得到的是“AsyncClientStreamingCall类型”
            using var clientStreamingCall = client.AddPhoto();
            // 拿到“请求流”
            var requestStream = clientStreamingCall.RequestStream;

            //向“请求流”中写数据
            await using var fs = File.OpenRead(Request3);
            while (true)
            {
                var buffer = new byte[1024];                               //模拟多次传递,将缓存设置小一点
                var length = await fs.ReadAsync(buffer, 0, buffer.Length); //将数据读取到buffer中

                if (length == 0)                                           //读取完毕
                {
                    break;                                                 //跳出循环
                }
                else if (length < buffer.Length)                           //最后一次读取长度无法填满buffer的长度
                {
                    Array.Resize(ref buffer, length);                      //改变buffer数组的长度
                }
                var streamData = ByteString.CopyFrom(buffer);              //将byte数组数据转成传递时需要的ByteString类型
                                                                           //将ByteString数据写入“请求流”中
                await requestStream.WriteAsync(new AddPhotoRequest { Photo = streamData });
            }

            await requestStream.CompleteAsync();  //告知服务端数据传递完毕

            var response = await clientStreamingCall.ResponseAsync;

            Response3 = response.IsOK ? "congratulations" : "ah oh"; // 将消息显示到前端
        }
        static async Task Main(string[] args)
        {
            Console.WriteLine("Calling SayHello Endpoint with name: 'World'");

            // The gRPC endpoint set up in our service.
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            // Create a client using the channel
            var client = new Greeter.GreeterClient(channel);

            // CAll the SayHello endpoint
            var helloReply = client.SayHello(new HelloRequest {
                Name = "World"
            });

            Console.WriteLine($"Response from server, '{helloReply.Message}'");

            Console.WriteLine("Calling StreamHello endpoint with name: 'John Doe'");
            // Calling the StreamHello ednpoint and constructing the stream
            using (var streamResponse = client.StreamHello(new HelloRequest {
                Name = "John Doe"
            }))
            {
                Console.WriteLine("Response stream listed here with index of receiving order");
                int i = 1;
                // Keep moving next and print the received character untill end of stream
                while (await streamResponse.ResponseStream.MoveNext(cancellationToken: CancellationToken.None))
                {
                    Console.WriteLine($"[{i:D2}] {streamResponse.ResponseStream.Current.Character}");
                    i++;
                }
            }
            Console.WriteLine("Closing stream resposne");

            // Prevent early exit
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        public CallInvoker CreateCallInvoker(HttpClient httpClient, string name, GrpcClientFactoryOptions clientFactoryOptions)
        {
            if (httpClient == null)
            {
                throw new ArgumentNullException(nameof(httpClient));
            }

            var channelOptions = new GrpcChannelOptions();

            channelOptions.HttpClient    = httpClient;
            channelOptions.LoggerFactory = _loggerFactory;

            if (clientFactoryOptions.ChannelOptionsActions.Count > 0)
            {
                foreach (var applyOptions in clientFactoryOptions.ChannelOptionsActions)
                {
                    applyOptions(channelOptions);
                }
            }

            var address = clientFactoryOptions.Address ?? httpClient.BaseAddress;

            if (address == null)
            {
                throw new InvalidOperationException($"Could not resolve the address for gRPC client '{name}'.");
            }

            var channel = GrpcChannel.ForAddress(address, channelOptions);

            var httpClientCallInvoker = channel.CreateCallInvoker();

            var resolvedCallInvoker = clientFactoryOptions.Interceptors.Count == 0
                ? httpClientCallInvoker
                : httpClientCallInvoker.Intercept(clientFactoryOptions.Interceptors.ToArray());

            return(resolvedCallInvoker);
        }
示例#16
0
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            bool executeInParallel = false;

            if (executeInParallel)
            {
                Task hello      = Hello(channel);
                Task calculator = Calculator(channel);
                Task streaming  = Streaming(channel);
                await Task.WhenAll(hello, calculator, streaming);
            }
            else
            {
                await Hello(channel);
                await Calculator(channel);
                await Streaming(channel);
            }

            Console.WriteLine("-----------------------------");
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
示例#17
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            var httpClientHandler = new HttpClientHandler();
            // Return `true` to allow certificates that are untrusted/invalid
            //httpClientHandler.ServerCertificateCustomValidationCallback =
            //    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var httpClient = new HttpClient(httpClientHandler);

            using var channel = GrpcChannel.ForAddress("http://127.0.0.1:5216", new GrpcChannelOptions
            {
                HttpClient = httpClient
            });

            await Task.Delay(2000);

            var client = new Identity.IdentityClient(channel);

            var info = await client.GetPluginInfoAsync(new GetPluginInfoRequest { });

            Console.WriteLine($"Plugin Name: {info.Name}");
            Console.ReadLine();
        }
示例#18
0
        private static OrderPlacement.OrderPlacementClient GetOrdersClient()
        {
            // Enable when connecting to server without HTTPS. See: https://github.com/aspnet/AspNetCore.Docs/issues/13120#issuecomment-516598055
            // AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            var serverUrl = System.Environment.GetEnvironmentVariable("ORDERS_URL") ?? "https://localhost:5001";

            var handler = new HttpClientHandler();

            if (!serverUrl.Contains("localhost"))
            {
                // NOTE: This is for development purposes only!
                // When running in dev with docker-compose, the address of the server wont be localhost, and so the dev HTTPS cert is invalid
                // This will disable the validation of the HTTPS certificates
                handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            }
            var httpClient = new HttpClient(handler);

            var channel = GrpcChannel.ForAddress(serverUrl, new GrpcChannelOptions {
                HttpClient = httpClient
            });

            return(new OrderPlacement.OrderPlacementClient(channel));
        }
示例#19
0
        public MainForm()
        {
            InitializeComponent();

            Thread.Sleep(5000);

            _draggableBox.Left       = 10;
            _draggableBox.Top        = 10;
            _draggableBox.Width      = 100;
            _draggableBox.Height     = 100;
            _draggableBox.BackColor  = Color.Red;
            _draggableBox.MouseDown += DraggableBox_MouseDown;
            _draggableBox.MouseMove += DraggableBox_MouseMove;
            Controls.Add(_draggableBox);
            Load += MainForm_Load;

            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new Streamer.StreamerClient(channel);

            _duplexStream = client.Do(new CallOptions());
            _duplexStream.RequestStream.WriteAsync(new StreamRequest {
                ClientId = _clientId
            });
        }
        private void ConfigureGrpcConnections(IServiceCollection services)
        {
            var addresses = new EndpointsAddresses();

            Configuration.GetSection("Addresses").Bind(addresses);

            var httpClientHandler = new HttpClientHandler();

            httpClientHandler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            var httpClient      = new HttpClient(httpClientHandler);
            var accountsChannel = GrpcChannel.ForAddress(addresses.Accounts, new GrpcChannelOptions {
                HttpClient = httpClient, MaxReceiveMessageSize = 16 * 1024 * 1024
            });

            services.AddSingleton(new AccountsClient(accountsChannel));

            var transactionsChannel = GrpcChannel.ForAddress(addresses.Transactions, new GrpcChannelOptions {
                HttpClient = httpClient, MaxReceiveMessageSize = 16 * 1024 * 1024
            });

            services.AddSingleton(new TransactionsClient(transactionsChannel));
        }
示例#21
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");

            builder.Services.AddTransient(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            builder.Services.AddSingleton <BlazorClient.Services.ToDoDataService>();

            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var baseUri    = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                // Now we can instantiate gRPC clients for this channel
                return(new Greeter.GreeterClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var baseUri    = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                // Now we can instantiate gRPC clients for this channel
                return(new ToDoGrpcService.ToDoService.ToDoServiceClient(channel));
            });
            await builder.Build().RunAsync();
        }
示例#22
0
        static async Task Main()
        {
            GrpcClientFactory.AllowUnencryptedHttp2 = true;
            using var http = GrpcChannel.ForAddress("http://localhost:10042");
            var calculator = http.CreateGrpcService <ICalculator>();
            var result     = await calculator.MultiplyAsync(new MultiplyRequest { X = 12, Y = 4 });

            Console.WriteLine(result.Result); // 48

            var clock = http.CreateGrpcService <ITimeService>();

            using var cancel = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            var options = new CallOptions(cancellationToken: cancel.Token);

            try
            {
                await foreach (var time in clock.SubscribeAsync(new CallContext(options)))
                {
                    Console.WriteLine($"The time is now: {time.Time}");
                }
            }
            catch (RpcException) { }
            catch (TaskCanceledException) { }
        }
示例#23
0
        public static async Task CallServiceAsync(string urlGrpc, Func <GrpcChannel, Task> func)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);

            var channel = GrpcChannel.ForAddress(urlGrpc);

            Log.Information($"Sending gRPC request to {urlGrpc} , target Url {channel.Target}");

            try
            {
                await func(channel);
            }
            catch (RpcException e)
            {
                Log.Error($"gRPC Calling Error via grpc: {e.Status} - {e.Message}");
                throw new ApiException(e, (int)e.StatusCode);
            }
            finally
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false);
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", false);
            }
        }
示例#24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var httpHandler = new HttpClientHandler();

            httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            GrpcChannel channel = GrpcChannel.ForAddress("https://localhost:5003", new GrpcChannelOptions {
                HttpHandler = httpHandler
            });

            client = new Input.InputClient(channel);

            Timer timer = new Timer(1000);

            timer.Elapsed  += CheckInputs;
            timer.AutoReset = true;
            timer.Enabled   = true;

            Console.WriteLine("Timer started");

            Console.ReadKey();
        }
示例#25
0
        static void TestSequential()
        {
            ClearMinMax();
            if (LogDetails)
            {
                Console.WriteLine($"{DateTime.Now} - Starting {nameof(TestSequential)} {TotalRequests} requests");
            }

            var stopwatch = Stopwatch.StartNew();

            for (int i = 0; i < TotalRequests; i++)
            {
                if (LogDetails)
                {
                    Console.WriteLine($"{DateTime.Now} - Start request {i}");
                }
                var stopwatchRequest = Stopwatch.StartNew();
                using var http = GrpcChannel.ForAddress("http://localhost:10042");
                var calculator = http.CreateGrpcService <ICalculator>();
                var result     = calculator.GetTime();
                stopwatchRequest.Stop();
                CaptureMetrics(stopwatchRequest);
                if (LogDetails)
                {
                    Console.WriteLine($"{DateTime.Now} - End request {i}: {result}");
                }
            }
            stopwatch.Stop();

            if (LogDetails)
            {
                Console.WriteLine($"{DateTime.Now} - {nameof(TestSequential)} for {TotalRequests} requests took: {stopwatch.ElapsedMilliseconds}ms");
            }

            WriteTableRow(nameof(TestSequential), stopwatch);
        }
示例#26
0
        static void TestConcurrentReusingGrpcChannel()
        {
            if (LogDetails)
            {
                Console.WriteLine($"{DateTime.Now} - Starting {nameof(TestConcurrentReusingGrpcChannel)} {TotalRequests} requests");
            }

            using var http = GrpcChannel.ForAddress("http://localhost:10042");
            var calculator = http.CreateGrpcService <ICalculator>();

            var stopwatch = Stopwatch.StartNew();

            Parallel.For(0, TotalRequests, parallelOptions, (i) =>
            {
                if (LogDetails)
                {
                    Console.WriteLine($"{DateTime.Now} - Start request {i}");
                }
                var stopwatchRequest = Stopwatch.StartNew();
                var result           = calculator.GetTime();
                stopwatchRequest.Stop();
                CaptureMetrics(stopwatchRequest);
                if (LogDetails)
                {
                    Console.WriteLine($"{DateTime.Now} - End request {i}: {result}");
                }
            });
            stopwatch.Stop();

            if (LogDetails)
            {
                Console.WriteLine($"{DateTime.Now} - {nameof(TestConcurrentReusingGrpcChannel)} for {TotalRequests} requests took: {stopwatch.ElapsedMilliseconds}ms");
            }

            WriteTableRow(nameof(TestConcurrentReusingGrpcChannel), stopwatch);
        }
示例#27
0
        protected async Task Init(CancellationToken stoppingToken)
        {
            var leader = _cluster.Leader;

            // block until leader is elected
            while (leader == null && !stoppingToken.IsCancellationRequested)
            {
                leader = _cluster.Leader;
                await Task.Delay(1000, stoppingToken);
            }

            if (stoppingToken.IsCancellationRequested)
            {
                return;
            }

            // if we are leader, there's nothing to do
            if (leader != _appConfig.HostName)
            {
                using var channel = GrpcChannel.ForAddress($"http://{leader}:5000");
                var leaderClient = new LeaderClient(channel);

                using var streamingCall = leaderClient.CatchUp(new CatchUpRequest
                {
                    Offset = _storage.LatestOffset
                }, cancellationToken: stoppingToken);

                while (await streamingCall.ResponseStream.MoveNext(stoppingToken))
                {
                    var catchUpData = streamingCall.ResponseStream.Current;
                    _storage.Add(catchUpData.Offset, catchUpData.Message.ToByteArray());
                }

                _storage.Drain();
            }
        }
        public static Channel CreateChannel(this OtlpExporterOptions options)
#endif
        {
            if (options.Endpoint.Scheme != Uri.UriSchemeHttp && options.Endpoint.Scheme != Uri.UriSchemeHttps)
            {
                throw new NotSupportedException($"Endpoint URI scheme ({options.Endpoint.Scheme}) is not supported. Currently only \"http\" and \"https\" are supported.");
            }

#if NETSTANDARD2_1 || NET5_0_OR_GREATER
            return(GrpcChannel.ForAddress(options.Endpoint));
#else
            ChannelCredentials channelCredentials;
            if (options.Endpoint.Scheme == Uri.UriSchemeHttps)
            {
                channelCredentials = new SslCredentials();
            }
            else
            {
                channelCredentials = ChannelCredentials.Insecure;
            }

            return(new Channel(options.Endpoint.Authority, channelCredentials));
#endif
        }
示例#29
0
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new CollegeService.CollegeServiceClient(channel);

            // Retrieve Single Row
            var professorRequest = new GetProfessorRequest {
                ProfessorId = "5ec797ec-da0a-43df-b3a3-3f9a04163656"
            };
            var professor = await client.GetProfessorByIdAsync(professorRequest);

            DisplayProfessorDetails(professor);

            // Retrieve Multiple Rows
            var professors = await client.GetAllProfessorsAsync(new Empty());

            foreach (var prof in professors.Professors)
            {
                DisplayProfessorDetails(prof);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
示例#30
0
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Bookstore.BookstoreClient(channel);

            //add new book
            Console.Write("title: ");
            var title         = Console.ReadLine();
            var bookToBeAdded = new Book()
            {
                Title = title.Trim().Length > 0 ? title : "undefined"
            };
            var response = await client.AddBookAsync(
                new AddBookRequest { Book = bookToBeAdded });

            Console.WriteLine("Adding status: " + response.Status);

            //get books from server
            var responseGetAll = await client.GetAllBooksAsync(new Empty());

            Console.WriteLine("Books from server: " + responseGetAll);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }