Example #1
0
        public IActionResult Post([FromBody] Product product)
        {
            var client         = new ProductService.ProductServiceClient(channel);
            var createdProduct = client.Insert(product);

            //return CreatedAtRoute("GetProduct", new { id = createdProduct.Id }, createdProduct);
            return(Created("products", createdProduct));
        }
Example #2
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("--------------CLIENT ---------");
            var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var client = new ProductService.ProductServiceClient(channel);

            var products = client.GetAll(new Empty());

            Console.WriteLine("[ GetAll ]");
            products.CDump("-- products");

            Console.WriteLine("");

            Console.WriteLine("[ Get Id=1 ]");

            var product = client.Get(new ProductId {
                Id = 1
            });

            product.CDump("-- product id=1");
            Console.WriteLine("");
            Console.WriteLine("[ Insert ]");

            var newProduct = new Product {
                Name = "Melon", Brand = "Vegi", Amount = 10, Value = 2.99f
            };
            var createdProduct = client.Insert(newProduct);

            createdProduct.DDump("createdProduct");
            Console.WriteLine("");
            Console.WriteLine("[ GetAll ]");

            var products01 = client.GetAll(new Empty());

            products01.CDump("-- products");
            createdProduct.Name = "MELON";
            Console.WriteLine("");
            Console.WriteLine("[ Update ]");

            var updatedProduct = await client.UpdateAsync(createdProduct);

            updatedProduct.CDump("updatedProduct");
            Console.WriteLine("");
            Console.WriteLine("[ Delete ]");

            var deletedProduct = await client.DeleteAsync(new ProductId { Id = 1 });

            updatedProduct.CDump("updatedProduct");
            Console.WriteLine("");
            Console.WriteLine("[ GetAll ]");

            products01 = client.GetAll(new Empty());
            products01.CDump("-- products");

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Example #3
0
        public IActionResult Delete(int id)
        {
            var client = new ProductService.ProductServiceClient(channel);

            client.Delete(new ProductId {
                Id = id
            });
            //return new ObjectResult(id);
            return(Ok(id));
        }
Example #4
0
        private static async Task ListProduct(ProductService.ProductServiceClient client)
        {
            var response = client.GetAllProducts(new GetAllProductsRequest()
            {
            });

            while (await response.ResponseStream.MoveNext())
            {
                Console.WriteLine(response.ResponseStream.Current.Product.ToString());
            }
        }
Example #5
0
        public IActionResult Put([FromBody] Product product)
        {
            var client         = new ProductService.ProductServiceClient(channel);
            var udpatedProduct = client.Update(product);

            if (udpatedProduct == null)
            {
                return(NotFound());
            }
            return(Ok(udpatedProduct));
        }
Example #6
0
        public async Task <IList <Product> > GetByIdAsync(IList <string> ids)
        {
            return(await _grpcCallerService.CallService(_productServiceProvider.GrpcEndpoint, async (grpcChannel) =>
            {
                var client = new ProductService.ProductServiceClient(grpcChannel);
                var response = await client.GetByIdsAsync(new GetByIdsRequest
                {
                    Ids = { ids }
                });

                return response.Products;
            }));
        }
Example #7
0
        public IActionResult GetById(int id)
        {
            var client  = new ProductService.ProductServiceClient(channel);
            var product = client.Get(new ProductId {
                Id = id
            });

            if (product == null)
            {
                return(NotFound());
            }
            //return new ObjectResult(product);
            return(Ok(product));
        }
Example #8
0
        private async static Task CreateProducts(ProductService.ProductServiceClient client)
        {
            var products = new List <Product.Product>
            {
                new Product.Product()
                {
                    Name = "Product X1", Description = "Product X1 Description"
                },
                new Product.Product()
                {
                    Name = "Product X2", Description = "Product X2 Description"
                },
                new Product.Product()
                {
                    Name = "Product X3", Description = "Product X3 Description"
                },
                new Product.Product()
                {
                    Name = "Product X4", Description = "Product X4 Description"
                }
            };

            using (var call = client.CreateProducts())
            {
                var requestStream  = call.RequestStream;
                var responseStream = call.ResponseStream;

                var responseTask = Task.Run(async() =>
                {
                    while (await responseStream.MoveNext())
                    {
                        Console.WriteLine("Saved: " + responseStream.Current.Product);
                    }
                });

                foreach (var product in products)
                {
                    await requestStream.WriteAsync(new CreateProductRequest()
                    {
                        Product = product
                    });

                    System.Threading.Thread.Sleep(1000);
                }
                await call.RequestStream.CompleteAsync();

                await responseTask;
            }
        }
Example #9
0
        private static Product.Product CreateProduct(ProductService.ProductServiceClient client)
        {
            var response = client.CreateProduct(new CreateProductRequest()
            {
                Product = new Product.Product()
                {
                    Name        = "Product X",
                    Description = "Product X Description"
                }
            });

            Console.WriteLine("The Product " + response.Product.Id + " was created !");

            return(response.Product);
        }
