예제 #1
0
        public ProductFacetsViewModel GetProductFacetsViewModel(
            CommerceSearchOptions productSearchOptions,
            string searchKeyword,
            string catalogName,
            Item item,
            Rendering rendering)
        {
            var           viewModel     = new ProductFacetsViewModel();
            SearchResults childProducts = null;

            if (productSearchOptions != null)
            {
                childProducts = this.GetChildProducts(item, productSearchOptions, searchKeyword, catalogName);
            }

            viewModel.Initialize(rendering, childProducts, productSearchOptions);

            return(viewModel);
        }
        /// <summary>
        /// This method returns child products for this category
        /// </summary>
        /// <param name="searchOptions">The options to perform the search with</param>
        /// <param name="categoryItem">The category item whose children to retrieve</param>
        /// <returns>A list of child products</returns>
        protected SearchResults GetChildProducts(CommerceSearchOptions searchOptions, Item categoryItem)
        {
            IEnumerable <CommerceQueryFacet> facets = null;
            var returnList        = new List <Item>();
            var totalPageCount    = 0;
            var totalProductCount = 0;

            if (Item != null)
            {
                SearchResponse searchResponse = null;
                if (CatalogUtility.IsItemDerivedFromCommerceTemplate(categoryItem, CommerceConstants.KnownTemplateIds.CommerceDynamicCategoryTemplate) || categoryItem.TemplateName == "Commerce Named Search")
                {
                    try
                    {
                        var defaultBucketQuery     = categoryItem[CommerceConstants.KnownSitecoreFieldNames.DefaultBucketQuery];
                        var persistendBucketFilter = categoryItem[CommerceConstants.KnownSitecoreFieldNames.PersistentBucketFilter];
                        persistendBucketFilter = CleanLanguageFromFilter(persistendBucketFilter);
                        searchResponse         = SearchNavigation.SearchCatalogItems(defaultBucketQuery, persistendBucketFilter, searchOptions);
                    }
                    catch (Exception ex)
                    {
                        Helpers.LogException(ex, this);
                    }
                }
                else
                {
                    searchResponse = SearchNavigation.GetCategoryProducts(categoryItem.ID, searchOptions);
                }

                if (searchResponse != null)
                {
                    returnList.AddRange(searchResponse.ResponseItems);

                    totalProductCount = searchResponse.TotalItemCount;
                    totalPageCount    = searchResponse.TotalPageCount;
                    facets            = searchResponse.Facets;
                }
            }

            var results = new SearchResults(returnList, totalProductCount, totalPageCount, searchOptions.StartPageIndex, facets);

            return(results);
        }
        protected SearchResults GetChildProducts(
            CommerceSearchOptions searchOptions,
            Item item)
        {
            Assert.ArgumentNotNull(item, nameof(item));
            Assert.ArgumentNotNull(searchOptions, nameof(searchOptions));
            SearchResults searchResults = null;
            string        str           = string.Format(CultureInfo.InvariantCulture, "ChildProductSearch_{0}", item.ID.ToString());

            if (!SiteContext.Items.Contains(str))
            {
                if (item != null)
                {
                    searchResults = !string.IsNullOrWhiteSpace(searchOptions.SearchKeyword) ? SearchManager.SearchCatalogItemsByKeyword(searchOptions.SearchKeyword, searchOptions.CatalogName, searchOptions) : SearchManager.GetCategoryProducts(item.ID, searchOptions);
                }
                SiteContext.Items[str] = searchResults;
            }
            return((SearchResults)SiteContext.Items[str]);
        }
        public ProductListResultModel GetProductList(
            IVisitorContext visitorContext,
            string currentItemId,
            string currentCatalogItemId,
            string searchKeyword,
            int?pageNumber,
            NameValueCollection facetValues,
            string sortField,
            int?pageSize,
            SortDirection?sortDirection)
        {
            Assert.ArgumentNotNull(visitorContext, nameof(visitorContext));

            var model = new ProductListResultModel();

            Item specifiedCatalogItem = !string.IsNullOrEmpty(currentCatalogItemId) ? Sitecore.Context.Database.GetItem(currentCatalogItemId) : null;
            Item currentCatalogItem   = specifiedCatalogItem ?? this.storefrontContext.CurrentCatalog.Item;

            model.CurrentCatalogItemId = currentCatalogItem.ID.Guid.ToString("D");

            // var currentItem = Sitecore.Context.Database.GetItem(currentItemId);

            // this.siteContext.CurrentCategoryItem = currentCatalogItem;
            // this.siteContext.CurrentItem = currentItem;
            CategorySearchInformation searchInformation = this.searchInformationProvider.GetCategorySearchInformation(currentCatalogItem);

            this.GetSortParameters(searchInformation, ref sortField, ref sortDirection);

            int itemsPerPage          = this.settingsProvider.GetDefaultItemsPerPage(pageSize, searchInformation);
            var commerceSearchOptions = new CommerceSearchOptions(itemsPerPage, pageNumber.GetValueOrDefault(0));

            this.UpdateOptionsWithFacets(searchInformation.RequiredFacets, facetValues, commerceSearchOptions);
            this.UpdateOptionsWithSorting(sortField, sortDirection, commerceSearchOptions);

            SearchResults        childProducts     = this.GetChildProducts(searchKeyword, commerceSearchOptions, specifiedCatalogItem);
            IList <ProductModel> productEntityList = this.AdjustProductPriceAndStockStatus(visitorContext, childProducts, currentCatalogItem);

            model.Initialize(commerceSearchOptions, childProducts, productEntityList);
            this.ApplySortOptions(model, commerceSearchOptions, searchInformation);

            return(model);
        }
        protected virtual void UpdateOptionsWithSorting(
            string sortField,
            SortDirection?sortDirection,
            CommerceSearchOptions productSearchOptions)
        {
            if (string.IsNullOrEmpty(sortField))
            {
                return;
            }

            productSearchOptions.SortField = sortField;
            if (!sortDirection.HasValue)
            {
                return;
            }

            productSearchOptions.SortDirection = sortDirection == SortDirection.Asc
                                                     ? CommerceConstants.SortDirection.Asc
                                                     : CommerceConstants.SortDirection.Desc;
        }
