示例#1
0
        public ProductsIncludingTypesAndBrands(ProductSearchParameters parameters)
            : base(product =>
                   (string.IsNullOrEmpty(parameters.Search) || product.Name.ToLower().Contains(parameters.Search)) &&
                   (!parameters.BrandId.HasValue || product.ProductBrandId == parameters.BrandId) &&
                   (!parameters.TypeId.HasValue || product.ProductTypeId == parameters.TypeId)
                   )
        {
            AddInclude(product => product.ProductType);
            AddInclude(product => product.ProductBrand);
            AddOrderBy(product => product.Name);

            if (!string.IsNullOrEmpty(parameters.Sort))
            {
                switch (parameters.Sort)
                {
                case "priceAsc":
                    AddOrderBy(product => product.Price);
                    break;

                case "priceDesc":
                    AddOrderByDescending(product => product.Price);
                    break;

                default:
                    AddOrderBy(product => product.Name);
                    break;
                }
            }

            Paginate(parameters.PageSize * (parameters.PageIndex - 1), parameters.PageSize);
        }
示例#2
0
        public ActionResult Index(string searchString, int SizeID = -1, int BrandID = -1, int ColourID = -1, int CustomerID = -1)
        {
            ProductSearchParameters _Params = new ProductSearchParameters();

            if (SizeID != -1)
            {
                _Params.SizeIds.Add(SizeID);
            }

            if (BrandID != -1)
            {
                _Params.BrandIds.Add(BrandID);
            }

            if (ColourID != -1)
            {
                _Params.ColourIds.Add(ColourID);
            }

            if (searchString.Length > 0)
            {
                _Params.SearchString = searchString;
            }

            ProductSearchModel _ProductViewModel = new ProductSearchModel
            {
                Sizes = processManager.GetSizes().Select(x => new SelectListItem
                {
                    Value = x.SizeId.ToString(),
                    Text  = x.SizeName
                }),
                Brands = processManager.GetBrands().Select(x => new SelectListItem
                {
                    Value = x.BrandId.ToString(),
                    Text  = x.BrandName
                }),
                Colours = processManager.GetColours().Select(x => new SelectListItem
                {
                    Value = x.ColourId.ToString(),
                    Text  = x.ColourName
                }),
                Customers = processManager.GetCustomers().Select(x => new SelectListItem
                {
                    Value = x.CustomerId.ToString(),
                    Text  = x.CustomerName
                })
            };


            if (CustomerID != -1)
            {
                _ProductViewModel.Products = processManager.CustomerProductSearch(CustomerID, _Params);
            }
            else
            {
                _ProductViewModel.Products = processManager.ProductSearch(_Params);
            }
            return(View(_ProductViewModel));
        }
示例#3
0
 public CountedProducts(ProductSearchParameters parameters)
     : base(product =>
            (string.IsNullOrEmpty(parameters.Search) || product.Name.ToLower().Contains(parameters.Search)) &&
            (!parameters.BrandId.HasValue || product.ProductBrandId == parameters.BrandId) &&
            (!parameters.TypeId.HasValue || product.ProductTypeId == parameters.TypeId)
            )
 {
 }
示例#4
0
        private async Task <List <Product> > GetProducts(ProductSearchParameters psp)
        {
            string[] returnProps = { "Id", "Name", "Description", "WebPrice", "Price", "CategoryId", "DateCreated", "DateChanged" };

            var products = await _productService.GetProductsAsync(psp, returnProps);

            return(products.ToList());
        }
示例#5
0
        public async Task <List <Product> > GetProducts(DateTime from)
        {
            var psp = new ProductSearchParameters {
                DateChanged = from.AddSeconds(-from.Second).AddSeconds(-1)
            };                                                                                                    // this time manipulation is needed because 24so service is ROUNDING (not truncating) company creation time

            return(await GetProducts(psp));
        }
示例#6
0
        public void ProcessManagerProductSearchAll()
        {
            DTOContext              _DTOC                    = new DTOContext();
            ProcessManager          _ProcessManager          = new ProcessManager(_DTOC);
            ProductSearchParameters _ProductSearchParameters = new ProductSearchParameters();
            List <Product>          products                 = _ProcessManager.ProductSearch(_ProductSearchParameters);

            Assert.AreEqual(products.Count(), _DTOC.Products.Count());
        }
示例#7
0
        public void ProcessManagerProductSearchColours()
        {
            DTOContext              _DTOC                    = new DTOContext();
            ProcessManager          _ProcessManager          = new ProcessManager(_DTOC);
            ProductSearchParameters _ProductSearchParameters = new ProductSearchParameters {
                ColourIds = new List <int>(new int[] { 1, 2, 3 })
            };
            List <Product> products = _ProcessManager.ProductSearch(_ProductSearchParameters);

            Assert.IsTrue(products.Count() < _DTOC.Products.Count());
        }