Example #10
0
        private static void DeleteProduct(ProductService.ProductServiceClient client, Product.Product Product)
        {
            try
            {
                var response = client.DeleteProduct(new DeleteProductRequest()
                {
                    ProductId = Product.Id
                });

                Console.WriteLine("The Product with id " + Product.Id + " was deleted");
            }
            catch (RpcException e)
            {
                Console.WriteLine(e.Status.Detail);
            }
        }
Example #11
0
        private static void UpdateProduct(ProductService.ProductServiceClient client, Product.Product Product)
        {
            try
            {
                var response = client.UpdateProduct(new UpdateProductRequest()
                {
                    Product = Product
                });

                Console.WriteLine(response.Product.ToString());
            }
            catch (RpcException e)
            {
                Console.WriteLine(e.Status.Detail);
            }
        }
Example #12
0
        public async Task <IList <Product> > GetByHandleAsync(IList <string> handles,
                                                              string languageCode)
        {
            return(await _grpcCallerService.CallService(_productServiceProvider.GrpcEndpoint, async (grpcChannel) =>
            {
                var client = new ProductService.ProductServiceClient(grpcChannel);
                var response = await client.GetByHandlesAsync(new GetByHandlesRequest
                {
                    Handles = { handles }
                });

                // Filter out matches in other languages
                return response.Products
                .Where(x => x.Handles
                       .Any(ls => ls.LanguageCode == languageCode && handles.Contains(ls.Value)))
                .ToList();
            }));
        }
Example #13
0
        static async Task Main(string[] args)
        {
            // The port number here must match the port of the gRPC server
            var channel = new Channel("localhost:50051", ChannelCredentials.Insecure);
            var client  = new ProductService.ProductServiceClient(channel);

            var response = await client.GetProductsAsync(new GetProductsRequest());

            foreach (var product in response.Products)
            {
                Console.WriteLine($"{product.Name} - {product.ProducedBy} - {product.Price}");
            }

            await channel.ShutdownAsync();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Example #14
0
        public async Task <SearchResult <Product> > GetBySearchAsync(string searchTerm,
                                                                     string languageCode,
                                                                     string categoryId,
                                                                     string pageCursor,
                                                                     int pageSize,
                                                                     ProductSortKey sortKey,
                                                                     bool reverse,
                                                                     string currencyCode)
        {
            return(await _grpcCallerService.CallService(_productServiceProvider.GrpcEndpoint, async (grpcChannel) =>
            {
                var client = new ProductService.ProductServiceClient(grpcChannel);
                var response = await client.GetBySearchAsync(new GetBySearchRequest
                {
                    SearchTerm = searchTerm,
                    LanguageCode = languageCode,
                    CategoryId = categoryId,
                    PageCursor = pageCursor,
                    PageSize = pageSize,
                    SortKey = sortKey,
                    Reverse = reverse,
                    CurrencyCode = currencyCode,
                });

                var results = response
                              .Results
                              .Select(x => new CursorNodeResult <Product>
                {
                    Cursor = x.Cursor,
                    Node = x.Node,
                })
                              .ToList();

                return new SearchResult <Product>
                {
                    HasNextPage = response.HasNextPage,
                    HasPreviousPage = response.HasPreviousPage,
                    StartCursor = response.StartCursor,
                    EndCursor = response.EndCursor,
                    TotalResults = response.TotalResults,
                    Results = results,
                };
            }));
        }
Example #15
0
        static void Main(string[] args)
        {
            Channel channel = new Channel("localhost:44558", ChannelCredentials.Insecure);

            client = new ProductService.ProductServiceClient(channel);
            int op = 0;

            do
            {
                Console.WriteLine("\n\n");
                Console.WriteLine("1. Get");
                Console.WriteLine("2. GetAll");
                Console.WriteLine("3. Add");
                Console.WriteLine("4. Remove");
                Console.WriteLine("0. Exit");
                Console.Write(">>");
                bool res = Int32.TryParse(Console.ReadLine(), out op);
                if (!res)
                {
                    continue;
                }

                switch (op)
                {
                case 1: Get();  break;

                case 2: GetAll(); break;

                case 3: Add(); break;

                case 4: Remove(); break;

                case 0: break;

                default: Console.WriteLine("Error!"); break;
                }
            } while (op != 0);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Example #16
0
        private static GetProductResponse GetProduct(ProductService.ProductServiceClient client, string id)
        {
            try
            {
                var response = client.GetProduct(new GetProductRequest()
                {
                    ProductId = id
                });

                Console.WriteLine(response.Product.ToString());

                return(response);
            }
            catch (RpcException e)
            {
                Console.WriteLine(e.Status.Detail);
                //just log and continue;
                Console.ReadKey();
                return(null);
            }
        }
Example #17
0
        static void ProductServiceRequest()
        {
            try
            {
                var productServiceChannel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
                var productServiceClient  = new ProductService.ProductServiceClient(productServiceChannel);
                var product = productServiceClient.GetProductById(new ProductByIdRequest {
                    ProductId = 1
                });
                Console.WriteLine($"ProductUuid: {product.ProductUuid}");

                var product2 = productServiceClient.GetProductByUuid(new ProductByUuidRequest {
                    ProductUuid = "Id Of Product 1"
                });
                Console.WriteLine($"ProductId: {product.ProductId}");

                productServiceChannel.ShutdownAsync().Wait();
                Console.WriteLine("ProductServiceRequest Terminated...");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception encountered: {ex}");
            }
        }
Example #18
0
 public SneakerProductsGrpcRepository(ProductService.ProductServiceClient client) => _client = client;
Example #19
0
        public List <Product> GetAll()
        {
            var client = new ProductService.ProductServiceClient(channel);

            return(client.GetAll(new Empty()).Products.ToList());
        }
Example #20
0
        static async Task Main(string[] args)
        {
            Channel channel = new Channel("localhost", 50052, ChannelCredentials.Insecure);

            await channel.ConnectAsync().ContinueWith((task) =>
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    Console.WriteLine("The client connected successfully");
                }
            });

            var client = new ProductService.ProductServiceClient(channel);
            //Product.Product product;


            //Test various operations
            int choice = -1;

            while (choice != 9)
            {
                choice = GetChoice();
                switch (choice)
                {
                case 9:
                    break;

                case 0:
                    //Create new product
                    var p1 = CreateProduct(client);
                    break;

                case 1:
                    //Create new product
                    var p2 = GetProduct(client, "product1");
                    break;

                case 2:
                    //update product
                    var p3 = GetProduct(client, "product1");
                    UpdateProduct(client, p3.Product);
                    break;

                case 3:
                    //delete product
                    var p4 = GetProduct(client, "product1");
                    DeleteProduct(client, p4.Product);
                    break;

                case 4:
                    //get all products
                    await ListProduct(client);

                    break;

                case 5:
                    //Test Bidirectional streaming
                    // test setup with one second delay at client for sending each record
                    // and two second delay at server side before saving
                    await CreateProducts(client);

                    break;

                default:
                    break;
                }
            }

            //test rpc exception
            //GetProduct(client, "-1");
            Console.ReadKey();
            channel.ShutdownAsync().Wait();
        }