예제 #6
0
        public ProductListHeaderViewModel GetProductListHeader(Rendering currentRendering, int?pageNumber, string facetValues, string sortField, int?pageSize, CommerceConstants.SortDirection?sortDirection)
        {
            var currentCategory      = _catalogManager.GetCurrentCategoryByUrl();
            var productSearchOptions = new CommerceSearchOptions(pageSize.GetValueOrDefault(currentCategory.ItemsPerPage),
                                                                 pageNumber.GetValueOrDefault(0));

            SetSortParameters(currentCategory, ref sortField, ref sortDirection);
            UpdateOptionsWithFacets(currentCategory.RequiredFacets, facetValues, productSearchOptions);
            UpdateOptionsWithSorting(sortField, sortDirection, productSearchOptions);

            var productListHeaderViewModel = GetProductListHeaderViewModel(productSearchOptions, currentCategory.SortFields, currentCategory.InnerItem, currentRendering);

            if (sortField != null)
            {
                productListHeaderViewModel.SelecterSortField     = sortField;
                productListHeaderViewModel.SelectedSortDirection = sortDirection;
            }

            return(productListHeaderViewModel);
        }
        /// <summary>
        /// This method returns child categories for this category
        /// </summary>
        /// <param name="searchOptions">The options to perform the search with</param>
        /// <param name="categoryItem">The category item whose children to retrieve</param>
        /// <returns>A list of child categories</returns>
        protected CategorySearchResults GetChildCategories(CommerceSearchOptions searchOptions, Item categoryItem)
        {
            var returnList         = new List <Item>();
            var totalPageCount     = 0;
            var totalCategoryCount = 0;

            if (Item != null)
            {
                var searchResponse = SearchNavigation.GetCategoryChildCategories(categoryItem.ID, searchOptions);

                returnList.AddRange(searchResponse.ResponseItems);

                totalCategoryCount = searchResponse.TotalItemCount;
                totalPageCount     = searchResponse.TotalPageCount;
            }

            var results = new CategorySearchResults(returnList, totalCategoryCount, totalPageCount, searchOptions.StartPageIndex, new List <FacetCategory>());

            return(results);
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);
            this.QueryStringToken = StorefrontConstants.QueryStrings.Paging;

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 20;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);
            this.QueryStringToken = StorefrontConstants.QueryStrings.Paging;

            int itemsPerPage = searchOptions?.NumberOfItemsToReturn ?? 20;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber       = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages    = products.TotalPageCount,
                    PageResultCount  = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex   = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }
        }
        /// <summary>
        /// Initializes the view model.
        /// </summary>
        /// <param name="rendering">The rendering.</param>
        /// <param name="products">The list of child products.</param>
        /// <param name="sortFields">The fields to allow sorting on.</param>
        /// <param name="searchOptions">Any search options used to find products in this category.</param>
        public void Initialize(
            Rendering rendering,
            SearchResults products,
            IEnumerable <CommerceQuerySort> sortFields,
            CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = searchOptions?.NumberOfItemsToReturn ?? 0;

            if (products != null)
            {
                ChildProducts = new List <ProductViewModel>();
                foreach (var child in products.SearchResultItems)
                {
                    var productModel = new ProductViewModel(child);
                    productModel.Initialize(this.Rendering);
                    this.ChildProducts.Add(productModel);
                }

                ChildProductFacets = products.Facets;
                if (itemsPerPage > products.SearchResultItems.Count)
                {
                    itemsPerPage = products.SearchResultItems.Count;
                }

                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber       = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages    = products.TotalPageCount,
                    PageResultCount  = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex   = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields;
        }
        protected void ApplySortOptions(ProductListResultModel model, CommerceSearchOptions commerceSearchOptions, CategorySearchInformation searchInformation)
        {
            Assert.ArgumentNotNull(model, nameof(model));
            Assert.ArgumentNotNull(commerceSearchOptions, nameof(commerceSearchOptions));
            Assert.ArgumentNotNull(searchInformation, nameof(searchInformation));

            if (searchInformation.SortFields == null || !searchInformation.SortFields.Any())
            {
                return;
            }

            var sortOptions = new List <SortOptionModel>();

            foreach (CommerceQuerySort sortField in searchInformation.SortFields)
            {
                bool isSelected = sortField.Name.Equals(commerceSearchOptions.SortField);

                var sortOptionAsc = new SortOptionModel
                {
                    Name          = sortField.Name,
                    DisplayName   = sortField.DisplayName,
                    SortDirection = SortDirection.Asc,
                    IsSelected    = isSelected && commerceSearchOptions.SortDirection == CommerceConstants.SortDirection.Asc
                };

                sortOptions.Add(sortOptionAsc);

                var sortOptionDesc = new SortOptionModel
                {
                    Name          = sortField.Name,
                    DisplayName   = sortField.DisplayName,
                    SortDirection = SortDirection.Desc,
                    IsSelected    = isSelected && commerceSearchOptions.SortDirection == CommerceConstants.SortDirection.Desc
                };

                sortOptions.Add(sortOptionDesc);
            }

            model.SortOptions = sortOptions;
        }
예제 #12
0
        public SearchResults GetProducts(
            string catalogName,
            ID categoryId,
            CommerceSearchOptions searchOptions,
            string searchKeyword)
        {
            Assert.ArgumentNotNull(catalogName, nameof(catalogName));

            var commerceSearchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();

            var queryable = this.GetBaseQueryable(catalogName, ProductCommerceSearchItemType);

            if (!ID.IsNullOrEmpty(categoryId))
            {
                queryable = queryable.Where(x => x.CommerceAncestorIds.Contains(categoryId));
            }

            if (!string.IsNullOrEmpty(searchKeyword))
            {
                queryable = queryable.Where(item => item.Name.Contains(searchKeyword) || item["_displayname"].Contains(searchKeyword));
            }

            queryable = commerceSearchManager.AddSearchOptionsToQuery(queryable, searchOptions);

            var results = queryable.GetResults();

            var searchResultsItems = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

            if (searchResultsItems != null)
            {
                return(new SearchResults(
                           searchResultsItems.ResponseItems,
                           searchResultsItems.TotalItemCount,
                           searchResultsItems.TotalPageCount,
                           searchOptions.StartPageIndex,
                           searchResultsItems.Facets.ToList()));
            }

            return(new SearchResults());
        }
 protected virtual void UpdateOptionsWithFacets(
     IEnumerable <CommerceQueryFacet> facets,
     string valueQueryString,
     CommerceSearchOptions productSearchOptions)
 {
     Assert.ArgumentNotNull(productSearchOptions, nameof(productSearchOptions));
     if (facets == null || !facets.Any())
     {
         return;
     }
     if (!string.IsNullOrEmpty(valueQueryString))
     {
         string str1 = HttpContext.Current.Server.UrlDecode(valueQueryString);
         if (str1 != null)
         {
             string str2     = str1;
             char[] chArray1 = new char[1] {
                 '&'
             };
             foreach (string str3 in str2.Split(chArray1))
             {
                 string[]           strArray           = str3.Split('=');
                 string             name               = strArray[0];
                 CommerceQueryFacet commerceQueryFacet = facets.FirstOrDefault(item => item.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
                 if (commerceQueryFacet != null)
                 {
                     string str4     = strArray[1];
                     char[] chArray2 = new char[1] {
                         '|'
                     };
                     foreach (string str5 in str4.Split(chArray2))
                     {
                         commerceQueryFacet.Values.Add(str5);
                     }
                 }
             }
         }
     }
     productSearchOptions.FacetFields = facets;
 }
예제 #14
0
        public SearchInfo GetSearchInfo(
            Item datasource,
            string searchKeyword,
            int?pageNumber,
            string facetValues,
            string sortField,
            int?pageSize,
            CommerceConstants.SortDirection?sortDirection)
        {
            if (this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] != null)
            {
                return((SearchInfo)this.CurrentSiteContext.Items[CurrentSearchInfoKeyName]);
            }

            var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>();

            var searchInfo = new SearchInfo
            {
                SearchKeyword  = searchKeyword ?? string.Empty,
                RequiredFacets = searchManager.GetFacetFieldsForItem(datasource),
                SortFields     = searchManager.GetSortFieldsForItem(datasource),
                Catalog        = StorefrontManager.CurrentStorefront.DefaultCatalog,
                ItemsPerPage   = pageSize ?? searchManager.GetItemsPerPageForItem(datasource)
            };

            if (searchInfo.ItemsPerPage == 0)
            {
                searchInfo.ItemsPerPage = StorefrontConstants.Settings.DefaultItemsPerPage;
            }

            var productSearchOptions = new CommerceSearchOptions(searchInfo.ItemsPerPage, pageNumber.GetValueOrDefault(0));

            UpdateOptionsWithFacets(searchInfo.RequiredFacets, facetValues, productSearchOptions);
            UpdateOptionsWithSorting(sortField, sortDirection, productSearchOptions);
            searchInfo.SearchOptions = productSearchOptions;

            this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] = searchInfo;

            return(searchInfo);
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, IEnumerable<CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 0;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * searchOptions.NumberOfItemsToReturn;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields ?? Enumerable.Empty<CommerceQuerySort>();
        }
        /// <summary>
        /// Builds a category view model or retrieves it if it already exists
        /// </summary>
        /// <param name="productSearchOptions">The product options class for finding child products</param>
        /// <param name="sortFields">The fields to sort he results on</param>
        /// <param name="categoryItem">The category item to base the view model on</param>
        /// <param name="rendering">The rendering to initialize the model with</param>
        /// <param name="cacheName">Name of the cache.</param>
        /// <returns>
        /// A category view model
        /// </returns>
        protected virtual CategoryViewModel GetCategoryViewModel(CommerceSearchOptions productSearchOptions, IEnumerable <CommerceQuerySort> sortFields, Item categoryItem, Rendering rendering, string cacheName)
        {
            string cacheKey = "Category/" + cacheName;
            bool   noCache  = (string.IsNullOrEmpty(cacheName));

            if (this.CurrentSiteContext.Items[cacheKey] != null && !noCache)
            {
                return((CategoryViewModel)this.CurrentSiteContext.Items[cacheKey]);
            }

            var           categoryViewModel = new CategoryViewModel(categoryItem);
            SearchResults childProducts     = null;

            if (productSearchOptions != null)
            {
                childProducts = this.GetChildProducts(productSearchOptions, categoryItem);
            }

            categoryViewModel.Initialize(rendering, childProducts, sortFields, productSearchOptions);
            if (childProducts != null && childProducts.SearchResultItems.Count > 0)
            {
                this.CatalogManager.GetProductBulkPrices(categoryViewModel.ChildProducts);
                this.InventoryManager.GetProductsStockStatus(this.CurrentStorefront, categoryViewModel.ChildProducts);

                foreach (var productViewModel in categoryViewModel.ChildProducts)
                {
                    Item productItem = childProducts.SearchResultItems.Where(item => item.Name == productViewModel.ProductId).Single();
                    productViewModel.CustomerAverageRating = this.CatalogManager.GetProductRating(productItem);
                }
            }

            if (!noCache)
            {
                this.CurrentSiteContext.Items[cacheKey] = categoryViewModel;
            }

            return(categoryViewModel);
        }
