Exemplo n.º 1
0
        private void HandleServerCommand(string[] args)
        {
            if (args.Length != 1 + 4)
            {
                this.Form.Error("Server: wrong number of arguments");
                goto ServerUsage;
            }
            string id  = args[1];
            string url = args[2];

            if (!url.StartsWith("http://"))
            {
                goto InvalidURL;
            }

            string[] urlElements = url.Replace("http://", "").Split(":", StringSplitOptions.RemoveEmptyEntries);
            if (urlElements.Length != 2)
            {
                this.Form.Error(urlElements.ToString());
                goto InvalidURL;
            }
            string host = urlElements[0];

            if (!int.TryParse(urlElements[1], out int port))
            {
                goto InvalidPort;
            }
            if (port < 1024 || 65535 < port)
            {
                goto InvalidPort;
            }

            if (!int.TryParse(args[3], out int min_delay) ||
                !int.TryParse(args[4], out int max_delay) ||
                min_delay < 0 ||
                max_delay < 0)
            {
                this.Form.Error("Server: delay arguments must be non negative numbers");
                return;
            }

            if (min_delay > max_delay)
            {
                this.Form.Error("Server: max_delay must be greater or equal than min_delay");
                return;
            }

            if (Servers.ContainsKey(id))
            {
                this.Form.Error($"Server: server {id} already exists");
                return;
            }

            PCSGrpcService.PCSGrpcServiceClient grpcClient;
            if (PCSClients.ContainsKey(host))
            {
                grpcClient = PCSClients[host];
            }
            else
            {
                string      address = "http://" + host + ":" + PCS_PORT;
                GrpcChannel channel = GrpcChannel.ForAddress(address);

                try
                {
                    grpcClient       = new PCSGrpcService.PCSGrpcServiceClient(channel);
                    PCSClients[host] = grpcClient;
                }
                catch (Exception)
                {
                    this.Form.Error("Server: unable to connect to PCS");
                    return;
                }
            }


            if (grpcClient.LaunchServer(new LaunchServerRequest {
                Id = id, Port = port, MinDelay = min_delay, MaxDelay = max_delay
            }).Ok)
            {
                this.Form.Log("Server: successfully launched server at " + host + ":" + port);
            }
            else
            {
                this.Form.Error("Server: failed launching server");
            }

            // register server
            ServerInfo server = new ServerInfo(id, url);

            Servers[id] = server;
            server.Init();

            return;

InvalidPort:
            this.Form.Error("Server: Invalid port number");
            goto ServerUsage;
InvalidURL:
            this.Form.Error("Server: Invalid URL");
            goto ServerUsage;
ServerUsage:
            this.Form.Error("Server usage: Server server_id URL min_delay max_delay");
        }
Exemplo n.º 2
0
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = _configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = _configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = _configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = _configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = _configuration["SSG_USERNAME"];
            string ssgPassword = _configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;



            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });

            /*
             *
             * services.AddHttpClient("Dynamics", c =>
             *  {
             *
             *      c.BaseAddress = new Uri(dynamicsOdataUri);
             *  })
             *  .AddPolicyHandler(GetRetryPolicy())
             *  .AddPolicyHandler(GetCircuitBreakerPolicy());
             *
             * services.AddTransient(new Func<IServiceProvider, IDynamicsClient>((serviceProvider) =>
             * {
             *  var service = serviceProvider.GetRequiredService<System.Net.Http.IHttpClientFactory>();
             *  var httpClient = service.CreateClient("Dynamics");
             *
             *  IDynamicsClient client = new DynamicsClient(httpClient, _configuration);
             *
             *  return client;
             * }));
             */

            services.AddHttpClient <IDynamicsClient, DynamicsClient>();



            // add BCeID Web Services

            string bceidUrl    = _configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = _configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = _configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BC Express Pay (Bambora) service
            services.AddHttpClient <IBCEPService, BCEPService>()
            .AddPolicyHandler(GetRetryPolicy());


            // add the PDF client.
            services.AddHttpClient <IPdfService, PdfService>()
            .AddPolicyHandler(GetRetryPolicy());

            // add the GeoCoder Client.
            services.AddHttpClient <IGeocoderService, GeocoderService>()
            .AddPolicyHandler(GetRetryPolicy());

            // add the file manager.
            string fileManagerURI = _configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest
                {
                    Secret = _configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

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

                    services.AddTransient(_ => new FileManagerClient(channel));
                }
            }
        }
Exemplo n.º 3
0
        public async Task ClientStream_HttpClientWithTimeout_Success()
        {
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "ErrorStartingCall" &&
                    writeContext.Exception is TaskCanceledException)
                {
                    return(true);
                }

                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "GrpcStatusError" &&
                    writeContext.Message == "Call failed with gRPC error status. Status code: 'Cancelled', Message: 'Error starting gRPC call.'.")
                {
                    return(true);
                }

                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "WriteMessageError" &&
                    writeContext.Exception is InvalidOperationException &&
                    writeContext.Exception.Message == "Can't write the message because the call is complete.")
                {
                    return(true);
                }

                if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName)
                {
                    return(true);
                }

                return(false);
            });

            // Arrange
            var data = new byte[1024 * 64]; // 64 KB

            var httpClient = Fixture.CreateClient();

            httpClient.Timeout = TimeSpan.FromSeconds(0.5);

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

            var client      = new StreamService.StreamServiceClient(channel);
            var dataMessage = new DataMessage
            {
                Data = ByteString.CopyFrom(data)
            };

            // Act
            var call = client.ClientStreamedData();

            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(async() =>
            {
                while (true)
                {
                    await call.RequestStream.WriteAsync(dataMessage).DefaultTimeout();

                    await Task.Delay(100);
                }
            }).DefaultTimeout();

            // Assert
            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
            Assert.AreEqual(StatusCode.Cancelled, call.GetStatus().StatusCode);
        }
Exemplo n.º 4
0
        public TradingApi(string address)
        {
            var channel = GrpcChannel.ForAddress(address);

            _client = new TradingService.TradingServiceClient(channel);
        }