示例#8
0
        public void ProcessManagerStringSearch()
        {
            DTOContext              _DTOC                    = new DTOContext();
            ProcessManager          _ProcessManager          = new ProcessManager(_DTOC);
            ProductSearchParameters _ProductSearchParameters = new ProductSearchParameters {
                SearchString = "Tee Nike"
            };
            List <Product> products = _ProcessManager.ProductSearch(_ProductSearchParameters);

            Assert.IsTrue(products.Count() < _DTOC.Products.Count());
        }
示例#9
0
        /// <summary>
        /// Genereates a key that will be used for caching products
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string GetProductCacheKey(ProductSearchParameters parameters)
        {
            // This is not intended to be called from the outside and is public only for tests and transparency.
            // This is supposed to be called only from this class therefor we can throw an expection.
            if (parameters == null)
            {
                throw new Exception("AmazonProductService GetProductCacheKey function is called with empty ProductSearchParameters.");
            }

            return(CacheConstants.CACHE_KEY_PRODUCT_PREFIX + parameters.IndexKey);
        }
示例#10
0
        /// <summary>
        /// Build the url for making rest call to amazon.
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string BuildProductSearchUrl(ProductSearchParameters parameters)
        {
            // We are trying to build a URL like this.
            // http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&
            // AWSAccessKeyId =[Access Key ID] & AssociateTag =[Associate ID] & SearchIndex = Apparel &
            // Keywords = Shirt & Timestamp =[YYYY - MM - DDThh:mm: ssZ] & Signature =[Request Signature]

            // This is not intended to be called from the outside and is public only for tests and transparency.
            // This is supposed to be called only from this class therefor we can throw an expection.
            if (parameters == null)
            {
                throw new Exception("AmazonProductService BuildProductSearchUrl function is called with empty ProductSearchParameters.");
            }

            if (parameters.Keyword == null)
            {
                throw new Exception("AmazonProductService BuildProductSearchUrl function is called with empty ProductSearchParameters.Keyword.");
            }

            // Create timestamp
            var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");

            // ResponseGroup
            // Specifies the types of values to return.You can specify multiple response groups in one request by separating them with commas.
            //Type: String
            //Default: Small
            //Valid Values: Accessories | BrowseNodes | EditorialReview | Images | ItemAttributes | ItemIds
            // | Large | Medium | OfferFull | Offers | PromotionSummary | OfferSummary | RelatedItems | Reviews |
            // SalesRank | Similarities | Small | Tracks | VariationImages | Variations(US only) | VariationSummary


            //                "&Keywords=" + parameters.Keyword + "&Operation=ItemSearch&ResponseGroup=Offers%2CItemAttributes" +
            // TODO add category selection to user settings or a random pick of category
            // Please for the love of God do not touch this line. I spent hours making this work.
            var url = "AWSAccessKeyId=" + _accessKeyId + "&AssociateTag=" + _associateId +
                      "&Keywords=" + Uri.EscapeDataString(parameters.Keyword) +
                      // "&Operation=ItemSearch&ResponseGroup=Offers%2CItemAttributes" +
                      "&Operation=ItemSearch&ResponseGroup=ItemAttributes%2CImages%2CLarge%2CEditorialReview%2CItemIds%2CReviews" +
                      "&SearchIndex=" + parameters.Category + "&Service=AWSECommerceService" +
                      "&Timestamp=" + Uri.EscapeDataString(timeStamp) + "&Version=2013-08-01";

            // Business of signing amazon request. Not a good idea to touch this.
            var dataToSign = "GET\n" +
                             "webservices.amazon.com\n" +
                             "/onca/xml\n" + url;
            var bytesToSign    = Encoding.UTF8.GetBytes(dataToSign);
            var secretKeyBytes = Encoding.UTF8.GetBytes(_accessSecret);
            var hmacSha256     = new HMACSHA256(secretKeyBytes);
            var hashBytes      = hmacSha256.ComputeHash(bytesToSign);
            var signature      = Convert.ToBase64String(hashBytes);
            var fullUrl        = "http://webservices.amazon.com/onca/xml?" + url + "&Signature=" + Uri.EscapeDataString(signature);

            return(fullUrl);
        }