예제 #17
0
        /// <summary>
        /// This method returns a list of ProductSearchResults for a datasource
        /// </summary>
        /// <param name="dataSource">The datasource to perform the searches with</param>
        /// <param name="productSearchOptions">The search options.</param>
        /// <returns>A list of ProductSearchResults</returns>       
        public MultipleProductSearchResults GetMultipleProductSearchResults(BaseItem dataSource, CommerceSearchOptions productSearchOptions)
        {
            Assert.ArgumentNotNull(productSearchOptions, "productSearchOptions");

            MultilistField searchesField = dataSource.Fields["Named Searches"];
            var searches = searchesField.GetItems();
            var productsSearchResults = new List<SearchResults>();
            foreach (Item search in searches)
            {
                var productsSearchResult = GetProductSearchResults(search, productSearchOptions);
                if (productsSearchResult != null)
                {
                    productsSearchResult.DisplayName = search["title"];
                    if (search.Fields["implicit"] != null)
                    {
                        productsSearchResult.Implicit = ((Sitecore.Data.Fields.CheckboxField)search.Fields["implicit"]).Checked;
                    }
                    productsSearchResults.Add(productsSearchResult);
                }
            }

            return new MultipleProductSearchResults(productsSearchResults);
        }
        /// <summary>
        /// Builds a product list header view model
        /// </summary>
        /// <param name="searchOptions">The search options.</param>
        /// <param name="searchKeyword">The search keyword.</param>
        /// <param name="rendering">The rendering.</param>
        /// <returns>The product list header view model.</returns>
        protected virtual ProductListHeaderViewModel GetSiteContentListHeaderViewModel(CommerceSearchOptions searchOptions, string searchKeyword, Rendering rendering)
        {
            var viewModel = new ProductListHeaderViewModel {
                PageSizeClass = StorefrontConstants.StyleClasses.ChangeSiteContentPageSize
            };
            SearchResults searchResults = null;

            if (searchOptions != null)
            {
                searchResults = this.GetSiteContentSearchResults(searchOptions, searchKeyword, rendering);
            }

            viewModel.Initialize(rendering, searchResults, null, searchOptions);

            return(viewModel);
        }
        /// <summary>
        /// Adds and required sorting to the options class
        /// </summary>
        /// <param name="sortField">The field to sort on</param>
        /// <param name="sortDirection">The direction to perform the sorting</param>
        /// <param name="productSearchOptions">The options class to add the sorting to.</param>
        protected void UpdateOptionsWithSorting(string sortField, CommerceConstants.SortDirection?sortDirection, CommerceSearchOptions productSearchOptions)
        {
            if (!string.IsNullOrEmpty(sortField))
            {
                productSearchOptions.SortField = sortField;

                if (sortDirection.HasValue)
                {
                    productSearchOptions.SortDirection = sortDirection.Value;
                }

                ViewBag.SortField     = sortField;
                ViewBag.SortDirection = sortDirection;
            }
        }
        /// <summary>
        /// Searches for catalog items based on keyword
        /// </summary>
        /// <param name="keyword">The keyword to search for.</param>
        /// <param name="catalogName">The name of the catalog containing the keyword</param>		
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>A list of child products</returns>
        public static SearchResponse SearchCatalogItemsByKeyword(string keyword, string catalogName, CommerceSearchOptions searchOptions)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(catalogName, "catalogName");
            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex(catalogName);

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable<CommerceProductSearchResultItem>()
                    .Where(item => item.Content.Contains(keyword))
                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product || item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                    .Where(item => item.CatalogName == catalogName)
                    .Where(item => item.Language == CurrentLanguageName)
                    .Select(p => new CommerceProductSearchResultItem()
                    {
                        ItemId = p.ItemId,
                        Uri = p.Uri
                    });

                searchResults = searchManager.AddSearchOptionsToQuery<CommerceProductSearchResultItem>(searchResults, searchOptions);

                var results = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return response;
            }
        }
        /// <summary>
        /// Builds a category view model or retrieves it if it already exists
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="productSearchOptions">The product options class for finding child products</param>
        /// <param name="sortFields">The fields to sort he results on</param>
        /// <param name="searchKeyword">The keyword to search for</param>
        /// <param name="catalogName">The name of the catalog to search against</param>
        /// <param name="rendering">The rendering to initialize the model with</param>
        /// <returns>
        /// A category view model
        /// </returns>
        protected virtual CategoryViewModel GetProductListViewModel([NotNull] CommerceStorefront storefront, CommerceSearchOptions productSearchOptions, IEnumerable <CommerceQuerySort> sortFields, string searchKeyword, string catalogName, Rendering rendering)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

            if (this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName] == null)
            {
                var categoryViewModel = new CategoryViewModel();

                var childProducts = this.GetChildProducts(productSearchOptions, searchKeyword, catalogName);

                categoryViewModel.Initialize(rendering, childProducts, sortFields, productSearchOptions);
                if (childProducts != null && childProducts.SearchResultItems.Count > 0)
                {
                    this.CatalogManager.GetProductBulkPrices(this.CurrentVisitorContext, categoryViewModel.ChildProducts);

                    this.CatalogManager.InventoryManager.GetProductsStockStatusForList(storefront, categoryViewModel.ChildProducts);

                    foreach (var productViewModel in categoryViewModel.ChildProducts)
                    {
                        Item productItem = childProducts.SearchResultItems.Where(item => item.Name == productViewModel.ProductId).Single();
                        productViewModel.CustomerAverageRating = this.CatalogManager.GetProductRating(productItem);
                    }
                }

                this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName] = categoryViewModel;
            }

            var viewModel = (CategoryViewModel)this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName];

            return(viewModel);
        }
        /// <summary>
        /// Gets all the products under a specific category
        /// </summary>
        /// <param name="categoryId">The parent category id</param>
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>A list of child products</returns>
        public static SearchResponse GetCategoryChildCategories(ID categoryId, CommerceSearchOptions searchOptions)
        {
            SearchResponse response = new SearchResponse();

            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex();

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable<CommerceBaseCatalogSearchResultItem>()
                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                    .Where(item => item.Language == CurrentLanguageName)
                    .Where(item => item.ItemId == categoryId)
                    .Select(p => p);

                var list = searchResults.ToList();
                if (list.Count > 0)
                {
                    if (list[0].Fields.ContainsKey(StorefrontConstants.KnownIndexFields.ChildCategoriesSequence))
                    {
                        var childCategoryDelimitedString = list[0][StorefrontConstants.KnownIndexFields.ChildCategoriesSequence];

                        string[] categoryIdArray = childCategoryDelimitedString.Split('|');

                        foreach (var childCategoryId in categoryIdArray)
                        {
                            var childCategoryItem = Sitecore.Context.Database.GetItem(ID.Parse(childCategoryId));
                            if (childCategoryItem != null)
                            {
                                response.ResponseItems.Add(childCategoryItem);
                            }
                        }
                    }
                }
            }

            return response;
        }
        public static SearchResponse GetProductByProductId(string productId, CommerceSearchOptions searchOptions)
        {
            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex();

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable<CommerceProductSearchResultItem>()
                                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product)
                                    .Where(item => item.Language == CurrentLanguageName)
                                    .Where(item => item.Name == productId)
                                    .Select(p => new CommerceProductSearchResultItem()
                                    {
                                        ItemId = p.ItemId,
                                        Uri = p.Uri
                                    });

                searchResults = searchManager.AddSearchOptionsToQuery<CommerceProductSearchResultItem>(searchResults, searchOptions);

                var results = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return response;
            }
        }