Exemplo n.º 5
0
        public async Task Active_UnaryCall_MultipleStreams_UnavailableAddress_FallbackToWorkingAddress()
        {
            // Ignore errors
            SetExpectedErrorsFilter(writeContext =>
            {
                return(true);
            });

            var    tcs  = new TaskCompletionSource <object?>(TaskCreationOptions.RunContinuationsAsynchronously);
            string?host = null;

            async Task <HelloReply> UnaryMethod(HelloRequest request, ServerCallContext context)
            {
                var protocol = context.GetHttpContext().Request.Protocol;

                Logger.LogInformation("Received protocol: " + protocol);

                await tcs.Task;

                host = context.Host;
                return(new HelloReply {
                    Message = request.Name
                });
            }

            // Arrange
            using var endpoint1 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50051, UnaryMethod, nameof(UnaryMethod), HttpProtocols.Http1AndHttp2, isHttps: true);
            using var endpoint2 = BalancerHelpers.CreateGrpcEndpoint <HelloRequest, HelloReply>(50052, UnaryMethod, nameof(UnaryMethod), HttpProtocols.Http1AndHttp2, isHttps: true);

            var services = new ServiceCollection();

            services.AddSingleton <ResolverFactory>(new StaticResolverFactory(_ => new[]
            {
                new BalancerAddress(endpoint1.Address.Host, endpoint1.Address.Port),
                new BalancerAddress(endpoint2.Address.Host, endpoint2.Address.Port)
            }));

            var socketsHttpHandler = new SocketsHttpHandler
            {
                EnableMultipleHttp2Connections = true,
                SslOptions = new System.Net.Security.SslClientAuthenticationOptions()
                {
                    RemoteCertificateValidationCallback = (_, __, ___, ____) => true
                }
            };
            var grpcWebHandler = new GrpcWebHandler(GrpcWebMode.GrpcWeb, new RequestVersionHandler(socketsHttpHandler));
            var channel        = GrpcChannel.ForAddress("static:///localhost", new GrpcChannelOptions
            {
                LoggerFactory   = LoggerFactory,
                HttpHandler     = grpcWebHandler,
                ServiceProvider = services.BuildServiceProvider(),
                Credentials     = new SslCredentials()
            });

            var client = TestClientFactory.Create(channel, endpoint1.Method);

            // Act
            grpcWebHandler.HttpVersion = new Version(1, 1);
            var http11CallTasks = new List <Task <HelloReply> >();

            for (int i = 0; i < 10; i++)
            {
                Logger.LogInformation($"Sending gRPC call {i}");

                http11CallTasks.Add(client.UnaryCall(new HelloRequest {
                    Name = "Balancer"
                }).ResponseAsync);
            }

            Logger.LogInformation($"Done sending gRPC calls");

            var balancer      = BalancerHelpers.GetInnerLoadBalancer <PickFirstBalancer>(channel) !;
            var subchannel    = balancer._subchannel !;
            var transport     = (SocketConnectivitySubchannelTransport)subchannel.Transport;
            var activeStreams = transport.GetActiveStreams();

            // Assert
            Assert.AreEqual(HttpHandlerType.SocketsHttpHandler, channel.HttpHandlerType);

            await TestHelpers.AssertIsTrueRetryAsync(() =>
            {
                activeStreams = transport.GetActiveStreams();
                return(activeStreams.Count == 10);
            }, "Wait for connections to start.");

            foreach (var t in activeStreams)
            {
                Assert.AreEqual(new DnsEndPoint("127.0.0.1", 50051), t.Address.EndPoint);
            }

            // Act
            grpcWebHandler.HttpVersion = new Version(2, 0);
            var http2CallTasks = new List <Task <HelloReply> >();

            for (int i = 0; i < 10; i++)
            {
                Logger.LogInformation($"Sending gRPC call {i}");

                http2CallTasks.Add(client.UnaryCall(new HelloRequest {
                    Name = "Balancer"
                }).ResponseAsync);
            }

            Logger.LogInformation($"Done sending gRPC calls");

            // Assert
            await TestHelpers.AssertIsTrueRetryAsync(() =>
            {
                activeStreams = transport.GetActiveStreams();
                return(activeStreams.Count == 11);
            }, "Wait for connections to start.");

            Assert.AreEqual(new DnsEndPoint("127.0.0.1", 50051), activeStreams[activeStreams.Count - 1].Address.EndPoint);

            tcs.SetResult(null);

            await Task.WhenAll(http11CallTasks).DefaultTimeout();

            await Task.WhenAll(http2CallTasks).DefaultTimeout();

            Assert.AreEqual(ConnectivityState.Ready, channel.State);

            Logger.LogInformation($"Closing {endpoint1}");
            endpoint1.Dispose();

            // There are still be 10 HTTP/1.1 connections because they aren't immediately removed
            // when the server is shutdown and connectivity is lost.
            await TestHelpers.AssertIsTrueRetryAsync(() =>
            {
                activeStreams = transport.GetActiveStreams();
                return(activeStreams.Count == 10);
            }, "Wait for HTTP/2 connection to end.");

            grpcWebHandler.HttpVersion = new Version(1, 1);

            await Task.Delay(1000);

            Logger.LogInformation($"Starting failed call");
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => client.UnaryCall(new HelloRequest {
                Name = "Balancer"
            }).ResponseAsync).DefaultTimeout();

            Assert.AreEqual(StatusCode.Unavailable, ex.StatusCode);

            // Removed by failed call.
            activeStreams = transport.GetActiveStreams();
            Assert.AreEqual(0, activeStreams.Count);
            Assert.AreEqual(ConnectivityState.Idle, channel.State);

            Logger.LogInformation($"Next call goes to fallback address.");
            var reply = await client.UnaryCall(new HelloRequest { Name = "Balancer" }).ResponseAsync.TimeoutAfter(TimeSpan.FromSeconds(20));

            Assert.AreEqual("Balancer", reply.Message);
            Assert.AreEqual("127.0.0.1:50052", host);

            activeStreams = transport.GetActiveStreams();
            Assert.AreEqual(1, activeStreams.Count);
            Assert.AreEqual(new DnsEndPoint("127.0.0.1", 50052), activeStreams[0].Address.EndPoint);
        }
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");
            builder.Services
            .AddBlazorise(options =>
            {
                options.ChangeTextOnKeyPress = true;
            })
            .AddBootstrapProviders()
            .AddFontAwesomeIcons();

            var identityUrl = builder.Configuration.GetSection("IdentityUrl").Value;

            builder.Services.AddHttpClient("CleanArchitecture.Services.Identity.API", client => client.BaseAddress = new Uri(identityUrl))
            .AddHttpMessageHandler <BaseAddressAuthorizationMessageHandler>();

            // Supply HttpClient instances that include access tokens when making requests to the server project
            builder.Services.AddTransient(sp => sp.GetRequiredService <IHttpClientFactory>().CreateClient("CleanArchitecture.Services.Identity.API"));

            builder.Services.AddApiAuthorization(a =>
            {
                a.ProviderOptions.ConfigurationEndpoint = $"{identityUrl}/_configuration/CleanArchitecture.Web.BlazorWebAssembly";
            });



            builder.Services.AddSingleton(services =>
            {
                // Get the service address from appsettings.json
                var config     = services.GetRequiredService <IConfiguration>();
                var catalogUrl = config["CatalogUrl"];

                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new StreamingHttpHandler(new HttpClientHandler())));
                var channel    = GrpcChannel.ForAddress(catalogUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                return(new Product.ProductClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                // Get the service address from appsettings.json
                var config    = services.GetRequiredService <IConfiguration>();
                var basketUrl = config["BasketUrl"];

                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new StreamingHttpHandler(new HttpClientHandler())));
                var channel    = GrpcChannel.ForAddress(basketUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                return(new Basket.BasketClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                // Get the service address from appsettings.json
                var config   = services.GetRequiredService <IConfiguration>();
                var orderUrl = config["OrderUrl"];

                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWebText, new StreamingHttpHandler(new HttpClientHandler())));
                var channel    = GrpcChannel.ForAddress(orderUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                return(new Order.OrderClient(channel));
            });
            builder.Services.AddSingleton <BasketState>();
            var host = builder.Build();

            host.Services
            .UseBootstrapProviders()
            .UseFontAwesomeIcons();
            await host.RunAsync();
        }