Example #21
0
        static ProductServiceClient()
        {
            var channel = ServiceClientHelper.GetChannelByApiName("ProductApi");

            Client = new ProductService.ProductServiceClient(channel);
        }
Example #22
0
 static void ValidatingParametersInAWCFService()
 {
     bool success;
     // Create a client to access the ProductService WCF service.
     ProductService.IProductService svc = new ProductService.ProductServiceClient();
     Console.WriteLine("Created a client to access the ProductService WCF service.");
     Console.WriteLine();
     // Call the method, which returns success or failure, to add a valid product.
     IProduct validProduct = new Product();
     PopulateValidProduct(validProduct);
     try
     {
         Console.WriteLine("Adding a valid product using the ProductService... ");
         success = svc.AddNewProduct(validProduct.ID, validProduct.Name, validProduct.Description,
                                       validProduct.ProductType, validProduct.InStock,
                                                                 validProduct.OnOrder, validProduct.DateDue);
         Console.WriteLine("Successful: {0}", success);
     }
     catch (FaultException<ValidationFault> ex)
     {
         // Validation of the Product instance failed within the service interface.
         Console.WriteLine("Validation within the ProductService failed.");
         // Convert the validation details in the exception to individual
         // ValidationResult instances and add them to the collection.
         ValidationResults results = ConvertToValidationResults(ex.Detail.Details, validProduct);
         // Display information about the validation errors
         ShowValidationResults(results);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error while calling service method: {0}", ex.Message);
     }
     Console.WriteLine();
     // Now call the same method to add an invalid product.
     IProduct invalidProduct = new Product();
     PopulateInvalidProduct(invalidProduct);
     try
     {
         Console.WriteLine("Adding an invalid product using the ProductService... ");
         success = svc.AddNewProduct(invalidProduct.ID, invalidProduct.Name, invalidProduct.Description,
                                       invalidProduct.ProductType, invalidProduct.InStock,
                                                                 invalidProduct.OnOrder, invalidProduct.DateDue);
         Console.WriteLine("Added an invalid product using the ProductService. Successful: {0}", success);
     }
     catch (FaultException<ValidationFault> ex)
     {
         // Validation of the Product instance failed within the service interface.
         Console.WriteLine("Validation within the ProductService failed.");
         // Convert the validation details in the exception to individual
         // ValidationResult instances and add them to the collection.
         ValidationResults results = ConvertToValidationResults(ex.Detail.Details, invalidProduct);
         // Display information about the validation errors
         ShowValidationResults(results);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error while calling service method: {0}", ex.Message);
     }
 }
Example #23
0
 // GET api/values
 public ProductService.Product GetProduct(int id)
 {
     ProductService.ProductServiceClient client = new ProductService.ProductServiceClient();
     ProductService.Product p = client.GetProductDetails(id);
     return(p);
 }