예제 #24
0
        /// <summary>
        /// Gets all the products under a specific category
        /// </summary>
        /// <param name="categoryId">The parent category id</param>
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>A list of child products</returns>
        public static SearchResponse GetCategoryChildCategories(ID categoryId, CommerceSearchOptions searchOptions)
        {
            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex();

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable<CommerceBaseCatalogSearchResultItem>()
                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                    .Where(item => item.Language == CurrentLanguageName)
                    .Where(item => item.CommerceAncestorIds.Contains(categoryId))
                    .Select(p => new CommerceBaseCatalogSearchResultItem()
                    {
                        ItemId = p.ItemId,
                        Uri = p.Uri
                    });

                searchResults = searchManager.AddSearchOptionsToQuery<CommerceBaseCatalogSearchResultItem>(searchResults, searchOptions);

                var results = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return response;
            }
        }
예제 #25
0
        /// <summary>
        /// Builds a category view model or retrieves it if it already exists
        /// </summary>
        /// <param name="productSearchOptions">The product options class for finding child products</param>
        /// <param name="categorySearchOptions">The category options classf or finding child categories</param>
        /// <param name="sortFields">The fields to sort he results on</param>
        /// <param name="item">The item.</param>
        /// <param name="rendering">The rendering to initialize the model with</param>
        /// <returns>
        /// A category view model
        /// </returns>
        protected virtual LandingPageViewModel GetLandingPageViewModel(CommerceSearchOptions productSearchOptions, CommerceSearchOptions categorySearchOptions, IEnumerable<CommerceQuerySort> sortFields, Item item, Rendering rendering)
        {
            if (this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName] == null)
            {
                var categoryViewModel = new LandingPageViewModel(item);
                this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName] = categoryViewModel;
            }

            var viewModel = (LandingPageViewModel)this.CurrentSiteContext.Items[CurrentCategoryViewModelKeyName];
            return viewModel;
        }