Exemplo n.º 7
0
        static async Task Main(string[] args)
        {
            var consumerConfig = new ConsumerConfig
            {
                GroupId          = $"dbserver1.dbo.Person.{Guid.NewGuid():N}.group.id",
                BootstrapServers = "192.168.110.241:9092",
                AutoOffsetReset  = AutoOffsetReset.Earliest,
            };


            using (var c = new ConsumerBuilder <string, string>(consumerConfig).Build())
            {
                c.Subscribe("dbserver1.dbo.Person");
                try
                {
                    while (true)
                    {
                        try
                        {
                            var      cr = c.Consume();
                            var      a  = JsonSerializer.Serialize(cr.Message);
                            Mensagem b  = null;

                            if (cr.Message.Value != null)
                            {
                                b = JsonSerializer.Deserialize <Mensagem>(cr.Message?.Value);
                            }

                            var chave  = JsonSerializer.Deserialize <KeyIndentification>(cr.Key);
                            var offset = cr.TopicPartitionOffset;


                            if (b == null)
                            {
                                Console.WriteLine($"DELETADO - {chave.payload.Id}");
                            }
                            else
                            {
                                if (b.payload?.after != null && b.payload?.before == null)
                                {
                                    using var channel = GrpcChannel.ForAddress("https://localhost:5001");
                                    var tester   = new Tester.TesterClient(channel);
                                    var response = await tester.SalvarUsuarioAsync(
                                        new ModeloRequest
                                    {
                                        Endereco = b.payload?.after.Address,
                                        Id       = b.payload.after.Id,
                                        IntNull  = new Random().Next(1, 10) % 2 == 0 ? b.payload?.after.Id : (int?)null,
                                        Nome     = b.payload?.after.Name,
                                        Telefone = b.payload?.after.Phone,
                                        Obj      = new OutroModelo {
                                            Texto = "texto"
                                        }
                                    }
                                        );

                                    Console.WriteLine($"INCLUSÃO - ID:{b.payload?.after.Id}\nNOME:{b.payload?.after.Name}\nENDERECO:{b.payload?.after.Address}\nTELEFONE:{b.payload?.after.Phone}");
                                }
                                else
                                {
                                    if (b.payload?.after == null)
                                    {
                                        Console.WriteLine($"ALTERAÇÃO - ID:{b.payload?.before.Id}\nNOME:{b.payload?.before.Name}\nENDERECO:{b.payload?.before.Address}\nTELEFONE:{b.payload?.before.Phone}");
                                    }
                                    else
                                    {
                                        Console.WriteLine($"ALTERAÇÃO - ID:{b.payload?.after.Id}\nNOME:{b.payload?.after.Name}\nENDERECO:{b.payload?.after.Address}\nTELEFONE:{b.payload?.after.Phone}");
                                    }
                                }
                            }

                            Console.WriteLine("======================================================== \n");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw e;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapMagicOnionHttpGateway("_", app.ApplicationServices.GetService <MagicOnion.Server.MagicOnionServiceDefinition>().MethodHandlers, GrpcChannel.ForAddress("https://localhost:5001"));
                endpoints.MapMagicOnionSwagger("swagger", app.ApplicationServices.GetService <MagicOnion.Server.MagicOnionServiceDefinition>().MethodHandlers, "/_/");

                endpoints.MapMagicOnionService();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private static async Task MainAsync(string[] args)
        {
            var node = new Node()
            {
                Id               = "sidecar~192.168.0.1~xds.default~default.svc.cluster.local",
                Cluster          = "",
                UserAgentName    = "grpc-dotnet",
                UserAgentVersion = "1.0.0",
                Locality         = new Locality()
                {
                    Region = "local-k8s-cluster",
                    Zone   = "a"
                },
                ClientFeatures = { "envoy.lb.does_not_support_overprovisioning" }
            };
            var serviceName = "outbound|8000||grpc-server.default.svc.cluster.local";

            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            // kubectl port-forward -n istio-system service/istio-pilot 15010:15010
            // https://github.com/grpc/grpc-java/blob/master/xds/src/main/java/io/grpc/xds/XdsClientImpl.java
            var channel = GrpcChannel.ForAddress("http://localhost:15010", new GrpcChannelOptions()
            {
                Credentials = ChannelCredentials.Insecure
            });
            var client     = new AggregatedDiscoveryService.AggregatedDiscoveryServiceClient(channel);
            var connection = client.StreamAggregatedResources();
            // method sendXdsRequest
            await connection.RequestStream.WriteAsync(new DiscoveryRequest()
            {
                TypeUrl       = ADS_TYPE_URL_LDS,
                ResourceNames = { },
                VersionInfo   = string.Empty,
                ResponseNonce = string.Empty,
                Node          = node
            });

            // method onNext
            await connection.ResponseStream.MoveNext(CancellationToken.None);

            // class ListenerResourceFetchTimeoutTask (the same file)
            var discoveryResponse = connection.ResponseStream.Current;

            version = discoveryResponse.VersionInfo;
            nonce   = discoveryResponse.Nonce;
            // method handleLdsResponseForListener
            var listeners      = discoveryResponse.Resources.Select(x => Listener.Parser.ParseFrom(x.Value)).ToList();
            var mylistenerList = listeners.Where(x => x.Address.SocketAddress.PortValue == 8000).ToList();

            if (mylistenerList.Count > 1)
            {
                throw new InvalidOperationException("One listener expected");
            }
            var mylistener = mylistenerList.First();
            //////////////////////////////////////////
            await connection.RequestStream.WriteAsync(new DiscoveryRequest()
            {
                TypeUrl       = ADS_TYPE_URL_RDS,
                ResourceNames = { mylistener.Name },
                VersionInfo   = version,
                ResponseNonce = nonce,
                Node          = node
            });

            await connection.ResponseStream.MoveNext(CancellationToken.None);

            discoveryResponse = connection.ResponseStream.Current;
            version           = discoveryResponse.VersionInfo;
            nonce             = discoveryResponse.Nonce;
            var routeConfigurations = discoveryResponse.Resources.Select(x => RouteConfiguration.Parser.ParseFrom(x.Value))
                                      .ToList();
            //////////////////////////////////////////
            await connection.RequestStream.WriteAsync(new DiscoveryRequest()
            {
                TypeUrl       = ADS_TYPE_URL_CDS,
                ResourceNames = { },
                VersionInfo   = version,
                ResponseNonce = nonce,
                Node          = node
            });

            await connection.ResponseStream.MoveNext(CancellationToken.None);

            discoveryResponse = connection.ResponseStream.Current;
            version           = discoveryResponse.VersionInfo;
            nonce             = discoveryResponse.Nonce;
            var clusters = discoveryResponse.Resources.Select(x => Cluster.Parser.ParseFrom(x.Value))
                           .ToList();
            var cluster = clusters
                          .Where(x => x.Type == Cluster.Types.DiscoveryType.Eds)
                          .Where(x => x?.EdsClusterConfig?.EdsConfig != null)
                          .Where(x => x.LbPolicy == Cluster.Types.LbPolicy.RoundRobin)
                          .Where(x => x?.Name.Contains(serviceName, StringComparison.OrdinalIgnoreCase) ?? false).First();
            //////////////////////////////////////////
            var edsClusterName = cluster.EdsClusterConfig?.ServiceName ?? cluster.Name;
            await connection.RequestStream.WriteAsync(new DiscoveryRequest()
            {
                TypeUrl       = ADS_TYPE_URL_EDS,
                ResourceNames = { edsClusterName },
                VersionInfo   = version,
                ResponseNonce = nonce,
                Node          = node
            });

            await connection.ResponseStream.MoveNext(CancellationToken.None);

            discoveryResponse = connection.ResponseStream.Current;
            version           = discoveryResponse.VersionInfo;
            nonce             = discoveryResponse.Nonce;
            var clusterLoadAssignments = discoveryResponse.Resources.Select(x => ClusterLoadAssignment.Parser.ParseFrom(x.Value))
                                         .ToList();
            var clusterLoadAssignment = clusterLoadAssignments
                                        .Where(x => x.Endpoints.Count != 0)
                                        .Where(x => x.Endpoints[0].LbEndpoints.Count != 0)
                                        .First();

            connection.RequestStream.CompleteAsync().Wait();
            connection.Dispose();
            channel.ShutdownAsync().Wait();
        }
Exemplo n.º 10
0
        static async Task Main(string[] args)
        {
            // DI
            var services = new ServiceCollection();

            var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Debug);
            });

            var serverErrors = new HttpStatusCode[] { 
                HttpStatusCode.BadGateway, 
                HttpStatusCode.GatewayTimeout, 
                HttpStatusCode.ServiceUnavailable, 
                HttpStatusCode.InternalServerError, 
                HttpStatusCode.TooManyRequests, 
                HttpStatusCode.RequestTimeout 
            };

            var gRpcErrors = new StatusCode[] {
                StatusCode.DeadlineExceeded,
                StatusCode.Internal,
                StatusCode.NotFound,
                StatusCode.ResourceExhausted,
                StatusCode.Unavailable,
                StatusCode.Unknown
            };

            Func<HttpRequestMessage, IAsyncPolicy<HttpResponseMessage>> retryFunc = (request) =>
            {
                return Policy.HandleResult<HttpResponseMessage>(r => {
                    
                    var grpcStatus = StatusManager.GetStatusCode(r);
                    var httpStatusCode = r.StatusCode;

                    return (grpcStatus == null && serverErrors.Contains(httpStatusCode)) || // if the server send an error before gRPC pipeline
                           (httpStatusCode == HttpStatusCode.OK && gRpcErrors.Contains(grpcStatus.Value)); // if gRPC pipeline handled the request (gRPC always answers OK)
                })
                .WaitAndRetryAsync(3, (input) => TimeSpan.FromSeconds(3 + input), (result, timeSpan, retryCount, context) =>
                                    {
                                        var grpcStatus = StatusManager.GetStatusCode(result.Result);
                                        Console.WriteLine($"Request failed with {grpcStatus}. Retry");
                                    });
            };

            // https://grpcwebdemo.azurewebsites.net
            // gRPC
            //services.AddGrpcClient<CountryServiceClient>(o =>
            //{
            //    o.Address = new Uri("https://localhost:5001");
            //}).AddPolicyHandler(retryFunc);
            //var provider = services.BuildServiceProvider();
            //var client = provider.GetRequiredService<CountryServiceClient>();


            // gRPC-Web
            var handler = new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler());
            var channel = GrpcChannel.ForAddress("https://grpc-dev-instance.eastus.azurecontainer.io", new GrpcChannelOptions
            {
                HttpClient = new HttpClient(handler),
                LoggerFactory = loggerFactory
            });
            var clientWeb = new CountryServiceClient(channel);


            try
            {
                // Get all gRPC
                var countries = (await clientWeb.GetAllAsync(new EmptyRequest())).Countries.Select(x => new Country
                {
                    CountryId = x.Id,
                    Description = x.Description,
                    CountryName = x.Name
                }).ToList();

                Console.WriteLine("Found countries");
                countries.ForEach(x => Console.WriteLine($"Found country {x.CountryName} ({x.CountryId}) {x.Description}"));


                // Get all gRPC - web
                //var countriesweb = (await clientWeb.GetAllAsync(new EmptyRequest())).Countries.Select(x => new Country
                //{
                //    CountryId = x.Id,
                //    Description = x.Description,
                //    CountryName = x.Name
                //}).ToList();

                //Console.WriteLine("Found countries with gRPC-Web");
                //countriesweb.ForEach(x => Console.WriteLine($"Found country with gRPC-Web:  {x.CountryName} ({x.CountryId}) {x.Description}"));


            }
            catch (RpcException e)
            {
                var errors = e.GetValidationErrors(); // Gets validation errors list
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 11
0
        public async Task RunConsumer()
        {
            var serverAddress = "https://localhost:5000";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // macOS doesn't support ASP.NET Core gRPC with TLS. So we're serving our app on an unsecure endpoint
                // This switch must be set before creating the GrpcChannel/HttpClient.
                // For more information see https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.1
                // 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";
            }

            // The port number(5000) must match the port of the gRPC server.
            var channel = GrpcChannel.ForAddress(serverAddress);
            var client  = new Address.AddressClient(channel);

            StringBuilder sb = new StringBuilder();

            while (true)
            {
                sb.Clear();

                // Our shopper repository contains details of shopper's with IDs ranging from 1-5
                Console.WriteLine("Enter a addressId to search (1, 2 or 3), empty for all, or 0 (zero) to exit");

                string command = Console.ReadLine();

                if (command != "0")
                {
                    var profile = await client.GetAsync(new AddressBookRequest()
                    {
                        Id = command
                    });

                    if (profile != null && profile.People != null)
                    {
                        foreach (Person person in profile.People)
                        {
                            sb.Append("-------------------------------------------------------------------------------");
                            sb.AppendLine();
                            sb.Append("PersonId: " + person.Id + " | Name: " + person.Name + " | Email: " + person.Email);
                            sb.AppendLine();

                            if (person.Phones != null)
                            {
                                foreach (var phone in person.Phones)
                                {
                                    sb.Append("Number: " + phone.Number + " | Type: " + phone.Type.ToString());
                                    sb.AppendLine();
                                }
                            }

                            sb.Append("LastUpdated: " + person.LastUpdated.ToDateTimeOffset());
                            sb.AppendLine();
                            sb.Append("Duration: " + person.Duration.ToTimeSpan());
                            sb.AppendLine();

                            double?doubleTestNullType = person.DoubleTestNullType;
                            float? floaTestNullType   = person.FloaTestNullType;
                            int?   int32TestNullType  = person.Int32TestNullType;
                            long?  int64TestNullType  = person.Int64TestNullType;
                            string stringTestNullType = person.StringTestNullType;

                            sb.Append("-------------------------------------------------------------------------------");
                            sb.AppendLine();
                        }
                    }

                    Console.WriteLine(sb.ToString());
                }
                else
                {
                    break;
                }
            }
        }
Exemplo n.º 12
0
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.

            //var channel = GrpcChannel.ForAddress("https://*****:*****@"ca.crt");
            //var cert = File.ReadAllText(@"client.crt");
            //var key = File.ReadAllText(@"client.key");
            //var keypair = new KeyCertificatePair(cert, key);
            //SslCredentials creds = new SslCredentials(cacert, keypair);

            var channel = GrpcChannel.ForAddress("https://localhost:9000");
            var client  = new XprtService.XprtServiceClient(channel);


            while (true)
            {
                Console.Clear();
                Console.WriteLine("Kies een actie, gevolgd door enter:");
                Console.WriteLine("1: SendMetadataAsync");
                Console.WriteLine("2: GetByBadgeNumber");
                Console.WriteLine("3: GetAll");
                Console.WriteLine("4: AddPhoto");
                Console.WriteLine("5: SaveAll");
                Console.WriteLine("6: EXIT");

                var input = Console.ReadLine();
                try
                {
                    int option = int.Parse(input);

                    switch (option)
                    {
                    case 1:
                        SendMetadataAsync(client).Wait();
                        break;

                    case 2:
                        GetByBadgeNumber(client).Wait();
                        break;

                    case 3:
                        GetAll(client).Wait();
                        break;

                    case 4:
                        AddPhoto(client).Wait();
                        break;

                    case 5:
                        SaveAll(client).Wait();
                        break;

                    case 6:

                        return;

                    default:
                        Console.WriteLine($"Onbekende optie: {option}");
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine("");
                Console.WriteLine("Geef enter om door te gaan.");
                Console.ReadKey();
            }
        }
Exemplo n.º 13
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("http://localhost:5001", new GrpcChannelOptions()
            {
                Credentials = ChannelCredentials.Insecure
            });
            var client = new Messenger.MessengerClient(channel);

            Console.WriteLine("USERNAME:"******"Starting Up, please wait");

            var reply = client.ListRooms(new ListRoomsRequest());

            int attempts = 1;

            var msg = reply.ResponseStream.MoveNext();

            var rooms = new List <AvailableRoom>();

            while (!msg.IsCompleted)
            {
                Console.Clear();
                Console.Write("Starting Up, please wait");
                if (attempts % 2 == 0)
                {
                    Console.WriteLine("...");
                }
                else
                {
                    Console.WriteLine();
                }
                attempts++;
                await Task.Delay(1000);

                if (msg.IsCompleted)
                {
                    if (!msg.Result)
                    {
                        //Finished
                        Console.Clear();
                        Console.WriteLine("Starting Up done!");
                        break;
                    }
                    rooms.Add(reply.ResponseStream.Current);
                    msg = reply.ResponseStream.MoveNext();
                }
            }
            if (rooms.Count == 0)
            {
                Console.WriteLine("No Chat Rooms Yet! Type the new room name and press enter:");
            }
            else
            {
                Console.WriteLine("Please Pick a Room or Type the new room name and press enter:");
                for (int i = 0; i < rooms.Count; i++)
                {
                    Console.WriteLine($"{i + 1}. {rooms[i].RoomName}");
                }
            }
            var choice      = Console.ReadLine();
            int roomChoosen = 0;

            if (!int.TryParse(choice, out roomChoosen))
            {
                roomChoosen = (await client.CreateRoomAsync(new CreateChatRoomRequest()
                {
                    RoomName = choice
                })).RoomId;
            }

            Console.Clear();
            Console.Write(">");

            var chatRoom = client.EnterChatRoom();

            await InitializeChannel(userName, roomChoosen, chatRoom);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            Task.Run(async() =>
            {
                while (await chatRoom.ResponseStream.MoveNext())
                {
                    MessageReceived(chatRoom.ResponseStream.Current);
                }
            });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            while (true)
            {
                var         txt    = Console.ReadLine();
                ChatMessage newMsg = new ChatMessage();
                newMsg.Author        = userName;
                newMsg.Text          = txt;
                newMsg.SystemMessage = false;
                newMsg.RoomId        = roomChoosen;
                newMsg.Timestamp     = DateTime.Now.ToString();
                chatRoom.RequestStream.WriteAsync(newMsg);
                Console.Write(">");
            }
        }
Exemplo n.º 14
0
        private void HandleClientCommand(string[] args)
        {
            if (args.Length != 1 + 3)
            {
                this.Form.Error("Client: wrong number of arguments");
                goto ClientUsage;
            }

            string username   = args[1];
            string url        = args[2];
            string scriptFile = args[3];

            if (Clients.ContainsKey(username))
            {
                this.Form.Error($"Client: client {username} already exists");
                return;
            }

            if (!url.StartsWith("http://"))
            {
                goto InvalidURL;
            }
            string[] urlElements = url.Replace("http://", "").Split(":", StringSplitOptions.RemoveEmptyEntries);
            if (urlElements.Length != 2)
            {
                this.Form.Error(urlElements.ToString());
                goto InvalidURL;
            }
            string host = urlElements[0];

            if (!int.TryParse(urlElements[1], out int port))
            {
                goto InvalidPort;
            }
            if (port < 1024 || 65535 < port)
            {
                goto InvalidPort;
            }

            PCSGrpcService.PCSGrpcServiceClient grpcClient;
            if (PCSClients.ContainsKey(host))
            {
                grpcClient = PCSClients[host];
            }
            else
            {
                try
                {
                    string      address = "http://" + host + ":" + PCS_PORT;
                    GrpcChannel channel = GrpcChannel.ForAddress(address);
                    grpcClient = new PCSGrpcService.PCSGrpcServiceClient(channel);
                }
                catch (Exception)
                {
                    this.Form.Error("Client: unable to connect to PCS");
                    return;
                }
            }

            grpcClient.Ping(new PCSPingRequest());
            int clientId;

            lock (ClientCountLock)
            {
                clientId = ++ClientCount;
            }

            try {
                if (grpcClient.LaunchClient(new LaunchClientRequest {
                    ScriptFile = scriptFile, Port = port, Id = clientId
                }).Ok)
                {
                    this.Form.Log("Client: successfully launched client at " + host);
                }
                else
                {
                    this.Form.Error("Client: failed launching client");
                }
            }
            catch (Exception)
            {
                this.Form.Error("Client: failed sending request to PCS");
            }

            // register client
            GrpcChannel clientChannel = GrpcChannel.ForAddress(url);
            var         clientGrpc    = new PuppetMasterClientGrpcService.PuppetMasterClientGrpcServiceClient(clientChannel);
            ClientInfo  client        = new ClientInfo(username, url, clientGrpc);

            Clients[username] = client;

            client.Init();

            return;

InvalidPort:
            this.Form.Error("Client: Invalid port number");
            goto ClientUsage;
InvalidURL:
            this.Form.Error("Client: Invalid URL");
ClientUsage:
            this.Form.Error("Client usage: Client username client_URL script_file");
        }
Exemplo n.º 15
0
        static async Task Main(string[] args)
        {
            try
            {
                await Task.Delay(1000);

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

                var calc = new Calculator.CalculatorClient(channel);

                var result1 = await client.SayHelloAsync(new HelloRequest
                {
                    Name = "Michael 1"
                });

                Console.WriteLine(result1.Message);
                await Task.Delay(100);

                result1 = await client.SayHelloAsync(new HelloRequest
                {
                    Name = "Michael 2"
                });

                Console.WriteLine(result1.Message);
                await Task.Delay(100);

                var result2 = await client.SayHowdyAsync(new HowdyRequest
                {
                    Name   = "Simon 1",
                    Number = 1
                });

                Console.WriteLine(result2.Message + "-" + result2.Number);
                await Task.Delay(100);

                result2 = await client.SayHowdyAsync(new HowdyRequest
                {
                    Name   = "Simon 2",
                    Number = 1
                });

                Console.WriteLine(result2.Message + "-" + result2.Number);
                await Task.Delay(100);

                await client.AskNothingAsync(new Empty());

                Console.WriteLine("nothing asked");
                await Task.Delay(100);

                await client.SayNothingAsync(new Empty());

                Console.WriteLine("nothing said");
                await Task.Delay(100);

                await client.SayRandomAsync(new Empty());

                Console.WriteLine("something random said");
                await Task.Delay(100);

                await client.SayOneAsync(new OneCommand { One = "Eins" });

                Console.WriteLine("One said");
                await Task.Delay(100);

                await client.SayTwoAsync(new Empty());

                Console.WriteLine("Two said");
                await Task.Delay(100);

                var calcResult = await calc.AddAsync(new AddRequest { A = 2, B = 3 });

                Console.WriteLine("Added: " + calcResult.Res);
                await Task.Delay(100);

                await client.DuplicateAsync(new Empty());

                Console.WriteLine("DuplicateAsync for greeter called");
                await Task.Delay(100);

                await calc.DuplicateAsync(new Empty());

                Console.WriteLine("DuplicateAsync for calc called");
                await Task.Delay(100);

                var stwCall = client.SentenceToWords(new SentenceMessage {
                    Sentence = "This is a fine sentence."
                });
                await foreach (var word in stwCall.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine($"Received word: <{word.Word}>");
                }

                var clientStream = client.WordsToSentence();
                await clientStream.RequestStream.WriteAsync(new WordMessage { Word = "Sending" });

                await Task.Delay(100);

                await clientStream.RequestStream.WriteAsync(new WordMessage { Word = "words" });

                await Task.Delay(100);

                await clientStream.RequestStream.WriteAsync(new WordMessage { Word = "one" });

                await Task.Delay(100);

                await clientStream.RequestStream.WriteAsync(new WordMessage { Word = "by" });

                await Task.Delay(100);

                await clientStream.RequestStream.WriteAsync(new WordMessage { Word = "one" });

                await Task.Delay(100);

                await clientStream.RequestStream.CompleteAsync();

                await Task.Delay(100);

                var sentence = await clientStream.ResponseAsync;
                Console.WriteLine($"WordsToSentence resulted in '{sentence.Sentence}'");

                // bidi stream
                var reverseStream = client.ReverseWords();
                await reverseStream.RequestStream.WriteAsync(new WordMessage { Word = "Sending" });

                await reverseStream.ResponseStream.MoveNext();

                var w = reverseStream.ResponseStream.Current;
                Console.WriteLine($"Reversed: {w.Word}");
                await Task.Delay(100);

                await reverseStream.RequestStream.WriteAsync(new WordMessage { Word = "Words" });

                await reverseStream.ResponseStream.MoveNext();

                w = reverseStream.ResponseStream.Current;
                Console.WriteLine($"Reversed: {w.Word}");
                await Task.Delay(100);

                await reverseStream.RequestStream.WriteAsync(new WordMessage { Word = "for" });

                await reverseStream.ResponseStream.MoveNext();

                w = reverseStream.ResponseStream.Current;
                Console.WriteLine($"Reversed: {w.Word}");
                await Task.Delay(100);

                await reverseStream.RequestStream.WriteAsync(new WordMessage { Word = "reversing!" });

                await reverseStream.ResponseStream.MoveNext();

                w = reverseStream.ResponseStream.Current;
                Console.WriteLine($"Reversed: {w.Word}");
                await Task.Delay(100);

                await reverseStream.RequestStream.CompleteAsync();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("Press Enter");
                Console.ReadLine();
            }
        }
Exemplo n.º 16
0
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new GRPCXemo.GRPCXemoClient(channel);
            int devId  = 0;

            try
            {
                Report.Notify(new Message(Codes.INFO_XM_GRPC_CLNT_INIT));
                // The port number(5001) must match the port of the gRPC server.
                devId = int.Parse(args[0]);

                if (devId == 0)
                {
                    throw new ArgumentException("Wrong device serial number!");
                }

                using (var sc = new SampleChanger(devId))
                {
                    var ctinit = new CancellationTokenSource(TimeSpan.FromSeconds(90));

                    await sc.HomeAsync(ctinit.Token);

                    var ct = new CancellationTokenSource();
                    Report.Notify(new Message(Codes.INFO_XM_GRPC_CLNT_IN_HOME));

                    var stopMeas = false;

                    while (!stopMeas)
                    {
                        Report.Notify(new Message(Codes.INFO_XM_GRPC_CLNT_IN_RUN_CYCL));

                        var ts = await client.DeviceIsReadyAsync(new DeviceIsReadyRequest { DevId = devId, IsReady = true });

                        await client.SampleInCellAsync(new SampleInCellRequest { DevId = devId, IsInCell = false });

                        await sc.TakeSampleFromTheCellAsync((short)ts.CellNum, ct.Token);

                        var gotodeth = await client.SampleHasTakenAsync(new SampleHasTakenRequest { DevId = devId, IsTaken = true });

                        await sc.PutSampleAboveDetectorWithHeightAsync(HH[gotodeth.H], ct.Token);

                        var takeSample1 = await client.SampleAboveDetectorAsync(new SampleAboveDetectorRequest { DevId = devId, IsAbove = true });

                        var isMeasDone = false;

                        Report.Notify(new Message(Codes.INFO_XM_GRPC_CLNT_WAIT_MEAS));
                        do
                        {
                            var measStatus = await client.IsMeasurementsDoneAsync(new IsMeasurementsDoneRequest { DevId = devId });

                            isMeasDone = measStatus.IsDone;
                            await Task.Delay(TimeSpan.FromSeconds(2));
                        }while (!isMeasDone);

                        Report.Notify(new Message(Codes.INFO_XM_GRPC_CLNT_MEAS_DONE));

                        var takeSample2 = await client.SampleAboveDetectorAsync(new SampleAboveDetectorRequest { DevId = devId, IsAbove = false });

                        await sc.PutSampleToTheDiskAsync((short)ts.CellNum, ct.Token);

                        var tsNext = await client.SampleInCellAsync(new SampleInCellRequest { DevId = devId, IsInCell = true });

                        var isLastMeasReply = await client.IsLastMeasurementAsync(new IsLastMeasurementRequest { DevId = devId });

                        stopMeas = isLastMeasReply.IsLast;
                    }

                    await sc.HomeAsync(ct.Token);

                    // NOTE: In order to not close main thread after await!
                    Console.WriteLine("Push any key to exit...");
                    Console.ReadKey();
                } // using (var sc = new SampleChanger(devId))
            }
            catch (TaskCanceledException)
            {
                Report.Notify(new Message(Codes.ERR_XM_GRPC_CLNT_DEV_NOT_ANS)
                {
                    DetailedText = $"Device '{devId}' do not answer. XemoClient will be rerun."
                });
                Shell.StartProcess("XemoClient.exe", devId.ToString());
            }
            catch (Exception ex)
            {
                await client.DeviceErrorAsync(new ErrorOccurredRequest { DevId = devId });

                Report.Notify(new Message(Codes.ERR_XM_GRPC_CLNT_UNREG)
                {
                    DetailedText = ex.Message
                });
            }
        }
Exemplo n.º 17
0
 public static CallInvoker Client(string baseUrl, GrpcClientConfig config = null) =>
 GrpcChannel.ForAddress(baseUrl).ForServiceStack(config);
Exemplo n.º 18
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            using var channel = GrpcChannel.ForAddress($"http://{GetLocalIp()}:5001");
            var client = new Greeter.GreeterClient(channel);

            // for Uniary call

            /*
             * var reply = await client.SayHelloAsync(
             *  new HelloRequest{
             *      Name = "Client"
             *  }
             * );
             */

            // server streaming

            using var call = client.SayHelloServerStream(
                      new HelloRequest { Name = "Shorotshishir" }
                      );
            while (await call.ResponseStream.MoveNext())
            {
                Console.WriteLine($"Greetings {call.ResponseStream.Current.Message}");
            }


            // client streaming

            /* using var call = client.SayHello();
             * for (int i = 0; i < 5; i++)
             * {
             *  await call.RequestStream.WriteAsync(
             *      new HelloRequest {
             *          Name = "Shorotshishir"
             *      }
             *  );
             * }
             * await call.RequestStream.CompleteAsync();
             * var response = await call;
             * System.Console.WriteLine($" Did you receive ? {response.Message}");
             */

            // Bi directional

            /*
             * using var call = client.SayHello();
             * var readTask = Task.Run(async ()=> {
             *  while(await call.ResponseStream.MoveNext()){
             *      System.Console.WriteLine($"Server Stream: {call.ResponseStream.Current.Message}");
             *  }
             * });
             *
             * for (int i = 0; i < 5; i++)
             * {
             *  await call.RequestStream.WriteAsync(
             *      new HelloRequest {
             *          Name = "Shorotshishir"
             *      }
             *  );
             * }
             */

            Console.WriteLine("Press any key to exit...");
            // Console.ReadKey();
        }
