Exemplo n.º 1
0
        private void add_Click(object sender, RoutedEventArgs e)
        {
            ServiceReference6.Country c      = new ServiceReference6.Country();
            CountryServiceClient      client = new CountryServiceClient();

            c.CountryLastUpdate = DateTime.Now;
            c.CountryName       = name.Text;
            client.Add(c);
        }
Exemplo n.º 2
0
 public CountryServiceClient() :
     base(CountryServiceClient.GetDefaultBinding(), CountryServiceClient.GetDefaultEndpointAddress())
 {
     this.Endpoint.Name = EndpointConfiguration.BasicHttpsBinding_ICountryService.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
Exemplo n.º 3
0
 private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress()
 {
     return(CountryServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpsBinding_ICountryService));
 }
Exemplo n.º 4
0
 private static System.ServiceModel.Channels.Binding GetDefaultBinding()
 {
     return(CountryServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpsBinding_ICountryService));
 }
Exemplo n.º 5
0
 public CountryServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) :
     base(CountryServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress)
 {
     this.Endpoint.Name = endpointConfiguration.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
Exemplo n.º 6
0
 public CountryServiceClient(EndpointConfiguration endpointConfiguration) :
     base(CountryServiceClient.GetBindingForEndpoint(endpointConfiguration), CountryServiceClient.GetEndpointAddress(endpointConfiguration))
 {
     this.Endpoint.Name = endpointConfiguration.ToString();
     ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
 }
Exemplo n.º 7
0
        static async Task Main(string[] args)
        {
            // DI
            var services = new ServiceCollection();

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

            Func <HttpRequestMessage, IAsyncPolicy <HttpResponseMessage> > retryFunc = (request) =>
            {
                return(Policy.HandleResult <HttpResponseMessage>(r => {
                    var grpcStatus = StatusManager.GetStatusCode(r);
                    return r.StatusCode != HttpStatusCode.OK && grpcStatus != StatusCode.OK && grpcStatus != StatusCode.InvalidArgument;
                })
                       .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://grpcwebdemo.azurewebsites.net", new GrpcChannelOptions
            {
                HttpClient    = new HttpClient(handler),
                LoggerFactory = loggerFactory
            });
            var clientWeb = new CountryServiceClient(channel);

            try
            {
                /*
                 * // Create
                 * var createdCountry = await client.CreateAsync(new CountryCreateRequest { Name = "Japan", Description = "" }); // Remove Name or Description to test validation
                 * var country = new Country
                 * {
                 *  CountryId = createdCountry.Id,
                 *  CountryName = createdCountry.Name,
                 *  Description = createdCountry.Description
                 * };
                 * Console.WriteLine($"Country {country.CountryName} ({country.CountryId}) created!");
                 *
                 *
                 * // GetById
                 * var foundCountry = await client.GetByIdAsync(new CountrySearchRequest { CountryId = country.CountryId });
                 * country = new Country
                 * {
                 *  CountryId = foundCountry.Id,
                 *  CountryName = foundCountry.Name,
                 *  Description = foundCountry.Description
                 * };
                 * Console.WriteLine($"Found country {country.CountryName} ({country.CountryId})");
                 *
                 *
                 * // Update
                 * var updatedCountry = await client.UpdateAsync(new CountryRequest { Id = country.CountryId, Name = "Japan", Description = "rising sun country, Nippon!!!" });
                 * country = new Country
                 * {
                 *  CountryId = updatedCountry.Id,
                 *  CountryName = updatedCountry.Name,
                 *  Description = updatedCountry.Description
                 * };
                 * Console.WriteLine($"Country {country.CountryName} ({country.CountryId}) updated with new description: {country.Description}");
                 *
                 * // Delete
                 * await client.DeleteAsync(new CountrySearchRequest { CountryId = country.CountryId });
                 * Console.WriteLine($"Deleted country {country.CountryName} ({country.CountryId})");
                 */

                /*
                 * // Get all gRPC
                 * var countries = (await client.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}"));


                //var handler2 = new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler());
                //var channel2 = GrpcChannel.ForAddress("https://grpcweb.azurewebsites.net/", new GrpcChannelOptions
                //{
                //    HttpClient = new HttpClient(handler2),
                //    LoggerFactory = loggerFactory
                //});
                //var clientweb2 = new Greeter.GreeterClient(channel2);
                //var response = await clientweb2.SayHelloAsync(new HelloRequest { Name = ".NET" });

                //Console.WriteLine(response.Message);
            }
            catch (RpcException e)
            {
                var errors = e.GetValidationErrors(); // Gets validation errors list
                Console.WriteLine(e.Message);
            }
        }
        private static void AddWCFServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddScoped<IAddressTypeService>(provider =>
            {
                var client = new AddressTypeServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["AddressTypeAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<IContactTypeService>(provider =>
            {
                var client = new ContactTypeServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["ContactTypeAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<ICountryService>(provider =>
            {
                var client = new CountryServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["CountryAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<ICustomerService>(provider =>
            {
                var client = new CustomerServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["CustomerAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<ISalesOrderService>(provider =>
            {
                var client = new SalesOrderServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["SalesOrderAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<ISalesPersonService>(provider =>
            {
                var client = new SalesPersonServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["SalesPersonAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<ISalesTerritoryService>(provider =>
            {
                var client = new SalesTerritoryServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["SalesTerritoryAPI:Uri"])
                );

                return client;
            });
            services.AddScoped<IStateProvinceService>(provider =>
            {
                var client = new StateProvinceServiceClient(
                    new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue },
                    new EndpointAddress(configuration["StateProvinceAPI:Uri"])
                );

                return client;
            });
        }
Exemplo n.º 9
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);
            }
        }