예제 #26
0
 public IQueryable <T> AddSearchOptionsToQuery <T>(IQueryable <T> searchResults, CommerceSearchOptions connectSearchOptions)
     where T : ISearchResult
 {
     return(_connectSearchManager.AddSearchOptionsToQuery(searchResults, connectSearchOptions));
 }
예제 #27
0
        public MultipleProductSearchResults GetMultipleProductList(Item datasource, Rendering currentRendering, CommerceSearchOptions productSearchOptions)
        {
            var multipleProductSearchResults = GetMultipleProductSearchResults(datasource, productSearchOptions);

            if (multipleProductSearchResults != null)
            {
                multipleProductSearchResults.Initialize(currentRendering);
                multipleProductSearchResults.DisplayName = datasource.DisplayName;

                var products = multipleProductSearchResults.ProductSearchResults.SelectMany(productSearchResult => productSearchResult.Products).ToList();
                _catalogManager.GetProductBulkPrices(this.CurrentVisitorContext, products);
                _inventoryManager.GetProductsStockStatusForList(this.CurrentStorefront, products);

                foreach (var productViewModel in products)
                {
                    Item productItem = multipleProductSearchResults.SearchResults
                                       .SelectMany(productSearchResult => productSearchResult.SearchResultItems)
                                       .FirstOrDefault(item => item.Name == productViewModel.ProductId);
                    productViewModel.CustomerAverageRating = _catalogManager.GetProductRating(productItem);
                }
            }

            return(multipleProductSearchResults);
        }
예제 #28
0
        /// <summary>
        /// This method returns child categories for this category
        /// </summary>
        /// <param name="searchOptions">The options to perform the search with</param>
        /// <param name="categoryItem">The category item whose children to retrieve</param>
        /// <returns>A list of child categories</returns>       
        protected CategorySearchResults GetChildCategories(CommerceSearchOptions searchOptions, Item categoryItem)
        {
            var returnList = new List<Item>();
            var totalPageCount = 0;
            var totalCategoryCount = 0;

            if (Item != null)
            {
                var searchResponse = SearchNavigation.GetCategoryChildCategories(categoryItem.ID, searchOptions);

                returnList.AddRange(searchResponse.ResponseItems);

                totalCategoryCount = searchResponse.TotalItemCount;
                totalPageCount = searchResponse.TotalPageCount;
            }

            var results = new CategorySearchResults(returnList, totalCategoryCount, totalPageCount, searchOptions.StartPageIndex, new List<FacetCategory>());

            return results;
        }
예제 #29
0
        /// <summary>
        /// This method returns child products for this category
        /// </summary>
        /// <param name="searchOptions">The options to perform the search with</param>
        /// <param name="categoryItem">The category item whose children to retrieve</param>
        /// <returns>A list of child products</returns>        
        protected SearchResults GetChildProducts(CommerceSearchOptions searchOptions, Item categoryItem)
        {
            IEnumerable<CommerceQueryFacet> facets = null;
            var returnList = new List<Item>();
            var totalPageCount = 0;
            var totalProductCount = 0;

            if (RenderingContext.Current.Rendering.Item != null)
            {
                SearchResponse searchResponse = null;
                if (CatalogUtility.IsItemDerivedFromCommerceTemplate(categoryItem, CommerceConstants.KnownTemplateIds.CommerceDynamicCategoryTemplate) || categoryItem.TemplateName == "Commerce Named Search")
                {
                    try
                    {
                        var defaultBucketQuery = categoryItem[CommerceConstants.KnownSitecoreFieldNames.DefaultBucketQuery];
                        var persistendBucketFilter = categoryItem[CommerceConstants.KnownSitecoreFieldNames.PersistentBucketFilter];
                        persistendBucketFilter = CleanLanguageFromFilter(persistendBucketFilter);
                        searchResponse = SearchNavigation.SearchCatalogItems(defaultBucketQuery, persistendBucketFilter, searchOptions);
                    }
                    catch (Exception ex)
                    {
                        Helpers.LogException(ex, this);
                    }
                }
                else
                {
                    searchResponse = SearchNavigation.GetCategoryProducts(categoryItem.ID, searchOptions);
                }

                if (searchResponse != null)
                {
                    returnList.AddRange(searchResponse.ResponseItems);

                    totalProductCount = searchResponse.TotalItemCount;
                    totalPageCount = searchResponse.TotalPageCount;
                    facets = searchResponse.Facets;
                }
            }

            var results = new SearchResults(returnList, totalProductCount, totalPageCount, searchOptions.StartPageIndex, facets);
            return results;
        }
예제 #30
0
        /// <summary>
        /// This method returns the ProductSearchResults for a datasource
        /// </summary>
        /// <param name="dataSource">The datasource to perform the search with</param>
        /// <param name="productSearchOptions">The search options.</param>
        /// <returns>A ProductSearchResults</returns>     
        public SearchResults GetProductSearchResults(Item dataSource, CommerceSearchOptions productSearchOptions)
        {
            Assert.ArgumentNotNull(productSearchOptions, "productSearchOptions");

            if (dataSource != null)
            {
                int totalProductCount = 0;
                int totalPageCount = 0;
                string error = string.Empty;

                if (dataSource.TemplateName == "Commerce Named Search" || dataSource.TemplateName == "Named Search")
                {
                    var returnList = new List<Item>();
                    IEnumerable<CommerceQueryFacet> facets = null;
                    var searchOptions = new CommerceSearchOptions(10, 0);
                    var defaultBucketQuery = dataSource[CommerceConstants.KnownSitecoreFieldNames.DefaultBucketQuery];
                    var persistendBucketFilter = CleanLanguageFromFilter(dataSource[CommerceConstants.KnownSitecoreFieldNames.PersistentBucketFilter]);

                    try
                    {
                        var searchResponse = SearchNavigation.SearchCatalogItems(defaultBucketQuery, persistendBucketFilter, searchOptions);

                        if (searchResponse != null)
                        {
                            returnList.AddRange(searchResponse.ResponseItems);

                            totalProductCount = searchResponse.TotalItemCount;
                            totalPageCount = searchResponse.TotalPageCount;
                            facets = searchResponse.Facets;
                        }
                    }
                    catch (Exception ex)
                    {
                        error = ex.Message;
                    }

                    return new SearchResults(returnList, totalProductCount, totalPageCount, searchOptions.StartPageIndex, facets);
                }

                var childProducts = GetChildProducts(productSearchOptions, dataSource).SearchResultItems;
                return new SearchResults(childProducts, totalProductCount, totalPageCount, productSearchOptions.StartPageIndex, new List<CommerceQueryFacet>());
            }

            return null;
        }