Exemplo n.º 19
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            using var channel = GrpcChannel.ForAddress("http://localhost:5000");
            var client = new StockMarketServiceClient(channel);

            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            using var stockStreamService = client.GetStockStream();

            var responseProcessing = Task.Run(async() =>
            {
                try
                {
                    await foreach (var stockReply in stockStreamService.ResponseStream.ReadAllAsync())
                    {
                        PrintStockInfo(stockReply);
                    }
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
                {
                    Console.WriteLine("Stream cancelled.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error reading response: " + ex);
                }
            });

            var datesUtc = Dates.Select(datesUtc => datesUtc.ToUniversalTime()).ToArray();

            for (int i = 0; i < 5; i++)
            {
                foreach (var symbol in new[] { "AAPL", "AMZN", "FB", "GOOG", "MSFT" })
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Requesting stock info for {symbol}...");
                    Console.ResetColor();

                    int index = rnd.Next(Dates.Count);
                    var date  = datesUtc[index].ToTimestamp();
                    Console.WriteLine(
                        $"Requesting Stock {symbol} history for date {date.ToDateTime().ToString("MM/dd/yyyy")}...");

                    await stockStreamService.RequestStream.WriteAsync(new StockRequest
                    {
                        Symbol = symbol,
                        Date   = date
                    });

                    await Task.Delay(1500); // simulate delay getting next item
                }
            }

            Console.WriteLine("Completing request stream");

            await stockStreamService.RequestStream.CompleteAsync();

            Console.WriteLine("Request stream completed");

            await responseProcessing;

            Console.WriteLine("Read all responses");
            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