示例#11
0
        public void ProcessManagerCustomerSearch()
        {
            DTOContext              _DTOC                    = new DTOContext();
            ProcessManager          _ProcessManager          = new ProcessManager(_DTOC);
            ProductSearchParameters _ProductSearchParameters = new ProductSearchParameters {
                ColourIds = new List <int>(new int[] { 1, 2, 3 })
            };
            Customer       _Customer = _DTOC.Customers.Where(i => i.CustomerId == 3).FirstOrDefault();
            List <Product> products  = _ProcessManager.CustomerProductSearch(_Customer.CustomerId, _ProductSearchParameters);

            Assert.IsTrue(products.Count() < _DTOC.Products.Count());
        }
示例#12
0
        public void ProductSearchParametersTests_IndexKey_Indexes()
        {
            // Setup
            var setup = new ProductSearchParameters();

            Assert.ThrowsAny <Exception>(() => setup.IndexKey);
            setup.Keyword = "     ";
            Assert.ThrowsAny <Exception>(() => setup.IndexKey);
            setup.Keyword = "a";
            Assert.Equal(setup.IndexKey, setup.Keyword);
            setup.Category = "z";
            Assert.Equal(setup.IndexKey, setup.Keyword + "_" + setup.Category);
        }
示例#13
0
        public AffiliateProductDto Get()
        {
            // Input is passed in the query string. Interface might change eventually.
            // For now lets just get a keyword from query string and use that.
            // Do check the keyword though because our control will pass it otherwise what's the point.
            // Do input validation first because it is less expensive
            if (!Request.Query.ContainsKey(QUERY_STRING_PARAMETER_KEYWORD))
            {
                return(null);
            }
            var keyword = Request.Query[QUERY_STRING_PARAMETER_KEYWORD][0];

            if (string.IsNullOrEmpty(keyword) || string.IsNullOrWhiteSpace(keyword))
            {
                return(null);
            }
            string category = null;

            if (Request.Query.ContainsKey(QUERY_STRING_PARAMETER_CATEGORY))
            {
                category = Request.Query[QUERY_STRING_PARAMETER_CATEGORY][0];
            }

            // Check if caller gave us security header.
            // This might throw exception if there was a header but invalid. But if someone is just messing with us we will return null.
            // Null in this case because we will also check that in react.
            var product = new AffiliateProductDto();

            if (!ParseAntiForgeryHeader(_antiforgery, product, HttpContext))
            {
                return(product);
            }

            // Form the parameters object. This will get smarter then just keyword eventually.
            var parameters = new ProductSearchParameters()
            {
                Keyword = keyword, Category = category
            };

            // Call the service
            product = _productService.FindProduct(parameters);

            // this may be null but we are not going to do anything here no pint really. Just let the client side deal with results.
            return(product);
        }
示例#14
0
        /// <summary>
        /// Parameters are read and filled by controller/caller.
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public AffiliateProductDto FindProduct(ProductSearchParameters parameters)
        {
            // Check parameters. Do not throw expection if blank, just say that nothing found since this is an interface implementation. :)
            if (parameters == null || string.IsNullOrEmpty(parameters.Keyword) || string.IsNullOrWhiteSpace(parameters.Keyword))
            {
                return(null);
            }

            // Do some cleanup because amazon returns nothing on long searches.
            parameters.Keyword  = CleanupKeywords(parameters.Keyword);
            parameters.Category = CleanupCategory(parameters.Category);

            // Generate product cache key
            var key = GetProductCacheKey(parameters);

            // First search cache
            var product = CheckCache(key);

            // Return if found
            if (product != null)
            {
                return(product);
            }

            // Build call url
            var fullUrl = BuildProductSearchUrl(parameters);

            // Search for product. Takes time.
            product = CallProductSearch(fullUrl);

            // Would be strange that amazon did not find anything but ok.
            if (product == null)
            {
                return(null);
            }

            // Cache product
            CacheProduct(key, product);

            return(product);
        }
示例#15
0
        public async Task <ActionResult <Pagination <ProductViewModel> > > GetProducts([FromQuery] ProductSearchParameters productSearchParameters)
        {
            var includeBrandsAndTypesQuery = new ProductsIncludingTypesAndBrands(productSearchParameters);
            var countParameters            = new CountedProducts(productSearchParameters);
            var totalItems = await _unitOfWork.Service <Product>().CountAsync(countParameters);

            var products = await _unitOfWork.Service <Product>().ListAllWithSpecificationAsync(includeBrandsAndTypesQuery);

            var data = _mapper.Map <IReadOnlyList <Product>, IReadOnlyList <ProductViewModel> >(products);

            return(Ok(new Pagination <ProductViewModel>(
                          productSearchParameters.PageIndex,
                          productSearchParameters.PageSize,
                          totalItems,
                          data
                          )));
        }