예제 #31
0
        /// <summary>
        /// Gets all the products under a specific category
        /// </summary>
        /// <param name="categoryId">The parent category id</param>
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>A list of child products</returns>
        public static CategorySearchResults GetCategoryChildCategories(ID categoryId, CommerceSearchOptions searchOptions)
        {
            List <Item> childCategoryList = new List <Item>();

            var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();
            var searchIndex   = searchManager.GetIndex();

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable <CommerceBaseCatalogSearchResultItem>()
                                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                                    .Where(item => item.Language == CurrentLanguageName)
                                    .Where(item => item.ItemId == categoryId)
                                    .Select(p => p);

                var list = searchResults.ToList();
                if (list.Count > 0)
                {
                    if (list[0].Fields.ContainsKey(StorefrontConstants.KnownIndexFields.ChildCategoriesSequence))
                    {
                        var childCategoryDelimitedString = list[0][StorefrontConstants.KnownIndexFields.ChildCategoriesSequence];

                        string[] categoryIdArray = childCategoryDelimitedString.Split('|');

                        foreach (var childCategoryId in categoryIdArray)
                        {
                            var childCategoryItem = Sitecore.Context.Database.GetItem(ID.Parse(childCategoryId));
                            if (childCategoryItem != null)
                            {
                                childCategoryList.Add(childCategoryItem);
                            }
                        }
                    }
                }
            }

            return(new CategorySearchResults(childCategoryList, childCategoryList.Count, 1, 1, new List <FacetCategory>()));
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, IEnumerable <CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = searchOptions?.NumberOfItemsToReturn ?? 0;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * searchOptions.NumberOfItemsToReturn;
                Pagination = new PaginationModel
                {
                    PageNumber       = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages    = products.TotalPageCount,
                    PageResultCount  = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex   = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields ?? Enumerable.Empty <CommerceQuerySort>();
        }