Exemplo n.º 20
0
 public GrpcServiceProvider()
 {
     this.Url        = "https://localhost:5001";
     this.RpcChannel = new Lazy <GrpcChannel>(GrpcChannel.ForAddress(this.Url));
 }
Exemplo n.º 21
0
 // Método para atribuir um valor ao field ServerAddress, que é usado para iniciar os channels das conexões GRPC
 public static void SetConnectionChannel(string address)
 {
     ConnectionChannel = GrpcChannel.ForAddress(address);
 }
Exemplo n.º 22
0
        /// <summary>
        /// 设备报警
        /// </summary>
        /// <param name="alarm"></param>
        internal void OnAlarmReceived(Alarm alarm)
        {
            try
            {
                //logger.Debug("OnAlarmReceived started.");
                Event.Alarm alm = new Event.Alarm();
                alm.AlarmType = alm.AlarmType = Event.Alarm.Types.AlarmType.CrossingLine;
                //switch (alarm.AlarmMethod)
                //{
                //    case "1":
                //        break;
                //    case "2":
                //        alm.AlarmType = Event.Alarm.Types.AlarmType.AlarmOutput;
                //        break;
                //}
                alm.Detail = alarm.AlarmDescription ?? string.Empty;
                //alm.DeviceID = alarm.DeviceID;//dms deviceid
                //alm.DeviceName = alarm.DeviceID;//dms name

                //devicemanagementservice 是预留的服务标识(暂命名为设备管理服务).目前没有这个服务.
                //需要你的微服务架构中实现一个设备资产以及一个配置管理服务(或者二合一的资源管服务)
                //以达到两个目的:1、用来为当前GB服务提供启动配置,2、为GB收到注册的设备/平台信息,提供全平台的统一的存储服务.
                string GBServerChannelAddress = EnvironmentVariables.DeviceManagementServiceAddress ?? "devicemanagementservice:8080";
                logger.Debug("Device Management Service Address: " + GBServerChannelAddress);
                var channel = GrpcChannel.ForAddress(GBServerChannelAddress);
                var client  = new DevicesManager.DevicesManagerClient(channel);
                var _rep    = new QueryGBDeviceByGBIDsResponse();
                var req     = new QueryGBDeviceByGBIDsRequest();
                logger.Debug("OnAlarmReceived Alarm: " + JsonConvert.SerializeObject(alarm));
                req.GbIds.Add(alarm.DeviceID);
                _rep = client.QueryGBDeviceByGBIDs(req);
                if (_rep.Devices != null && _rep.Devices.Count > 0)
                {
                    alm.DeviceID   = _rep.Devices[0].GBID;
                    alm.DeviceName = _rep.Devices[0].Name;
                }
                else
                {
                    logger.Debug("QueryGBDeviceByGBIDsResponse Devices.Count: " + _rep.Devices.Count);
                }
                logger.Debug("QueryGBDeviceByGBIDsRequest-Alarm .Devices: " + _rep.Devices[0].ToString());
                UInt64 timeStamp = (UInt64)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
                alm.EndTime   = timeStamp;
                alm.StartTime = timeStamp;

                Message message = new Message();
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("Content-Type", "application/octet-stream");
                message.Header = dic;
                message.Body   = alm.ToByteArray();

                byte[] payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
                string subject = Event.AlarmTopic.OriginalAlarmTopic.ToString();//"OriginalAlarmTopic"
                #region
                Options opts = ConnectionFactory.GetDefaultOptions();
                opts.Url = EnvironmentVariables.GBNatsChannelAddress ?? Defaults.Url;
                logger.Debug("GB Nats Channel Address: " + opts.Url);
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    c.Publish(subject, payload);
                    c.Flush();
                    logger.Debug("Device alarm created connection and published.");
                }
                #endregion

                new Action(() =>
                {
                    logger.Debug("OnAlarmReceived AlarmResponse: " + alm.ToString());

                    _sipCoreMessageService.NodeMonitorService[alarm.DeviceID].AlarmResponse(alarm);
                }).Invoke();
            }
            catch (Exception ex)
            {
                logger.Error("OnAlarmReceived Exception: " + ex.Message);
            }
        }
