Example #1
0
 public ProductsResponse GetProducts(GetProductsRequest request)
 {
     return(new ProductsResponse
     {
         Products = _products
     });
 }
Example #2
0
        public Task <GetProductsResponse> GetProducts(GetProductsRequest request)
        {
            var skip = request.PageNo * request.PageSize;
            var take = request.PageSize;

            return(Task.Factory.StartNew(() =>
            {
                Debug.WriteLine("Quering DB. Current thread is " + System.Threading.Thread.CurrentThread.ManagedThreadId);
                using (var context = new MercuryDbConnection())
                {
                    var query = context.Product
                                .OrderBy(x => x.ID)
                                .Skip(skip)
                                .Take(take)
                                .Select(p => new ProductShortInfo
                    {
                        Id = p.ID,
                        BestSellers = p.BestSeller,
                        Color = p.Color,
                        Material = p.Material,
                        Model = p.Model,
                        ModifyDate = p.ModifyDate,
                        Name = p.Name,
                    });

                    return new GetProductsResponse {
                        Products = query.ToList()
                    };
                }
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default));
        }
Example #3
0
        public async Task <BaseResponse <List <ProductDto> > > Handle(GetProductsRequest request, CancellationToken cancellationToken)
        {
            BaseResponse <List <ProductDto> > response = new BaseResponse <List <ProductDto> >();

            try
            {
                List <ProductDto> products = (await _repository.GetWhereAsync(m => 1 == 1)).Select(m => new ProductDto
                {
                    CategoryId   = m.CategoryId,
                    CreatedDate  = m.CreatedDate,
                    Id           = m.Id,
                    IsDeleted    = m.IsDeleted,
                    ModifiedDate = m.ModifiedDate,
                    Name         = m.Name,
                    Price        = m.Price,
                }).ToList();

                response.PayLoad = products;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                response.ReturnMessage = "An error occurred while getting products.";
            }

            return(response);
        }
Example #4
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonPricingConfig config = new AmazonPricingConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonPricingClient client = new AmazonPricingClient(creds, config);

            GetProductsResponse resp = new GetProductsResponse();

            do
            {
                GetProductsRequest req = new GetProductsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.GetProducts(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.FormatVersion)
                {
                    AddObject(obj);
                }

                foreach (var obj in resp.PriceList)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public async Task <GetProductsResponse> GetPaginatedProductsAsync(GetProductsRequest request)
        {
            Expression <Func <Domain.Entities.Product, bool> > categoryFilter =
                (x => request.Categories.Contains(x.Category));

            if (!ProductSortingMapping.TryGetValue(request.OrderBy, out var orderByPropertyName))
            {
                throw new MappingException($"No entity property mapping found for '{nameof(request.OrderBy)}'");
            }

            var paginatedProducts = await _unitOfWork.ProductRepository.GetPaginatedFilteredOrderedListAsync(request.Page,
                                                                                                             request.PageSize,
                                                                                                             categoryFilter,
                                                                                                             orderByPropertyName,
                                                                                                             request.OrderDescending);

            var paginatedProductsResponse = _mapper.Map <GetProductsResponse>(paginatedProducts,
                                                                              o => o.AfterMap((source, destination) =>
            {
                destination.OrderedBy       = request.OrderBy;
                destination.OrderDescending = request.OrderDescending;
            }));

            return(paginatedProductsResponse);
        }
Example #6
0
        public async Task Handle_If_Request_Is_Null_Should_Return_Unsuccesful_Response()
        {
            GetProductsResponse useCaseResponse = null;

            // Mock dependencies
            var mockGetExtensions             = new Mock <IGetPagedListFromRepository <Product> >();
            var mockResponsesMessagesSettings = new Mock <IOptions <Dto.ResponsesSettings> >();
            var mockOutput = new Mock <UseCases.IOutputPort <GetProductsResponse> >();

            // Setup
            mockResponsesMessagesSettings
            .Setup(x => x.Value)
            .Returns(TestsConfigurationHelper.ResponsesSettings);

            mockOutput
            .Setup(x => x.Handle(It.IsAny <GetProductsResponse>()))
            .Callback((GetProductsResponse response) =>
            {
                useCaseResponse = response;
            });

            // Arrange
            var useCase = new GetProductsUseCase(
                mockGetExtensions.Object,
                mockResponsesMessagesSettings.Object);

            GetProductsRequest request = null;

            // Act
            var result = await useCase.Handle(request, mockOutput.Object);

            // Assert
            Assert.False(result);
            Assert.Contains(useCaseResponse.Errores, x => x.Codigo == nameof(TestsConfigurationHelper.ResponsesSettings.RequestMissingErrorMessage));
        }
        internal virtual GetProductsResponse GetProducts(GetProductsRequest request)
        {
            var marshaller   = GetProductsRequestMarshaller.Instance;
            var unmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(Invoke <GetProductsRequest, GetProductsResponse>(request, marshaller, unmarshaller));
        }
Example #8
0
        public void Handle_ShouldGetProducts()
        {
            var productEntities = new List <ProductEntity>
            {
                new ProductEntity {
                    Name = "1", Price = 1, Quantity = 1
                },
                new ProductEntity {
                    Name = "2", Price = 2, Quantity = 2
                },
                new ProductEntity {
                    Name = "3", Price = 3, Quantity = 3
                }
            };
            var request = new GetProductsRequest
            {
                SortOption = It.IsAny <SortOption>()
            };

            _mockProductsService.Setup(s => s.GetProducts(request.SortOption)).ReturnsAsync(productEntities);

            var result = _sut.Handle(request, It.IsAny <CancellationToken>()).Result;

            Assert.True(result.Count() == productEntities.Count());
            for (int i = 0; i < result.Count(); i++)
            {
                Assert.Equal(productEntities.ElementAt(i).Name, result.ElementAt(i).Name);
                Assert.Equal(productEntities.ElementAt(i).Price, result.ElementAt(i).Price);
                Assert.Equal(productEntities.ElementAt(i).Quantity, result.ElementAt(i).Quantity);
            }
        }
Example #9
0
        public async Task <IEnumerable <GetProductsResponse> > GetProductsAsync(GetProductsRequest request)
        {
            string getProductsEndPoint           = $"{_catalogServiceUri}/api/v1/products";
            List <GetProductsResponse> responses = await RestClient.GetAsync <List <GetProductsResponse> >(getProductsEndPoint);

            return(responses);
        }
Example #10
0
        public async Task <IActionResult> GetProducts([FromQuery] ProductsSearchRequest productsRequest, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var getProductsRequest = new GetProductsRequest()
            {
                PageNumber   = productsRequest.PageNumber,
                PageSize     = productsRequest.PageSize,
                ProductName  = productsRequest.ProductSearchName,
                CategoryId   = productsRequest.CategoryId,
                LoadCategory = true,
                CalculateTotalProductsCount = true
            };

            var searchResult = await _mediator.Send(getProductsRequest, cancellationToken);

            var productItems    = _mapper.Map <IEnumerable <ProductItemDto> >(searchResult.FoundProducts);
            var searchResultDto = new ProductsSearchResultDto()
            {
                TotalProductsCount = searchResult.TotalProductsCount.GetValueOrDefault(),
                ProductItems       = productItems
            };

            return(Ok(searchResultDto));
        }
Example #11
0
 public void SetUpJsonHeaders()
 {
     GetProductsRequest.AddHeader("Content-Type", "application/json");
     PostProductRequest.AddHeader("Content-Type", "application/json");
     GetSpecificProductRequest.AddHeader("Content-Type", "application/json");
     GetNewestProductRequest.AddHeader("Content-Type", "application/json");
 }
Example #12
0
        public void GetProducts_ShouldReturnListOfProductsFilteredByAll()
        {
            var dto = new GetProductsRequest
            {
                Name        = "product",
                Description = "description",
                StartDate   = DateTime.Now.AddDays(-50),
                EndDate     = DateTime.Now.AddDays(1),
                Price       = 10.20M,
                OrderBy     = ProductOrderBy.NameAscending
            };

            var productRepository = InitializeRepository();
            var products          = context.CommerceContext().Products
                                    .Where(u => u.Name.ToLower().Contains(dto.Name.ToLower()) &&
                                           u.Description.ToLower().Contains(dto.Description.ToLower()) &&
                                           u.Price == dto.Price &&
                                           u.CreationDate >= dto.StartDate &&
                                           u.CreationDate <= dto.EndDate)
                                    .OrderBy(u => u.Name);

            var result = productRepository.GetProducts(dto);

            context.DropCommerceContext();
            Assert.Equal(products, result);
        }
Example #13
0
        public override async Task <ProductList> GetProducts(GetProductsRequest request, ServerCallContext context)
        {
            var products = await _ctx.Products.ToListAsync();

            if (products.Count <= 0)
            {
                return(default);
Example #14
0
        /// <summary>
        /// Initiates the asynchronous execution of the GetProducts operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetProducts operation on AmazonPricingClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetProducts
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15/GetProducts">REST API Reference for GetProducts Operation</seealso>
        public virtual IAsyncResult BeginGetProducts(GetProductsRequest request, AsyncCallback callback, object state)
        {
            var marshaller   = GetProductsRequestMarshaller.Instance;
            var unmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(BeginInvoke <GetProductsRequest>(request, marshaller, unmarshaller,
                                                    callback, state));
        }
        public override async Task <GetProductsReply> GetProducts(GetProductsRequest request, ServerCallContext context)
        {
            var products = GetProducts();
            var result   = new GetProductsReply();

            result.Products.AddRange(products);
            return(result);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the GetProducts operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetProducts operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15/GetProducts">REST API Reference for GetProducts Operation</seealso>
        public virtual Task <GetProductsResponse> GetProductsAsync(GetProductsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = GetProductsRequestMarshaller.Instance;
            var unmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(InvokeAsync <GetProductsRequest, GetProductsResponse>(request, marshaller,
                                                                         unmarshaller, cancellationToken));
        }
        public Task <GetProductsResponse> GetProductsAsync(GetProductsRequest request)
        {
            var response = new GetProductsResponse
            {
                Products = _products
            };

            return(Task.FromResult(response));
        }
        /// <summary>
        /// Returns a list of all products that match the filter criteria.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetProducts service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the GetProducts service method, as returned by Pricing.</returns>
        /// <exception cref="Amazon.Pricing.Model.ExpiredNextTokenException">
        /// The pagination token expired. Try again without a pagination token.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InternalErrorException">
        /// An error on the server occurred during the processing of your request. Try again later.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InvalidNextTokenException">
        /// The pagination token is invalid. Try again without a pagination token.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InvalidParameterException">
        /// One or more parameters had an invalid value.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.NotFoundException">
        /// The requested resource can't be found.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15/GetProducts">REST API Reference for GetProducts Operation</seealso>
        public virtual Task <GetProductsResponse> GetProductsAsync(GetProductsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = GetProductsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(InvokeAsync <GetProductsResponse>(request, options, cancellationToken));
        }
        /// <summary>
        /// Returns a list of all products that match the filter criteria.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetProducts service method.</param>
        ///
        /// <returns>The response from the GetProducts service method, as returned by Pricing.</returns>
        /// <exception cref="Amazon.Pricing.Model.ExpiredNextTokenException">
        /// The pagination token expired. Try again without a pagination token.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InternalErrorException">
        /// An error on the server occurred during the processing of your request. Try again later.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InvalidNextTokenException">
        /// The pagination token is invalid. Try again without a pagination token.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.InvalidParameterException">
        /// One or more parameters had an invalid value.
        /// </exception>
        /// <exception cref="Amazon.Pricing.Model.NotFoundException">
        /// The requested resource can't be found.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15/GetProducts">REST API Reference for GetProducts Operation</seealso>
        public virtual GetProductsResponse GetProducts(GetProductsRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = GetProductsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(Invoke <GetProductsResponse>(request, options));
        }
        /// <summary>
        /// Initiates the asynchronous execution of the GetProducts operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetProducts operation on AmazonPricingClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetProducts
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15/GetProducts">REST API Reference for GetProducts Operation</seealso>
        public virtual IAsyncResult BeginGetProducts(GetProductsRequest request, AsyncCallback callback, object state)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = GetProductsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = GetProductsResponseUnmarshaller.Instance;

            return(BeginInvoke(request, options, callback, state));
        }
Example #21
0
        protected override async Task OnInitializedAsync()
        {
            User = (await authenticationStateTask).User;
            var productsRequest = new GetProductsRequest()
            {
                Page = 1, PageSize = 10
            };

            products = await _productService.GetProductsAsync(productsRequest, CancellationToken.None);
        }
            public async Task <IEnumerable <GetProductsResponse> > Handle(GetProductsRequest request, CancellationToken cancellationToken)
            {
                var entities = await _dbContext.Products.Include(product => product.Stores)
                               .ThenInclude(storeProduct => storeProduct.Store)
                               .Where(product => product.Stores.Any())
                               .ProjectTo <GetProductsResponse>(_mapper.ConfigurationProvider)
                               .ToListAsync(cancellationToken);

                return(entities);
            }
Example #23
0
 public IActionResult Get([FromQuery] GetProductsRequest dto)
 {
     try
     {
         return(Ok(productService.GetProducts(dto)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
Example #24
0
        public GetProductsResponse GetProductsByCriteria(GetProductsRequest request)
        {
            GetProductsResponse      response = new GetProductsResponse();
            ProductBusinessComponent bc       = DependencyInjectionHelper.GetProductBusinessComponent();

            IQueryable <Product> products = bc.GetProductsByCriteria(request.SearchType, request.Category, request.ProductName);

            response.Products = ProductAdapter.ProductsToDtos(products);

            return(response);
        }
        public async Task <IActionResult> GetProductsAsync([FromQuery] GetProductsRequest request)
        {
            Logger?.LogDebug("{0} has been invoked", nameof(GetProductsAsync));

            // Get response from business logic
            var response = await Service
                           .GetProductsAsync(request.PageSize, request.PageNumber, request.ProductCategoryID);

            // Return as http response
            return(response.ToHttpResult());
        }
        public async Task <ActionResult <GetProductsResponse> > GetProductsAsync(GetProductsRequest request)
        {
            var result = await _mediator.Send(request);

            if (result == null)
            {
                return(NotFound("Product not found"));
            }

            return(Ok(result));
        }
Example #27
0
        public async Task <BaseResponse <List <ProductDto> > > Handle(GetProductsRequest request, CancellationToken cancellationToken)
        {
            var response = new BaseResponse <List <ProductDto> >();

            var products = await _productRespository.GetList(p => !p.IsDeleted && p.IsActive);

            var productDtos = _mapper.Map <List <ProductDto> >(products);

            response.Data = productDtos;

            return(response);
        }
Example #28
0
        public Task <ResponseMessage> GetProducts(GetProductsRequest request)
        {
            var response = new ResponseMessage();
            var products = _productsRepository.GetProducts(request.Id);

            if (request.Id.HasValue && products.Count == 0)
            {
                return(Fault(HttpStatusCode.NotFound));
            }
            response.Data = products;
            return(Task.FromResult(response));
        }
Example #29
0
        public async Task <ProductsViewModel> GetProductsAsync(GetProductsRequest getProductsRequest, CancellationToken cancellationToken)
        {
            var qpc = new QueryParamCollection
            {
                { "pageSize", getProductsRequest.PageSize },
                { "page", getProductsRequest.Page }
            }.ToQueryString();

            var response = await _httpClient.SendAsync <ProductsViewModel>(HttpMethod.Get, $"v1/Product/GetProducts?{qpc}", null, cancellationToken);

            return(response);
        }
        public async Task <bool> Handle(GetProductsRequest request, IOutputPort <GetProductsResponse> outputPort)
        {
            var products = await repository.GetProducts();

            var productsDto = new List <ProductDto>();

            foreach (var p in products)
            {
                productsDto.Add(new ProductDto(p.Id, p.Name, p.Description, p.Price, p.Category));
            }
            outputPort.Handle(new GetProductsResponse(productsDto, true));
            return(true);
        }
Example #31
0
        public GetProductsResponse GetProducts(GetProductsRequest request)
        {
            GetProductsResponse response = new GetProductsResponse();
            try
            {
                response.Products = productsRepository.GetAll();
                response.Status = true;
                response.Message = "ok";
            }
            catch (Exception e)
            {
                response.Status = false;
                response.Message = e.Message;
                if (e.InnerException != null)
                {
                    response.Message += Environment.NewLine;
                    response.Message += string.Format("Inner exception: {0}", e.InnerException.Message);
                }
            }

            return response;
        }