예제 #33
0
        public static SearchResponse GetNavigationCategories(string navigationDataSource, CommerceSearchOptions searchOptions)
        {
            ID  navigationId;
            var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();
            var searchIndex   = searchManager.GetIndex();

            if (navigationDataSource.IsGuid())
            {
                navigationId = ID.Parse(navigationDataSource);
            }
            else
            {
                using (var context = searchIndex.CreateSearchContext())
                {
                    var query = LinqHelper.CreateQuery <Sitecore.ContentSearch.SearchTypes.SitecoreUISearchResultItem>(context, SearchStringModel.ParseDatasourceString(navigationDataSource))
                                .Select(result => result.GetItem().ID);
                    if (query != null & query.Any())
                    {
                        navigationId = query.First();
                    }
                    else
                    {
                        return(new SearchResponse());
                    }
                }
            }

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable <CommerceBaseCatalogSearchResultItem>()
                                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                                    .Where(item => item.Language == CurrentLanguageName)
                                    .Where(item => item.CommerceAncestorIds.Contains(navigationId))
                                    .Select(p => new CommerceBaseCatalogSearchResultItem()
                {
                    ItemId = p.ItemId,
                    Uri    = p.Uri
                });

                searchResults = searchManager.AddSearchOptionsToQuery <CommerceBaseCatalogSearchResultItem>(searchResults, searchOptions);

                var results  = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return(response);
            }
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="childCategories">The list of child categories</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, CategorySearchResults childCategories, IEnumerable<CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            ChildProducts = products == null ? new List<Item>() : products.SearchResultItems;
        }
        public static SearchResponse GetNavigationCategories(string navigationDataSource, CommerceSearchOptions searchOptions)
        {
            ID navigationId;
            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex();

            if (navigationDataSource.IsGuid())
            {
                navigationId = ID.Parse(navigationDataSource);
            }
            else
            {
                using (var context = searchIndex.CreateSearchContext())
                {
                    var query = LinqHelper.CreateQuery<Sitecore.ContentSearch.SearchTypes.SitecoreUISearchResultItem>(context, SearchStringModel.ParseDatasourceString(navigationDataSource))
                        .Select(result => result.GetItem().ID);
                    if (query != null & query.Any())
                    {
                        navigationId = query.First();
                    }
                    else
                    {
                        return new SearchResponse();
                    }
                }
            }

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable<CommerceBaseCatalogSearchResultItem>()
                   .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                   .Where(item => item.Language == CurrentLanguageName)
                   .Where(item => item.CommerceAncestorIds.Contains(navigationId))
                    .Select(p => new CommerceBaseCatalogSearchResultItem()
                    {
                        ItemId = p.ItemId,
                        Uri = p.Uri
                    });

                searchResults = searchManager.AddSearchOptionsToQuery<CommerceBaseCatalogSearchResultItem>(searchResults, searchOptions);

                var results = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return response;
            }
        }
        protected SearchResults GetChildProducts(string searchKeyword, CommerceSearchOptions searchOptions, Item categoryItem)
        {
            SearchResults searchResults = this.searchManager.GetProducts(this.storefrontContext.CatalogName, categoryItem?.ID, searchOptions, searchKeyword);

            return(searchResults);
        }
        /// <summary>
        /// Executes a search to retrieve catalog items.
        /// </summary>
        /// <param name="defaultBucketQuery">The search default bucket query value.</param>
        /// <param name="persistentBucketFilter">The search persistent bucket filter value.</param>
        /// <param name="searchOptions">The search options.</param>
        /// <returns>A list of catalog items.</returns>
        public static SearchResponse SearchCatalogItems(string defaultBucketQuery, string persistentBucketFilter, CommerceSearchOptions searchOptions)
        {
            var searchManager = CommerceTypeLoader.CreateInstance<ICommerceSearchManager>();
            var searchIndex = searchManager.GetIndex();

            var defaultQuery = defaultBucketQuery.Replace("&", ";");
            var persistentQuery = persistentBucketFilter.Replace("&", ";");
            var combinedQuery = CombineQueries(persistentQuery, defaultQuery);
            var searchStringModel = SearchStringModel.ParseDatasourceString(combinedQuery);

            using (var context = searchIndex.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
            {
                var query = LinqHelper.CreateQuery<Sitecore.ContentSearch.SearchTypes.SitecoreUISearchResultItem>(context, searchStringModel)
                    .Where(item => item.Language == SearchNavigation.CurrentLanguageName);

                query = searchManager.AddSearchOptionsToQuery(query, searchOptions);

                var results = query.GetResults();
                var response = SearchResponse.CreateFromUISearchResultsItems(searchOptions, results);

                return response;
            }
        }
        protected virtual void UpdateOptionsWithFacets(IList <CommerceQueryFacet> facets, NameValueCollection valueQuery, CommerceSearchOptions productSearchOptions)
        {
            if (facets == null || !facets.Any())
            {
                return;
            }

            if (valueQuery != null)
            {
                foreach (string name in valueQuery)
                {
                    var commerceQueryFacet = facets.FirstOrDefault(item => item.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
                    if (commerceQueryFacet != null)
                    {
                        var facetValues = valueQuery[name];
                        foreach (var facetValue in facetValues.Split('|'))
                        {
                            commerceQueryFacet.Values.Add(facetValue);
                        }
                    }
                }
            }

            productSearchOptions.FacetFields = facets;
        }
        /// <summary>
        /// Searches for site content items based on keyword
        /// </summary>
        /// <param name="keyword">The keyword to search for.</param>
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>
        /// A list of child products
        /// </returns>
        public static SearchResponse SearchSiteByKeyword(string keyword, CommerceSearchOptions searchOptions)
        {
            const string IndexNameFormat = "sitecore_{0}_index";
            string indexName = string.Format(
                System.Globalization.CultureInfo.InvariantCulture,
                IndexNameFormat,
                Sitecore.Context.Database.Name);

            var searchIndex = ContentSearchManager.GetIndex(indexName);
            using (var context = searchIndex.CreateSearchContext())
            {
                //var rootSearchPath = Sitecore.IO.FileUtil.MakePath(Sitecore.Context.Site.ContentStartPath, "Home", '/');
                var searchResults = context.GetQueryable<SearchResultItem>();
                searchResults = searchResults.Where(item => item.Path.StartsWith(Sitecore.Context.Site.ContentStartPath));
                searchResults = searchResults.Where(item => item[StorefrontConstants.KnownIndexFields.SiteContentItem] == "1");
                searchResults = searchResults.Where(item => item.Language == CurrentLanguageName);
                searchResults = searchResults.Where(GetContentExpression(keyword));
                searchResults = searchResults.Page(searchOptions.StartPageIndex, searchOptions.NumberOfItemsToReturn);

                var results = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return response;
            }
        }
        /// <summary>
        /// This method returns a list of ProductSearchResults for a datasource
        /// </summary>
        /// <param name="dataSource">The datasource to perform the searches with</param>
        /// <param name="productSearchOptions">The search options.</param>
        /// <returns>A list of ProductSearchResults</returns>
        public MultipleProductSearchResults GetMultipleProductSearchResults(BaseItem dataSource, CommerceSearchOptions productSearchOptions)
        {
            Assert.ArgumentNotNull(productSearchOptions, "productSearchOptions");

            MultilistField searchesField         = dataSource.Fields[StorefrontConstants.KnownFieldNames.NamedSearches];
            var            searches              = searchesField.GetItems();
            var            productsSearchResults = new List <SearchResults>();

            foreach (Item search in searches)
            {
                var itemType = search.ItemType();
                switch (itemType)
                {
                case StorefrontConstants.ItemTypes.NamedSearch:
                {
                    var productsSearchResult = GetProductSearchResults(search, productSearchOptions);
                    if (productsSearchResult != null)
                    {
                        productsSearchResult.NamedSearchItem = search;
                        productsSearchResult.DisplayName     = search[StorefrontConstants.KnownFieldNames.Title];
                        productsSearchResults.Add(productsSearchResult);
                    }

                    break;
                }

                case StorefrontConstants.ItemTypes.SelectedProducts:
                {
                    int           itemCount        = 0;
                    SearchResults staticSearchList = new SearchResults();
                    staticSearchList.DisplayName     = search[StorefrontConstants.KnownFieldNames.Title];
                    staticSearchList.NamedSearchItem = search;

                    MultilistField productListField = search.Fields[StorefrontConstants.KnownFieldNames.ProductList];
                    var            productList      = productListField.GetItems();
                    foreach (Item productItem in productList)
                    {
                        var catalogItemtype = productItem.ItemType();
                        if (catalogItemtype == StorefrontConstants.ItemTypes.Category || catalogItemtype == StorefrontConstants.ItemTypes.Product)
                        {
                            staticSearchList.SearchResultItems.Add(productItem);

                            itemCount++;
                        }
                    }

                    staticSearchList.TotalItemCount = itemCount;
                    staticSearchList.TotalPageCount = itemCount;
                    productsSearchResults.Add(staticSearchList);

                    break;
                }
                }
            }

            return(new MultipleProductSearchResults(productsSearchResults));
        }
        /// <summary>
        /// Gets a <see cref="SiteContentSearchResultsViewModel" /> object that represents the site content search results.
        /// </summary>
        /// <param name="searchOptions">The search options.</param>
        /// <param name="searchKeyword">The search keyword.</param>
        /// <param name="rendering">The rendering.</param>
        /// <returns>The site content search result view model.</returns>
        protected virtual SiteContentSearchResultsViewModel GetSiteContentListViewModel(CommerceSearchOptions searchOptions, string searchKeyword, Rendering rendering)
        {
            var model = new SiteContentSearchResultsViewModel();

            model.Initialize(rendering);

            var searchResults = this.GetSiteContentSearchResults(searchOptions, searchKeyword, rendering);

            if (searchResults != null)
            {
                model.ContentItems = searchResults.SearchResultItems
                                     .Select(item => SiteContentViewModel.Create(item))
                                     .ToList();
            }

            return(model);
        }
예제 #42
0
        /// <summary>
        /// Takes a collection of a facets and a querystring of facet values and adds the values to the collection
        /// </summary>
        /// <param name="facets">The facet collection</param>
        /// <param name="valueQueryString">The values to add to the collection in querystring format</param>
        /// <param name="productSearchOptions">The options to update with facets</param>
        protected void UpdateOptionsWithFacets(IEnumerable<CommerceQueryFacet> facets, string valueQueryString, CommerceSearchOptions productSearchOptions)
        {
            if (facets != null && facets.Any())
            {
                if (!string.IsNullOrEmpty(valueQueryString))
                {
                    var facetValuesCombos = valueQueryString.Split(new char[] { '&' });

                    foreach (var facetValuesCombo in facetValuesCombos)
                    {
                        var facetValues = facetValuesCombo.Split(new char[] { '=' });

                        var name = facetValues[0];

                        var existingFacet = facets.FirstOrDefault(item => item.Name.Equals(name, System.StringComparison.OrdinalIgnoreCase));

                        if (existingFacet != null)
                        {
                            var values = facetValues[1].Split(new char[] { StorefrontConstants.QueryStrings.FacetsSeparator });

                            foreach (var value in values)
                            {
                                existingFacet.Values.Add(value);
                            }
                        }
                    }
                }

                productSearchOptions.FacetFields = facets;
            }
        }
        /// <summary>
        /// Takes a collection of a facets and a querystring of facet values and adds the values to the collection
        /// </summary>
        /// <param name="facets">The facet collection</param>
        /// <param name="valueQueryString">The values to add to the collection in querystring format</param>
        /// <param name="productSearchOptions">The options to update with facets</param>
        protected void UpdateOptionsWithFacets(IEnumerable <CommerceQueryFacet> facets, string valueQueryString, CommerceSearchOptions productSearchOptions)
        {
            if (facets != null && facets.Any())
            {
                if (!string.IsNullOrEmpty(valueQueryString))
                {
                    var facetValuesCombos = valueQueryString.Split(new char[] { '&' });

                    foreach (var facetValuesCombo in facetValuesCombos)
                    {
                        var facetValues = facetValuesCombo.Split(new char[] { '=' });

                        var name = facetValues[0];

                        var existingFacet = facets.FirstOrDefault(item => item.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

                        if (existingFacet != null)
                        {
                            var values = facetValues[1].Split(new char[] { StorefrontConstants.QueryStrings.FacetsSeparator });

                            foreach (var value in values)
                            {
                                existingFacet.Values.Add(value);
                            }
                        }
                    }
                }

                productSearchOptions.FacetFields = facets;
            }
        }
예제 #44
0
        /// <summary>
        /// Searches for catalog items based on keyword
        /// </summary>
        /// <param name="keyword">The keyword to search for.</param>
        /// <param name="catalogName">The name of the catalog containing the keyword</param>
        /// <param name="searchOptions">The paging options for this query</param>
        /// <returns>A list of child products</returns>
        public static SearchResponse SearchCatalogItemsByKeyword(string keyword, string catalogName, CommerceSearchOptions searchOptions)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(catalogName, "catalogName");
            var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();
            var searchIndex   = searchManager.GetIndex(catalogName);

            using (var context = searchIndex.CreateSearchContext())
            {
                var searchResults = context.GetQueryable <CommerceProductSearchResultItem>()
                                    .Where(item => item.Name.Equals(keyword) || item["_displayname"].Equals(keyword) || item.Content.Contains(keyword))
                                    .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product || item.CommerceSearchItemType == CommerceSearchResultItemType.Category)
                                    .Where(item => item.CatalogName == catalogName)
                                    .Where(item => item.Language == CurrentLanguageName)
                                    .Select(p => new CommerceProductSearchResultItem()
                {
                    ItemId = p.ItemId,
                    Uri    = p.Uri
                });

                searchResults = searchManager.AddSearchOptionsToQuery <CommerceProductSearchResultItem>(searchResults, searchOptions);

                var results  = searchResults.GetResults();
                var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results);

                return(response);
            }
        }