Exemplo n.º 23
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

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

            // Add the Telerik components
            builder.Services.AddTelerikBlazor();

            // Add the Grpc channels
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.EventService.EventServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.CauseService.CauseServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.ClassService.ClassServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.ExcludeService.ExcludeServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.EffectService.EffectServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.UserService.UserServiceClient(channel));
            });
            builder.Services.AddSingleton(services =>
            {
                var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
                var backendUrl = services.GetRequiredService <NavigationManager>().BaseUri;
                var channel    = GrpcChannel.ForAddress(backendUrl, new GrpcChannelOptions {
                    HttpClient = httpClient
                });
                return(new Causality.Shared.Models.MetaService.MetaServiceClient(channel));
            });

            // Add http client
            builder.Services.AddScoped(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            // Add localstorage nuget
            builder.Services.AddBlazoredLocalStorage();

            // Add onlinestate nuget
            builder.Services.AddTransient <OnlineStateService>();

            // Add and Init indexedDB nuget
            builder.Services.AddIndexedDB(dbStore =>
            {
                dbStore.DbName  = "Causality";
                dbStore.Version = 1;

                dbStore.Stores.Add(new StoreSchema
                {
                    Name       = "Blobs",
                    PrimaryKey = new IndexSpec {
                        Name = "id", KeyPath = "id", Auto = true
                    },
                    Indexes = new List <IndexSpec>
                    {
                        new IndexSpec {
                            Name = "key", KeyPath = "key", Auto = false
                        },
                        new IndexSpec {
                            Name = "value", KeyPath = "value", Auto = false
                        }
                    }
                });

                dbStore.Stores.Add(new StoreSchema
                {
                    Name       = "Outbox",
                    PrimaryKey = new IndexSpec {
                        Auto = true
                    }
                });
            });

            // Add the stateobject
            builder.Services.AddScoped <ApplicationState>();

            // Add the data services
            builder.Services.AddTransient <EventService>();
            builder.Services.AddTransient <CauseService>();
            builder.Services.AddTransient <ClassService>();
            builder.Services.AddTransient <ExcludeService>();
            builder.Services.AddTransient <EffectService>();
            builder.Services.AddTransient <UserService>();
            builder.Services.AddTransient <MetaService>();

            await builder.Build().RunAsync();
        }
Exemplo n.º 24
0
        /// <summary>
        /// 设备状态上报
        /// </summary>
        internal void DeviceStatusReport()
        {
            //logger.Debug("DeviceStatusReport started.");
            // var pre = new TimeSpan(DateTime.Now.Ticks);
            while (true)
            {
                //report status every 8 seconds
                System.Threading.Thread.Sleep(8000);
                try
                {
                    foreach (string deviceid in _sipCoreMessageService.NodeMonitorService.Keys)
                    {
                        //if not device then skip
                        if (!DevType.GetCataType(deviceid).Equals(DevCataType.Device))
                        {
                            continue;
                        }

                        Event.Status stat = new Event.Status();
                        stat.Status_      = false;
                        stat.OccurredTime = (UInt64)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
                        #region waiting DeviceStatuses add in for 500 Milliseconds
                        _sipCoreMessageService.DeviceStateQuery(deviceid);
                        TimeSpan t1 = new TimeSpan(DateTime.Now.Ticks);
                        while (true)
                        {
                            System.Threading.Thread.Sleep(100);
                            TimeSpan t2 = new TimeSpan(DateTime.Now.Ticks);
                            if (DeviceStatuses.ContainsKey(deviceid))
                            {
                                //on line
                                stat.Status_ = DeviceStatuses[deviceid].Status.Equals("ON") ? true : false;
                                //logger.Debug("Device status of [" + deviceid + "]: " + DeviceStatuses[deviceid].Status);
                                DeviceStatuses.Remove(deviceid);
                                break;
                            }
                            else if (t2.Subtract(t1).Duration().Milliseconds > 500)
                            {
                                //off line
                                //logger.Debug("Device status of [" + deviceid + "]: OFF");
                                break;
                            }
                        }
                        #endregion
                        //devicemanagementservice 是预留的服务标识(暂命名为设备管理服务).目前没有这个服务.
                        //需要你的微服务架构中实现一个设备资产以及一个配置管理服务(或者二合一的资源管服务)
                        //以达到两个目的:1、用来为当前GB服务提供启动配置,2、为GB收到注册的设备/平台信息,提供全平台的统一的存储服务.
                        string GBServerChannelAddress = EnvironmentVariables.DeviceManagementServiceAddress ?? "devicemanagementservice:8080";
                        var    channel = GrpcChannel.ForAddress(GBServerChannelAddress); // ChannelCredentials.Insecure);
                        var    client  = new DevicesManager.DevicesManagerClient(channel);
                        QueryGBDeviceByGBIDsResponse rep = new QueryGBDeviceByGBIDsResponse();
                        QueryGBDeviceByGBIDsRequest  req = new QueryGBDeviceByGBIDsRequest();
                        req.GbIds.Add(deviceid);
                        rep = client.QueryGBDeviceByGBIDs(req);
                        if (rep.Devices != null && rep.Devices.Count > 0)
                        {
                            stat.DeviceID   = rep.Devices[0].Guid;
                            stat.DeviceName = rep.Devices[0].Name;

                            Message message = new Message();
                            Dictionary <string, string> dic = new Dictionary <string, string>();
                            dic.Add("Content-Type", "application/octet-stream");
                            message.Header = dic;
                            message.Body   = stat.ToByteArray();
                            byte[] payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
                            string subject = Event.StatusTopic.OriginalStatusTopic.ToString();
                            #region
                            Options opts = ConnectionFactory.GetDefaultOptions();
                            opts.Url            = EnvironmentVariables.GBNatsChannelAddress ?? Defaults.Url;
                            using IConnection c = new ConnectionFactory().CreateConnection(opts);
                            c.Publish(subject, payload);
                            c.Flush();
                            #endregion
                        }
                        else
                        {
                            logger.Debug("QueryGBDeviceByGBIDsRequest: Devices[" + deviceid + "] can't be found in database");
                            continue;
                        }
                        //logger.Debug("QueryGBDeviceByGBIDsRequest-Status .Devices: " + rep.Devices[0].ToString());
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("DeviceStatusReport Exception: " + ex.Message);
                }
            }
        }
Exemplo n.º 25
0
 public Connection(string address, string topic)
 {
     Address = address;
     Topic   = topic;
     Channel = GrpcChannel.ForAddress(address);
 }
Exemplo n.º 26
0
        private void DeviceDmsRegister(SIPTransaction sipTransaction, string gbname)
        {
            try
            {
                //Device insert into database
                Device     _device    = new Device();
                SIPRequest sipRequest = sipTransaction.TransactionRequest;
                _device.Guid = Guid.NewGuid().ToString();
                _device.IP   = sipTransaction.TransactionRequest.RemoteSIPEndPoint.Address.ToString();//IPC
                _device.Name = gbname;
                _device.LoginUser.Add(new LoginUser()
                {
                    LoginName = _SIPAccount.SIPUsername ?? "admin", LoginPwd = _SIPAccount.SIPPassword ?? "123456"
                });                                                                                                //same to GB config service
                _device.Port         = Convert.ToUInt32(sipTransaction.TransactionRequest.RemoteSIPEndPoint.Port); //5060
                _device.GBID         = sipTransaction.TransactionRequestFrom.URI.User;                             //42010000001180000184
                _device.PtzType      = 0;
                _device.ProtocolType = 0;
                _device.ShapeType    = ShapeType.Dome;
                //var options = new List<ChannelOption> { new ChannelOption(ChannelOptions.MaxMessageLength, int.MaxValue) };

                //devicemanagementservice 是预留的服务标识(暂命名为设备管理服务).目前没有这个服务.
                //需要你的微服务架构中实现一个设备资产以及一个配置管理服务(或者二合一的资源管服务)
                //以达到两个目的:1、用来为当前GB服务提供启动配置,2、为GB收到注册的设备/平台信息,提供全平台的统一的存储服务.
                var channel = GrpcChannel.ForAddress(EnvironmentVariables.DeviceManagementServiceAddress ?? "devicemanagementservice:8080"); //, ChannelCredentials.Insecure);
                logger.Debug("Device Management Service Address: " + (EnvironmentVariables.DeviceManagementServiceAddress ?? "devicemanagementservice:8080"));
                var client = new DevicesManager.DevicesManagerClient(channel);
                //if (!_sipCoreMessageService.NodeMonitorService.ContainsKey(_device.GBID))
                //{
                //    AddDeviceRequest _AddDeviceRequest = new AddDeviceRequest();
                //    _AddDeviceRequest.Device.Add(_device);
                //    _AddDeviceRequest.LoginRoleId = "XXXX";
                //    var reply = client.AddDevice(_AddDeviceRequest);
                //    if (reply.Status == OP_RESULT_STATUS.OpSuccess)
                //    {
                //        logger.Debug("Device[" + sipTransaction.TransactionRequest.RemoteSIPEndPoint + "] have added registering DMS service.");
                //        DeviceEditEvent(_device.GBID, "add");
                //    }
                //    else
                //    {
                //        logger.Error("_sipRegistrarCore_RPCDmsRegisterReceived.AddDevice: " + reply.Status.ToString());
                //    }
                //}
                //else
                //{
                //    UpdateDeviceRequest _UpdateDeviceRequest = new UpdateDeviceRequest();
                //    _UpdateDeviceRequest.DeviceItem.Add(_device);
                //    _UpdateDeviceRequest.LoginRoleId = "XXXX";
                //    var reply = client.UpdateDevice(_UpdateDeviceRequest);
                //    if (reply.Status == OP_RESULT_STATUS.OpSuccess)
                //    {
                //        logger.Debug("Device[" + sipTransaction.TransactionRequest.RemoteSIPEndPoint + "] have updated registering DMS service.");
                //    }
                //    else
                //    {
                //        logger.Error("_sipRegistrarCore_RPCDmsRegisterReceived.UpdateDevice: " + reply.Status.ToString());
                //    }
                //}

                //add & update device
                AddDeviceRequest _AddDeviceRequest = new AddDeviceRequest();
                _AddDeviceRequest.Device.Add(_device);
                _AddDeviceRequest.LoginRoleId = "XXXX";
                var reply = client.AddDevice(_AddDeviceRequest);
                if (reply.Status == OP_RESULT_STATUS.OpSuccess)
                {
                    logger.Debug("Device added into DMS service: " + JsonConvert.SerializeObject(_device));
                }
                else
                {
                    logger.Warn("DeviceDmsRegister.AddDevice: " + reply.Status.ToString());
                }
            }
            catch (Exception ex)
            {
                logger.Error("DeviceDmsRegister Exception: " + ex.Message);
            }
        }
Exemplo n.º 27
0
        static async Task Main()
        {
            // This switch must be set before creating the GrpcChannel/HttpClient.
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            // using (var channel = GrpcChannel.ForAddress("http://*****:*****@"{countryData.CountryFull}
                                                                            {countryData.Message}
                                                                            with {countryData.Players.Count} registered players");
                    }
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
                {
                    Console.WriteLine("Stream cancelled.");
                }

                var aCountry = await client.GetCountryAsync(new CountryRequest { Country = "Italy" });

                Console.WriteLine($"Seeking Italy; Found {aCountry.ToString()}");

                aCountry = await client.GetCountryAsync(new CountryRequest { Country = "No Country" });

                Console.WriteLine($"Seeking non existent country; Found {aCountry.ToString()}");

                #endregion


                #region Consume Players
                var playersClient = new PlayerDirectoryClient(channel);
                var playerCts     = new CancellationTokenSource(TimeSpan.FromSeconds(10));
                using (var playersStreamingCall = playersClient.GetPlayers(new Empty(), cancellationToken: playerCts.Token))
                {
                    try
                    {
                        await foreach (PlayersReply playerData in playersStreamingCall.ResponseStream.ReadAllAsync())
                        {
                            Console.WriteLine($@"{playerData.Message}
                            {playerData.Players.ToString()}");
                        }
                    }
                    catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
                    {
                        Console.WriteLine("Stream cancelled.");
                    }
                }

                PlayerReply aPlayer = await playersClient.GetPlayerAsync(new PlayerRequest { Name = "Hasan Sukur", Country = "Turkey" });

                Console.WriteLine($"Should have found: {aPlayer.ToString()}");


                PlayerReply notFound = await playersClient.GetPlayerAsync(new PlayerRequest { Name = "Idiakose O. Sunday" });

                Console.WriteLine($"Should have found me. Hehehehhe: {notFound.ToString()}");

                #endregion
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public EmailClient()
     : this(GrpcChannel.ForAddress("https://localhost:5003"))
 {
 }
Exemplo n.º 29
0
    public async Task <IActionResult> Services()
    {
        try
        {
            HttpClient client = clientFactory.CreateClient(
                name: "Northwind.OData");

            HttpRequestMessage request = new(
                method : HttpMethod.Get, requestUri :
                "catalog/products/?$filter=startswith(ProductName, 'Cha')&$select=ProductId,ProductName,UnitPrice");

            HttpResponseMessage response = await client.SendAsync(request);

            ViewData["productsCha"] = (await response.Content
                                       .ReadFromJsonAsync <ODataProducts>())?.Value;
        }
        catch (Exception ex)
        {
            _logger.LogWarning($"Northwind.OData service exception: {ex.Message}");
        }

        try
        {
            HttpClient client = clientFactory.CreateClient(
                name: "Northwind.GraphQL");

            HttpRequestMessage request = new(
                method : HttpMethod.Post, requestUri : "graphql");

            request.Content = new StringContent(content: @"
        query {
          products (categoryId: 8) {
            productId
            productName
            unitsInStock
          }
        }",
                                                encoding: Encoding.UTF8,
                                                mediaType: "application/graphql");

            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                ViewData["seafoodProducts"] = (await response.Content
                                               .ReadFromJsonAsync <GraphQLProducts>())?.Data?.Products;
            }
            else
            {
                ViewData["seafoodProducts"] = Enumerable.Empty <Product>().ToArray();
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning($"Northwind.GraphQL service exception: {ex.Message}");
        }

        try
        {
            using (GrpcChannel channel =
                       GrpcChannel.ForAddress("https://localhost:5006"))
            {
                Greeter.GreeterClient greeter = new(channel);
                HelloReply            reply   = await greeter.SayHelloAsync(
                    new HelloRequest { Name = "Henrietta" });

                ViewData["greeting"] = "Greeting from gRPC service: " + reply.Message;
            }
        }
        catch (Exception)
        {
            _logger.LogWarning($"Northwind.gRPC service is not responding.");
        }

        try
        {
            using (GrpcChannel channel =
                       GrpcChannel.ForAddress("https://localhost:5006"))
            {
                Shipr.ShiprClient shipr = new(channel);

                ShipperReply reply = await shipr.GetShipperAsync(
                    new ShipperRequest { ShipperId = 3 });

                ViewData["shipr"] = new Shipper
                {
                    ShipperId   = reply.ShipperId,
                    CompanyName = reply.CompanyName,
                    Phone       = reply.Phone
                };
            }
        }
        catch (Exception)
        {
            _logger.LogWarning($"Northwind.gRPC service is not responding.");
        }

        return(View());
    }
        static async Task Main(string[] args)
        {
            Console.Title           = "gRPC Baseball Predictions Client";
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Starting the gRPC Baseball Predictions Client.");
            Console.WriteLine();

            // Retrieve Sample Baseball Data
            var mlbBaseballPlayerBatters = await BaseballData.GetSampleBaseballData();

            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var baseBallPredictionClient = new BaseballBatterPrediction.BaseballBatterPredictionClient(channel);

            foreach (var mlbBaseballPlayerBatter in mlbBaseballPlayerBatters)
            {
                // Slow down predictions, to see a better representation on the Console program
                // Note: You would remove this in a real-world implementation
                await Task.Delay(600);

                // OnHallOfFameBallot Prediction
                var baseBallPredictionRequest = new MLBBaseballBatterPredictionRequest {
                    PredictionID            = Guid.NewGuid().ToString(),
                    PredictionType          = PredictionType.OnHallOfFameBallot,
                    AlgorithmName           = AlgorithmName.StochasticGradientDescentCalibrated,
                    UseEnsembleOfAlgorithms = true,
                    MLBBaseballBatter       = mlbBaseballPlayerBatter
                };

                var baseBallPredictionReply =
                    await baseBallPredictionClient.MakeBaseBallBatterPredictionAsync(baseBallPredictionRequest);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(baseBallPredictionReply.MLBBaseballBatter.FullPlayerName);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("On Hall Of Fame Ballot ################################");
                Console.ResetColor();
                Console.WriteLine("PredictionID: {0}", baseBallPredictionReply.PredictionID);
                Console.WriteLine("Predicted Probability of {0}: {1}", baseBallPredictionRequest.PredictionType,
                                  Math.Round((Decimal)baseBallPredictionReply.MLBHOFPrediction.Probability, 5, MidpointRounding.AwayFromZero));
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("######################################################");
                Console.WriteLine();

                // InductedToHallOfFame Prediction

                // OnHallOfFameBallot Prediction
                baseBallPredictionRequest = new MLBBaseballBatterPredictionRequest
                {
                    PredictionID            = Guid.NewGuid().ToString(),
                    PredictionType          = PredictionType.OnHallOfFameBallot,
                    AlgorithmName           = AlgorithmName.StochasticGradientDescentCalibrated,
                    UseEnsembleOfAlgorithms = true,
                    MLBBaseballBatter       = mlbBaseballPlayerBatter
                };

                baseBallPredictionReply =
                    await baseBallPredictionClient.MakeBaseBallBatterPredictionAsync(baseBallPredictionRequest);

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(baseBallPredictionReply.MLBBaseballBatter.FullPlayerName);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Inducted to Hall Of Fame #############################");
                Console.ResetColor();
                Console.WriteLine("PredictionID: {0}", baseBallPredictionReply.PredictionID);
                Console.WriteLine("Predicted Probability of {0}: {1}", baseBallPredictionRequest.PredictionType,
                                  Math.Round((Decimal)baseBallPredictionReply.MLBHOFPrediction.Probability, 5, MidpointRounding.AwayFromZero));
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("######################################################");
                Console.WriteLine();
            }

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine();
            Console.WriteLine("Finished the gRPC Baseball Predictions Client.");
            Console.ReadLine();
        }