예제 #45
0
 public static SearchResponse CreateFromUISearchResultsItems(
     CommerceSearchOptions searchOptions,
     SearchResults <SitecoreUISearchResultItem> sitecoreSearchResults)
 {
     return(Create(searchOptions, sitecoreSearchResults, i => i.GetItem()));
 }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, IEnumerable<CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 0;

            if (products != null)
            {
                ChildProducts = new List<ProductViewModel>();
                foreach (var child in products.SearchResultItems)
                {
                    var productModel = new ProductViewModel(child);
                    productModel.Initialize(this.Rendering);
                    this.ChildProducts.Add(productModel);
                }

                ChildProductFacets = products.Facets;
                if (itemsPerPage > products.SearchResultItems.Count)
                {
                    itemsPerPage = products.SearchResultItems.Count;
                }

                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields;
        }
예제 #47
0
        /// <summary>
        /// Executes a search to retrieve catalog items.
        /// </summary>
        /// <param name="defaultBucketQuery">The search default bucket query value.</param>
        /// <param name="persistentBucketFilter">The search persistent bucket filter value.</param>
        /// <param name="searchOptions">The search options.</param>
        /// <returns>A list of catalog items.</returns>
        public static SearchResponse SearchCatalogItems(string defaultBucketQuery, string persistentBucketFilter, CommerceSearchOptions searchOptions)
        {
            var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();
            var searchIndex   = searchManager.GetIndex();

            var defaultQuery      = defaultBucketQuery.Replace("&", ";");
            var persistentQuery   = persistentBucketFilter.Replace("&", ";");
            var combinedQuery     = CombineQueries(persistentQuery, defaultQuery);
            var searchStringModel = SearchStringModel.ParseDatasourceString(combinedQuery);

            using (var context = searchIndex.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
            {
                var query = LinqHelper.CreateQuery <Sitecore.ContentSearch.SearchTypes.SitecoreUISearchResultItem>(context, searchStringModel)
                            .Where(item => item.Language == SearchNavigation.CurrentLanguageName);

                query = searchManager.AddSearchOptionsToQuery(query, searchOptions);

                var results  = query.GetResults();
                var response = SearchResponse.CreateFromUISearchResultsItems(searchOptions, results);

                return(response);
            }
        }
예제 #48
0
        /// <summary>
        /// Adds and required sorting to the options class
        /// </summary>
        /// <param name="sortField">The field to sort on</param>
        /// <param name="sortDirection">The direction to perform the sorting</param>
        /// <param name="productSearchOptions">The options class to add the sorting to.</param>
        protected void UpdateOptionsWithSorting(string sortField, CommerceConstants.SortDirection? sortDirection, CommerceSearchOptions productSearchOptions)
        {
            if (!string.IsNullOrEmpty(sortField))
            {
                productSearchOptions.SortField = sortField;

                if (sortDirection.HasValue)
                {
                    productSearchOptions.SortDirection = sortDirection.Value;
                }

                ViewBag.SortField = sortField;
                ViewBag.SortDirection = sortDirection;
            }
        }