Esempio n. 1
0
        private void AddFacets(List <FacetGroupOption> facetGroups, CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            var nodeContent = currentContent as NodeContent;

            if (facetGroups == null && nodeContent == null)
            {
                return;
            }

            foreach (var facetGroupOption in facetGroups.Where(x => x.Facets.Any(y => y.Selected)))
            {
                var searchFilter = _search.SearchFilters.FirstOrDefault(x => x.field.Equals(facetGroupOption.GroupFieldName, StringComparison.OrdinalIgnoreCase));
                if (searchFilter == null)
                {
                    if (nodeContent == null)
                    {
                        continue;
                    }
                    searchFilter = GetSearchFilterForNode(nodeContent);
                }

                var facetValues = searchFilter.Values.SimpleValue
                                  .Where(x => facetGroupOption.Facets.FirstOrDefault(y => y.Selected && y.Key.ToLower() == x.key.ToLower()) != null);

                criteria.Add(searchFilter.field.ToLower(), facetValues);
            }
        }
Esempio n. 2
0
        private CatalogEntrySearchCriteria CreateCriteria(IContent currentContent, FilterOptionFormModel filterOptions)
        {
            var pageSize  = filterOptions.PageSize > 0 ? filterOptions.PageSize : _defaultPageSize;
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market    = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection {
                    "product"
                },
                Locale            = _preferredCulture.Name,
                MarketId          = market.MarketId,
                StartingRecord    = pageSize * (filterOptions.Page - 1),
                RecordsToRetrieve = pageSize,
                Sort = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending))
            };

            var nodeContent = currentContent as NodeContent;

            if (nodeContent != null)
            {
                criteria.Outlines = _search.GetOutlinesForNode(nodeContent.Code);
            }
            if (!string.IsNullOrEmpty(filterOptions.Q))
            {
                criteria.SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q);
            }

            return(criteria);
        }
Esempio n. 3
0
        /// <summary>
        /// Searches the entries.
        /// </summary>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        public virtual SearchResults SearchEntries(CatalogEntrySearchCriteria criteria)
        {
            try
            {
                if (criteria.IsISBN)
                {
                    Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(Int32.MaxValue);
                }
                _Results = Manager.Search(criteria);
            }
            catch (SystemException)
            {
                if (HttpContext.Current.IsDebuggingEnabled)
                {
                    throw;
                }
            }

            // Perform fuzzy search if nothing has been found AND the search phrase is NOT a big number (e.g. ISBN)
            if (_Results.TotalCount == 0 && !criteria.IsISBN)
            {
                Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(1024);
                criteria.IsFuzzySearch      = true;
                criteria.FuzzyMinSimilarity = 0.7f;
                _Results = Manager.Search(criteria);
            }
            Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(1024);
            return(_Results);
        }
Esempio n. 4
0
        public void Search_Lucene_Simple()
        {
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria();

            criteria.SearchPhrase = "canon";
            SearchManager manager = new SearchManager(AppContext.Current.ApplicationName);
            SearchResults results = manager.Search(criteria);
        }
Esempio n. 5
0
        private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            var nodeContent = currentContent as NodeContent;

            if (nodeContent != null)
            {
                criteria.Add(GetSearchFilterForNode(nodeContent));
            }
            _search.SearchFilters.ToList().ForEach(criteria.Add);

            ISearchResults searchResult;

            try
            {
                searchResult = _search.Search(criteria);
            }
            catch (ParseException)
            {
                return(new CustomSearchResult
                {
                    FacetGroups = new List <FacetGroupOption>(),
                    ProductViewModels = new List <ProductViewModel>()
                });
            }

            var facetGroups = new List <FacetGroupOption>();

            foreach (var searchFacetGroup in searchResult.FacetGroups)
            {
                // Only add facet group if more than one value is available
                if (searchFacetGroup.Facets.Count == 0)
                {
                    continue;
                }
                facetGroups.Add(new FacetGroupOption
                {
                    GroupName      = searchFacetGroup.Name,
                    GroupFieldName = searchFacetGroup.FieldName,
                    Facets         = searchFacetGroup.Facets.OfType <Facet>().Select(y => new FacetOption
                    {
                        Name     = y.Name,
                        Selected = y.IsSelected,
                        Count    = y.Count,
                        Key      = y.Key
                    }).ToList()
                });
            }

            return(new CustomSearchResult
            {
                ProductViewModels = CreateProductViewModels(searchResult),
                SearchResult = searchResult,
                FacetGroups = facetGroups
            });
        }
        public ActionResult ProviderModelFilteredSearch(string keyWord, string group, string facet)
        {
            var vmodel = new PMSearchResultViewModel();

            vmodel.SearchQueryText = keyWord;

            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            //string _SearchConfigPath =
            //@"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            //TextReader reader = new StreamReader(_SearchConfigPath);
            //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            //reader.Close();

            //foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            //{
            //    // Step 1 - use the XML file
            //    criteria.Add(filter);
            //}

            CreateFacetsByCode(criteria);

            foreach (SearchFilter filter in criteria.Filters)
            {
                if (filter.field.ToLower() == group.ToLower())
                {
                    var svFilter = filter.Values.SimpleValue
                                   .FirstOrDefault(x => x.value.Equals(facet, StringComparison.OrdinalIgnoreCase));
                    if (svFilter != null)
                    {
                        //This overload to Add causes the filter to be applied
                        criteria.Add(filter.field, svFilter);
                    }
                }
            }

            // use the manager for search and for index management
            SearchManager manager = new SearchManager("ECApplication");

            // Do search
            ISearchResults results = manager.Search(criteria);

            vmodel.SearchResults = results.Documents.ToList();
            vmodel.FacetGroups   = results.FacetGroups.ToList();
            vmodel.ResultCount   = results.Documents.Count.ToString();

            return(View("ProviderModelQuery", vmodel));
        }
Esempio n. 7
0
        public void Search_Lucene_WithinCatalogsWithSorting()
        {
            ICatalogSystem system = CatalogContext.Current;

            // Get catalog lists
            CatalogDto catalogs = system.GetCatalogDto();

            // Create Entry Criteria
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria();

            // Bind default catalogs if none found
            if (criteria.CatalogNames.Count == 0)
            {
                if (catalogs.Catalog.Count > 0)
                {
                    foreach (CatalogDto.CatalogRow row in catalogs.Catalog)
                    {
                        if (row.IsActive && row.StartDate <= FrameworkContext.Current.CurrentDateTime && row.EndDate >= FrameworkContext.Current.CurrentDateTime)
                        {
                            criteria.CatalogNames.Add(row.Name);
                        }
                    }
                }
            }

            // Define phrase we want to search
            criteria.SearchPhrase = "canon";

            // Create a manager
            SearchManager manager = new SearchManager(AppContext.Current.ApplicationName);

            SearchResults results = null;

            // Define sort parameter
            criteria.Sort = new SearchSort("DisplayName");

            // Perform search
            results = manager.Search(criteria);

            Assert.IsTrue(results.TotalCount > 0, "No hits were found in Lucene index.");

            // Get IDs we need
            int[] resultIndexes = results.GetIntResults(0, 10 + 5); // we add padding here to accomodate entries that might have been deleted since last indexing

            // Retrieve actual entry objects, with no caching
            Entries entries = CatalogContext.Current.GetCatalogEntries(resultIndexes, false, new TimeSpan(), new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));

            entries.TotalResults = results.TotalCount;

            Assert.IsTrue(entries.TotalResults > 0, "No entries were returned from the database.");
        }
Esempio n. 8
0
        private IEnumerable <string> GetNodes(CatalogEntrySearchCriteria criteria)
        {
            HashSet <string> stringSet = new HashSet <string>(this.ToStringEnumerable(criteria.CatalogNodes), (IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);

            foreach (string outline in criteria.Outlines)
            {
                if (outline.EndsWith("*"))
                {
                    int    startIndex = outline.LastIndexOf('/') + 1;
                    string str        = outline.Substring(startIndex, outline.Length - 1 - startIndex);
                    stringSet.Add(str);
                }
            }
            return((IEnumerable <string>)stringSet);
        }
Esempio n. 9
0
        public List <Entry> BookSearch(BookFilter BookFilter)
        {
            int  count        = 0;
            bool cacheResults = true;

            TimeSpan cacheTimeout = new TimeSpan(0, 0, 30);

            if (String.IsNullOrEmpty(BookFilter.search))
            {
                cacheTimeout = new TimeSpan(0, 1, 0);
            }

            SearchFilterHelper filter = SearchFilterHelper.Current;

            CatalogEntrySearchCriteria criteria = filter.CreateSearchCriteria(BookFilter.search, new SearchSort(BookFilter.sort));


            if (criteria.CatalogNames.Count == 0)
            {
                CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId);
                if (catalogs.Catalog.Count > 0)
                {
                    foreach (CatalogDto.CatalogRow row in catalogs.Catalog)
                    {
                        if (row.IsActive && row.StartDate <= FrameworkContext.Current.CurrentDateTime && row.EndDate >= FrameworkContext.Current.CurrentDateTime)
                        {
                            criteria.CatalogNames.Add(row.Name);
                        }
                    }
                }
            }


            Entries entries = filter.SearchEntries(criteria, BookFilter.startIndex, BookFilter.itemsPerPage, out count, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo), cacheResults, cacheTimeout);

            int resultsCount = entries.Entry != null?entries.Entry.Count() : 0;

            if (entries.Entry != null && entries.Entry.Count() > BookFilter.itemsPerPage)               //ECF's search helper pads the results by 5
            {
                Entry[] entryset = entries.Entry;
                Array.Resize <Entry>(ref entryset, BookFilter.itemsPerPage);
                entries.Entry = entryset;
            }

            return(new List <Entry> (entries.Entry));
        }
Esempio n. 10
0
        public void Search_Lucene_Fuzzy()
        {
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria();

            criteria.SearchPhrase = "fanon";
            SearchManager manager = new SearchManager(AppContext.Current.ApplicationName);
            SearchResults results = manager.Search(criteria);

            if (results.TotalCount == 0)
            {
                criteria.IsFuzzySearch      = true;
                criteria.FuzzyMinSimilarity = 0.7f;
                results = manager.Search(criteria);
            }

            Assert.IsTrue(results.TotalCount > 0, "No hits were found in Lucene index.");
        }
Esempio n. 11
0
        /// <summary>
        /// Searches the entries.
        /// </summary>
        /// <param name="criteria">The criteria.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="recordsToRetrieve">The records to retrieve.</param>
        /// <param name="count">The count.</param>
        /// <param name="responseGroup">The response group.</param>
        /// <param name="cacheResults">if set to <c>true</c> [cache results].</param>
        /// <param name="cacheTimeout">The cache timeout.</param>
        /// <returns></returns>
        public virtual Entries SearchEntries(CatalogEntrySearchCriteria criteria, int startIndex, int recordsToRetrieve, out int count, CatalogEntryResponseGroup responseGroup, bool cacheResults, TimeSpan cacheTimeout)
        {
            // Assign new cache key, specific for site guid and response groups requested
            string cacheKey = String.Empty;

            // Only cache results if specified
            if (cacheResults)
            {
                cacheKey = CatalogCache.CreateCacheKey("seach-catalog-entries", responseGroup.CacheKey, criteria.CacheKey, "start:" + startIndex.ToString(), "end:" + recordsToRetrieve.ToString());

                // check cache first
                object cachedObject = CatalogCache.Get(cacheKey);

                if (cachedObject != null)
                {
                    Entries cachedEntries = (Entries)cachedObject;
                    count = cachedEntries.TotalResults;
                    return(cachedEntries);
                }
            }

            // Perform Lucene search
            SearchResults results = SearchEntries(criteria);

            count = results.TotalCount;

            // Get IDs we need
            int[] resultIndexes = results.GetIntResults(startIndex, recordsToRetrieve + 5); // we add padding here to accomodate entries that might have been deleted since last indexing

            // Retrieve actual entry objects, with no caching
            Entries entries = CatalogContext.Current.GetCatalogEntries(resultIndexes, false, new TimeSpan(), responseGroup);

            entries.TotalResults = count;

            if (!String.IsNullOrEmpty(cacheKey)) // cache results
            {
                // Insert to the cache collection
                CatalogCache.Insert(cacheKey, entries, cacheTimeout);
            }

            return(entries);
        }
Esempio n. 12
0
        private CatalogEntrySearchCriteria CreateCriteriaForQuickSearch(FilterOptionFormModel filterOptions)
        {
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market    = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection {
                    "product"
                },
                Locale            = _preferredCulture.Name,
                MarketId          = market.MarketId,
                StartingRecord    = 0,
                RecordsToRetrieve = filterOptions.PageSize,
                Sort         = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending)),
                SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q)
            };

            return(criteria);
        }
Esempio n. 13
0
        private static Entries GetEntries(string searchText, string classType, MarketId marketId, string languageName, int startIndex, int pageSize, out int count)
        {
            var helper = SearchFilterHelper.Current;
            var group  = new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull);
            CatalogEntrySearchCriteria criteria = helper.CreateSearchCriteria(searchText, CatalogEntrySearchCriteria.DefaultSortOrder);

            criteria.RecordsToRetrieve = pageSize;
            criteria.StartingRecord    = startIndex;

            //class type
            if (classType != null)
            {
                criteria.ClassTypes.Add(classType);
            }

            criteria.Locale          = languageName;
            criteria.MarketId        = marketId;
            criteria.IncludeInactive = false;

            while (searchText.StartsWith("*") || searchText.StartsWith("?"))
            {
                searchText = searchText.Substring(1);
            }
            criteria.SearchPhrase = searchText;

            try
            {
                return(helper.SearchEntries(criteria, out count, @group, true, new TimeSpan(0, 10, 0)));
            }
            catch (Exception ex)
            {
                if (ex is StackOverflowException || ex is OutOfMemoryException)
                {
                    throw;
                }

                count = 0;
                return(new Entries());
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Gets the facets.
        /// </summary>
        /// <param name="cacheResults">if set to <c>true</c> [cache results].</param>
        /// <param name="cacheTimeout">The cache timeout.</param>
        /// <returns></returns>
        public virtual FacetGroup[] GetFacets(bool cacheResults, TimeSpan cacheTimeout)
        {
            NameValueCollection querystring = HttpContext.Current.Request.QueryString;

            string cacheKey = String.Empty;
            CatalogEntrySearchCriteria criteria = CreateSearchCriteria(querystring["search"], null);

            if (cacheResults)
            {
                // Only cache results if specified
                cacheKey = CatalogCache.CreateCacheKey("search-catalog-facets", criteria.CacheKey);

                // check cache first
                object cachedObject = CatalogCache.Get(cacheKey);

                if (cachedObject != null)
                {
                    return((FacetGroup[])cachedObject);
                }
            }

            FacetGroup[] groups = null;

            if (_Results != null)
            {
                groups = _Results.FacetGroups;
            }
            else
            {
                groups = SearchEntries(criteria).FacetGroups;
            }

            if (!String.IsNullOrEmpty(cacheKey)) // cache results
            {
                // Insert to the cache collection
                CatalogCache.Insert(cacheKey, groups, cacheTimeout);
            }
            return(groups);
        }
Esempio n. 15
0
        protected void BindSearch()
        {
            int        count        = 0;
            bool       cacheResults = false;
            TimeSpan   cacheTimeout = new TimeSpan(0, 0, 1);
            SearchSort sort         = new SearchSort("TypeSort");

            SearchFilterHelper filter = SearchFilterHelper.Current;

            CatalogEntrySearchCriteria criteria = filter.CreateSearchCriteria(null, sort);

            criteria.CatalogNames.Add("NWTD");

            Entries entries = filter.SearchEntries(criteria, 0, 5, //ECF's API pads the results
                                                   out count,
                                                   new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo),
                                                   cacheResults, cacheTimeout
                                                   );

            this.gvSearchResults.DataSource = entries.Entry;
            this.gvSearchResults.DataBind();
        }
Esempio n. 16
0
        private CatalogEntrySearchCriteria CreateDefaultCriteria(FilterOptionViewModel filterOptions)
        {
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market    = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection {
                    "product", "package", "bundle"
                },
                Locale            = _languageResolver.GetPreferredCulture().Name,
                MarketId          = market.MarketId,
                StartingRecord    = 0,
                RecordsToRetrieve = filterOptions.PageSize > 0 ? filterOptions.PageSize : _defaultPageSize,
                Sort = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending))
            };

            if (!string.IsNullOrEmpty(filterOptions.Q))
            {
                criteria.SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q);
            }

            return(criteria);
        }
Esempio n. 17
0
        private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            var nodeContent = currentContent as NodeContent;
            if (nodeContent != null)
            {
                criteria.Add(GetSearchFilterForNode(nodeContent));
            }
            _search.SearchFilters.ToList().ForEach(criteria.Add);
            
            ISearchResults searchResult;

            try
            {
                searchResult = _search.Search(criteria);
            }
            catch (ParseException)
                {
                return new CustomSearchResult
                {
                    FacetGroups = new List<FacetGroupOption>(),
                    ProductViewModels = new List<ProductViewModel>()
                };
            }

            var facetGroups = new List<FacetGroupOption>();
            foreach (var searchFacetGroup in searchResult.FacetGroups)
            {
                // Only add facet group if more than one value is available
                if (searchFacetGroup.Facets.Count == 0)
                {
                    continue;
                }
                facetGroups.Add(new FacetGroupOption
                {
                    GroupName = searchFacetGroup.Name,
                    GroupFieldName = searchFacetGroup.FieldName,
                    Facets = searchFacetGroup.Facets.OfType<Facet>().Select(y => new FacetOption
                    {
                        Name = y.Name,
                        Selected = y.IsSelected,
                        Count = y.Count,
                        Key = y.Key 
                    }).ToList()
                });
            }

            return new CustomSearchResult
            {
                ProductViewModels = CreateProductViewModels(searchResult),
                SearchResult = searchResult,
                FacetGroups = facetGroups
            };
        }
Esempio n. 18
0
        private void AddFacets(List<FacetGroupOption> facetGroups, CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            var nodeContent = currentContent as NodeContent;
            if (facetGroups == null && nodeContent == null)
            {
                return;
            }

            foreach (var facetGroupOption in facetGroups.Where(x => x.Facets.Any(y => y.Selected)))
            {
                var searchFilter = _search.SearchFilters.FirstOrDefault(x => x.field.Equals(facetGroupOption.GroupFieldName, StringComparison.OrdinalIgnoreCase));
                if (searchFilter == null)
                {
                    if (nodeContent == null)
                    {
                        continue;
                    }
                    searchFilter = GetSearchFilterForNode(nodeContent);
                }
                
                var facetValues = searchFilter.Values.SimpleValue
                    .Where(x => facetGroupOption.Facets.FirstOrDefault(y => y.Selected && y.Key.ToLower() == x.key.ToLower()) != null);

                criteria.Add(searchFilter.field.ToLower(), facetValues);
            }
        }
Esempio n. 19
0
        private CatalogEntrySearchCriteria CreateCriteria(IContent currentContent, FilterOptionFormModel filterOptions)
        {
            var pageSize = filterOptions.PageSize > 0 ? filterOptions.PageSize : 20;
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection { "product" },
                Locale = _preferredCulture.Name,
                MarketId = market.MarketId,
                StartingRecord = pageSize * (filterOptions.Page - 1),
                RecordsToRetrieve = pageSize,
                Sort = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending))
            };
            
            var nodeContent = currentContent as NodeContent;
            if (nodeContent != null)
            {
                criteria.Outlines = _search.GetOutlinesForNode(nodeContent.Code);
            }
            if (!string.IsNullOrEmpty(filterOptions.Q))
            {
                criteria.SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q);
            }

            return criteria;
        }
Esempio n. 20
0
        private CatalogEntrySearchCriteria CreateCriteriaForQuickSearch(FilterOptionFormModel filterOptions)
        {
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection { "product" },
                Locale = _preferredCulture.Name,
                MarketId = market.MarketId,
                StartingRecord = 0,
                RecordsToRetrieve = filterOptions.PageSize,
                Sort = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending)),
                SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q)
            };

            return criteria;
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:EPiServer.Commerce.FindSearchProvider.FindSearchQueryBuilder" /> class.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="criteria">The criteria.</param>
        /// <param name="languageOption">The language option.</param>
        /// <exception cref="T:System.InvalidOperationException">The Find search query builder only works with clients created by the provider.</exception>
        public FindSearchQueryBuilder(IClient client, ISearchCriteria criteria, QueryCultureOption languageOption)
        {
            ProviderClient providerClient = client as ProviderClient;

            if (providerClient == null)
            {
                throw new InvalidOperationException("The Find search query builder only works with clients created by the provider.");
            }
            ISearchConfiguration       providerConfiguration = providerClient.ProviderConfiguration;
            Language                   language  = (Language)null;
            ITypeSearch <FindDocument> search1   = criteria.IgnoreFilterOnLanguage || !FindSearchQueryBuilder._providerLanguages.TryGetValue(criteria.Locale, out language) ? providerClient.Search <FindDocument>() : providerClient.Search <FindDocument>(language);
            CatalogEntrySearchCriteria criteria1 = criteria as CatalogEntrySearchCriteria;

            if (criteria1 != null)
            {
                ITypeSearch <FindDocument> search2;
                if (criteria.IgnoreFilterOnLanguage)
                {
                    search2 = search1.ForDefaultFields(criteria1.SearchPhrase, string.Empty);
                }
                else
                {
                    ITypeSearch <FindDocument> search3 = search1.ForDefaultFields(criteria1.SearchPhrase, criteria.Locale);
                    HashSet <string>           source  = new HashSet <string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);
                    if (language != null && !string.IsNullOrEmpty(language.FieldSuffix) && languageOption.HasFlag((Enum)QueryCultureOption.Neutral))
                    {
                        source.Add(language.FieldSuffix);
                    }
                    if (!string.IsNullOrEmpty(criteria.Locale) && languageOption.HasFlag((Enum)QueryCultureOption.Specific))
                    {
                        source.Add(criteria.Locale);
                    }
                    if (!source.Any <string>())
                    {
                        source.Add(ContentLanguage.PreferredCulture.Name);
                    }
                    search2 = search3.FilterLanguages((IEnumerable <string>)source);
                }
                if (DateTime.MinValue < criteria1.StartDate && criteria1.EndDate < DateTime.MaxValue)
                {
                    search2 = search2.FilterDates(criteria1.StartDate, criteria1.EndDate, criteria1.IncludePreorderEntry);
                }
                search1 = search2.FilterCatalogs(this.ToStringEnumerable(criteria1.CatalogNames)).FilterCatalogNodes(this.GetNodes(criteria1)).FilterOutlines(this.GetOutlines(criteria1)).FilterMetaClasses(this.ToStringEnumerable(criteria1.SearchIndex)).FilterCatalogEntryTypes(this.ToStringEnumerable(criteria1.ClassTypes));
                if (!criteria1.IncludeInactive)
                {
                    search1 = search1.FilterInactiveCatalogEntries();
                }
                if (criteria1.MarketId != MarketId.Empty)
                {
                    search1 = search1.FilterCatalogEntryMarket(criteria1.MarketId);
                }
            }
            ITypeSearch <FindDocument> search4 = search1.AddActiveFilters(criteria).AddFacets(criteria).OrderBy(criteria);

            if (criteria.StartingRecord > 0)
            {
                search4 = search4.Skip <FindDocument>(criteria.StartingRecord);
            }
            if (criteria.RecordsToRetrieve > 0)
            {
                search4 = search4.Take <FindDocument>(criteria.RecordsToRetrieve);
            }
            this.Search = (ISearch <FindDocument>)search4;
        }
Esempio n. 22
0
        public ActionResult ProviderModelQuery(string keyWord)
        {
            // Create criteria
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                RecordsToRetrieve = 200, // there is a default of 50
                // Locale have to be there... else no hits
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            // Add more to the criteria
            criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder;
            criteria.CatalogNames.Add("Fashion"); // ...if we know what catalog to search in, not mandatory
            //criteria.IgnoreFilterOnLanguage = true; // if we want to search all languages... need the locale anyway

            criteria.ClassTypes.Add(EntryType.Variation);
            criteria.MarketId = MarketId.Default; // should use the ICurrentMarket service, of course...

            criteria.IsFuzzySearch      = true;
            criteria.FuzzyMinSimilarity = 0.7F;

            criteria.IncludeInactive = true;

            // the _outline field
            System.Collections.Specialized.StringCollection sc =
                new System.Collections.Specialized.StringCollection
            {
                "Fashion/Clothes_1/Men_1/Shirts_1",
                "Fashion/Clothes_1/UniSex_1"
            };
            criteria.Outlines = sc; // another "AND"

            #region SimpleWalues
            ///*
            // Add facets to the criteria... and later prepare them for the "search result" as FacetGroups
            // With the below only these values are in the result... no Red or RollsRoys
            Mediachase.Search.SimpleValue svWhite = new SimpleValue
            {
                value        = "white",
                key          = "white",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descWhite = new Description
            {
                locale = "en",
                Value  = "White"
            };
            svWhite.Descriptions.Description = new[] { descWhite };

            // If added like this it ends up in "ActiveFields" of the criteria and the result is filtered
            //criteria.Add("color", svWhite);
            // ...also the facetGroups on the "result" are influenced

            Mediachase.Search.SimpleValue svBlue = new SimpleValue
            {
                value        = "blue",
                key          = "blue",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descBlue = new Description
            {
                locale = "en",
                Value  = "Blue"
            };
            svBlue.Descriptions.Description = new[] { descBlue };
            //criteria.Add("color", svBlue);

            Mediachase.Search.SimpleValue svVolvo = new SimpleValue
            {
                value        = "volvo",
                key          = "volvo",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descVolvo = new Description
            {
                locale = "en",
                Value  = "volvo"
            };
            svVolvo.Descriptions.Description = new[] { descVolvo };
            //criteria.Add("brand", svVolvo);

            Mediachase.Search.SimpleValue svSaab = new SimpleValue
            {
                value        = "saab",
                key          = "saab",
                locale       = "en",
                Descriptions = new Descriptions {
                    defaultLocale = "en"
                }
            };
            var descSaab = new Description
            {
                locale = "en",
                Value  = "saab"
            };
            svSaab.Descriptions.Description = new[] { descSaab };
            //criteria.Add("brand", svSaab);

            #region Debug

            // the above filters the result so only saab (the blue) is there
            // With the above only we see only the Blue shirt... is that a saab - yes
            // New: no xml --> gives one Active and an empty filter even searchFilter.Values.SimpleValue below is there
            // New: outcommenting the above line --> and add XML file ... no "Active Fileds"
            // Have the Filters added - but no actice fields
            // New: trying this... Brand gets "ActiveField" with volvo & saab.. but the result shows all brands
            // New: outcommenting the below line and adding above only one, the saab
            //criteria.Add("brand", new List<ISearchFilterValue> { svSaab, svVolvo });
            // ...get a FacetGroups "in there"... like with the XML-file ... a manual way to add...
            // ...stuff that is not in the XML-file, or skip the XML File
            // New: taking out the single saab filter added

            #endregion

            SearchFilter searchFilterColor = new SearchFilter
            {
                //field = BaseCatalogIndexBuilder.FieldConstants.Catalog, // Have a bunch
                field = "color",

                // mandatory
                Descriptions = new Descriptions
                {
                    // another way of getting the language
                    defaultLocale = _langResolver.Service.GetPreferredCulture().Name
                },

                Values = new SearchFilterValues(),
            };

            SearchFilter searchFilterBrand = new SearchFilter
            {
                field = "brand",

                Descriptions = new Descriptions
                {
                    defaultLocale = _langResolver.Service.GetPreferredCulture().Name
                },

                Values = new SearchFilterValues(),
            };

            var descriptionColor = new Description
            {
                locale = "en",
                Value  = "Color"
            };

            var descriptionBrand = new Description
            {
                locale = "en",
                Value  = "Brand"
            };


            searchFilterColor.Descriptions.Description = new[] { descriptionColor };
            searchFilterBrand.Descriptions.Description = new[] { descriptionBrand };

            searchFilterColor.Values.SimpleValue = new SimpleValue[] { svWhite, svBlue };
            searchFilterBrand.Values.SimpleValue = new SimpleValue[] { svVolvo, svSaab };

            // can do like the below or us the loop further down...
            // the "foreach (SearchFilter item in _NewSearchConfig.SearchFilters)"
            // use these in the second part of the demo... "without XML" ... saw that with XML-style
            criteria.Add(searchFilterColor);
            criteria.Add(searchFilterBrand);

            #region Debug

            // gets the "filters" without this below and the XML... further checks...
            // do we need this? ... seems not... or it doesn't work like this
            // New: Have XML and commenting out the below lines Looks the same as with it
            // New: second...outcommenting the criteria.Add(searchFilter);
            // the Facets prop is empty......without the XML
            // the below line seems not to work
            // New: adding these again together with the saab above active
            //... difference is the "VariationFilter"
            // We get the Facets on the criteria, but no facets in the "result" without the XML

            //criteria.Filters = searchFilter; // read-only

            // Without the XML...

            // boom... on a missing "key"... the description
            // when commenting out the criteria.Add() for the simple values...??
            // When adding more to the SearchFilter it works...
            // ... the Simple values are there in the only instance if the filter
            // commenting out and check with the XML
            // when using the XML the groups sit in FacetGroups
            // when using the above... no facet-groups added

            // The same facets added a second time, Filter number 2 and no facet-groups
            //SearchConfig sConf = new SearchConfig();

            #endregion Debug

            //*/
            #endregion SimpleValues

            // use the manager for search and for index management
            SearchManager manager = new SearchManager("ECApplication");

            #region Facets/Filters

            // Filters from the XML file, populates the FacetGroups on the Search result
            string _SearchConfigPath =
                @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            TextReader    reader     = new StreamReader(_SearchConfigPath);
            XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            reader.Close();

            foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            {
                // Step 1 - use the XML file
                //criteria.Add(filter);
            }

            // Manual...
            SearchConfig _NewSearchConfig = new SearchConfig
            {
                SearchFilters = new SearchFilter[] { searchFilterColor, searchFilterBrand }
            };

            // can do like this, but there is another way (a bit above)
            foreach (SearchFilter item in _NewSearchConfig.SearchFilters)
            {
                // Step 2 - skip the XML file
                //criteria.Add(item);
            }

            #endregion

            // Do search
            ISearchResults results = manager.Search(criteria);

            #region Debug


            // doens't work
            //FacetGroup facetGroup = new FacetGroup("Bogus", "Bummer");
            //results.FacetGroups = new[] { facetGroup };

            // ...different return types - same method
            //SearchFilterHelper.Current.SearchEntries()

            // out comment and do a new try
            //ISearchFacetGroup[] facets = results.FacetGroups;

            // NEW: adding these ... for the provider, last line doesn's assign
            //ISearchFacetGroup[] searchFacetGroup0 = new SearchFacetGroup() { };
            FacetGroup facetGroup0 = new FacetGroup("colorgroup", "dummy"); //{ "",""}; // FacetGroup("brand","volvo");
            Facet      f1          = new Facet(facetGroup0, svWhite.key, svWhite.value, 1);
            facetGroup0.Facets.Add(f1);
            //facets[1] = facetGroup0;
            ISearchFacetGroup[] searchFacetGroup = new FacetGroup[] { facetGroup0 };
            //searchFacetGroup.Facets.Add(f1);
            //results.FacetGroups = searchFacetGroup; // nothing happens here, facet-group still empty

            #endregion

            int[] ints = results.GetKeyFieldValues <int>();

            // The DTO-way
            CatalogEntryDto dto = _catalogSystem.GetCatalogEntriesDto(ints);

            // CMS style (better)... using ReferenceConverter and ContentLoader
            List <ContentReference> refs = new List <ContentReference>();
            ints.ToList().ForEach(i => refs.Add(_referenceConverter.GetContentLink(i, CatalogContentType.CatalogEntry, 0)));

            localContent = _contentLoader.GetItems(refs, new LoaderOptions()); //

            // ToDo: Facets
            List <string> facetList = new List <string>();

            int facetGroups = results.FacetGroups.Count();

            foreach (ISearchFacetGroup item in results.FacetGroups)
            {
                foreach (var item2 in item.Facets)
                {
                    facetList.Add(String.Format("{0} {1} ({2})", item.Name, item2.Name, item2.Count));
                }
            }

            var searchResultViewModel = new SearchResultViewModel
            {
                totalHits = new List <string> {
                    ""
                },                                   // change
                nodes      = localContent.OfType <FashionNode>(),
                products   = localContent.OfType <ShirtProduct>(),
                variants   = localContent.OfType <ShirtVariation>(),
                allContent = localContent,
                facets     = facetList
            };


            return(View(searchResultViewModel));
        }
        public ActionResult ProviderModelQuery(string keyWord)
        {
            var vmodel = new PMSearchResultViewModel();

            vmodel.SearchQueryText = keyWord;

            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                RecordsToRetrieve = 200, // there is a default of 50
                                         // Locale have to be there… else no hits
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            #region Options
            //criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder;
            //criteria.CatalogNames.Add("Fashion");
            //criteria.ClassTypes.Add(EntryType.Variation);
            //criteria.MarketId = MarketId.Default;
            //criteria.IsFuzzySearch = true;
            //criteria.FuzzyMinSimilarity = 0.7F;
            //criteria.IncludeInactive = true;
            //System.Collections.Specialized.StringCollection sc =
            //    new System.Collections.Specialized.StringCollection
            //    {
            //        "Fashion/Clothes_1/Men_1/Shirts_1",
            //        "Fashion/Clothes_1/UniSex_1"
            //    };
            //criteria.Outlines = sc;

            #endregion Options

            //string _SearchConfigPath = @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            //TextReader reader = new StreamReader(_SearchConfigPath);
            //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            //reader.Close();
            //foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            //{
            //    criteria.Add(filter);
            //}

            CreateFacetsByCode(criteria);

            SearchManager manager = new SearchManager("ECApplication");

            // Do search
            ISearchResults results = manager.Search(criteria);

            int[] ints = results.GetKeyFieldValues <int>();

            var _referenceConverter = ServiceLocator.Current.GetInstance <Mediachase.Commerce.Catalog.ReferenceConverter>();
            var _contentLoader      = ServiceLocator.Current.GetInstance <IContentLoader>();

            List <ContentReference> refs = new List <ContentReference>();
            ints.ToList().ForEach(i => refs.Add(_referenceConverter
                                                .GetContentLink(i, CatalogContentType.CatalogEntry, 0)));
            var localContent = _contentLoader.GetItems(refs, new LoaderOptions());


            vmodel.SearchResults = results.Documents.ToList();
            vmodel.FacetGroups   = results.FacetGroups.ToList();
            vmodel.ResultCount   = results.Documents.Count.ToString();

            return(View(vmodel));
        }
Esempio n. 24
0
        /// <summary>
        /// Searches the entries.
        /// </summary>
        /// <param name="keywords">The keywords.</param>
        /// <param name="sort">The sort.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="recordsToRetrieve">The records to retrieve.</param>
        /// <param name="count">The count.</param>
        /// <param name="responseGroup">The response group.</param>
        /// <param name="cacheResults">if set to <c>true</c> [cache results].</param>
        /// <param name="cacheTimeout">The cache timeout.</param>
        /// <returns></returns>
        public virtual Entries SearchEntries(string keywords, SearchSort sort, int startIndex, int recordsToRetrieve, out int count, CatalogEntryResponseGroup responseGroup, bool cacheResults, TimeSpan cacheTimeout)
        {
            CatalogEntrySearchCriteria criteria = CreateSearchCriteria(keywords, sort);

            return(SearchEntries(criteria, startIndex, recordsToRetrieve, out count, responseGroup, cacheResults, cacheTimeout));
        }
Esempio n. 25
0
 public virtual ISearchResults Search(CatalogEntrySearchCriteria criteria)
 {
     Initialize();
     return _searchManager.Search(criteria);
 }
Esempio n. 26
0
        /// <summary>
        /// Binds the fields.
        /// </summary>
        private void BindFields()
        {
            int recordsToRetrieve = DataPager2.PageSize;

            // Perform search
            string   keywords     = Request.QueryString["search"];
            int      count        = 0;
            bool     cacheResults = true;
            TimeSpan cacheTimeout = new TimeSpan(0, 0, 30);

            if (String.IsNullOrEmpty(keywords))
            {
                cacheTimeout = new TimeSpan(0, 1, 0);
            }

            SearchFilterHelper filter = SearchFilterHelper.Current;

            string sort = Request.QueryString["s"];

            SearchSort sortObject = null;

            if (!String.IsNullOrEmpty(sort))
            {
                if (sort.Equals("name", StringComparison.OrdinalIgnoreCase))
                {
                    sortObject = new SearchSort("DisplayName");
                }
                else if (sort.Equals("plh", StringComparison.OrdinalIgnoreCase))
                {
                    sortObject = new SearchSort(String.Format("SalePrice{0}", CMSContext.Current.CurrencyCode));
                }
                else if (sort.Equals("phl", StringComparison.OrdinalIgnoreCase))
                {
                    sortObject = new SearchSort(String.Format("SalePrice{0}", CMSContext.Current.CurrencyCode), true);
                }
            }

            // Put default sort order if none is set
            if (sortObject == null)
            {
                sortObject = CatalogEntrySearchCriteria.DefaultSortOrder;
            }

            CatalogEntrySearchCriteria criteria = filter.CreateSearchCriteria(keywords, sortObject);

            if (_Parameters.Contains("Catalogs"))
            {
                foreach (string catalog in _Parameters["Catalogs"].ToString().Split(new char[',']))
                {
                    if (!String.IsNullOrEmpty(catalog))
                    {
                        criteria.CatalogNames.Add(catalog);
                    }
                }
            }

            if (_Parameters.Contains("NodeCode"))
            {
                foreach (string node in _Parameters["NodeCode"].ToString().Split(new char[',']))
                {
                    if (!String.IsNullOrEmpty(node))
                    {
                        criteria.CatalogNodes.Add(node);
                    }
                }
            }

            if (_Parameters.Contains("EntryClasses"))
            {
                foreach (string node in _Parameters["EntryClasses"].ToString().Split(new char[',']))
                {
                    if (!String.IsNullOrEmpty(node))
                    {
                        criteria.SearchIndex.Add(node);
                    }
                }
            }

            if (_Parameters.Contains("EntryTypes"))
            {
                foreach (string entry in _Parameters["EntryTypes"].ToString().Split(new char[',']))
                {
                    if (!String.IsNullOrEmpty(entry))
                    {
                        criteria.ClassTypes.Add(entry);
                    }
                }
            }

            if (_Parameters.Contains("RecordsPerPage"))
            {
                recordsToRetrieve = Int32.Parse(_Parameters["RecordsPerPage"].ToString());
            }

            // Bind default catalogs if none found
            if (criteria.CatalogNames.Count == 0)
            {
                CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId);
                if (catalogs.Catalog.Count > 0)
                {
                    foreach (CatalogDto.CatalogRow row in catalogs.Catalog)
                    {
                        if (row.IsActive && row.StartDate <= FrameworkContext.Current.CurrentDateTime && row.EndDate >= FrameworkContext.Current.CurrentDateTime)
                        {
                            criteria.CatalogNames.Add(row.Name);
                        }
                    }
                }
            }

            // No need to perform search if no catalogs specified
            if (criteria.CatalogNames.Count != 0)
            {
                Entries entries = filter.SearchEntries(criteria, _StartRowIndex, recordsToRetrieve, out count, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo), cacheResults, cacheTimeout);
                CatalogSearchDataSource.TotalResults   = count;
                CatalogSearchDataSource.CatalogEntries = entries;
            }
            _Results = filter.Results;

            if (count == 0)
            {
                PagingHeader.Visible = false;
                PagingFooter.Visible = false;
                DataPager2.Visible   = false;
                DataPager3.Visible   = false;
                MyMenu.Visible       = false;
            }
            else
            {
                MyMenu.Filters = filter.SelectedFilters;
                MyMenu.Facets  = filter.GetFacets(cacheResults, cacheTimeout);
                MyMenu.Visible = true;
                //MyMenu.DataBind();
                PagingHeader.Visible = true;
                PagingFooter.Visible = true;
                DataPager2.Visible   = true;
                DataPager3.Visible   = true;
            }
        }
Esempio n. 27
0
        /// <summary>
        /// When the page loads, we'll perform the search based on the criteria defined in the query string.
        /// Some of this is automatically done by ECF, for better or for worse, other things are done by us in our
        /// public properties such as KeyWords
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //before we conduct the search, we'd better make sure the prices are set for the user
            global::NWTD.Profile.SetSaleInformation();

            //Hide the "Add Selected items to cart" button on the top of the results
            this.srBookSearch.AddToCartTop.Visible = false;


            //The criteria for this search is going to be based on the query string.

            //first get some variables ready
            int      count        = 0;
            bool     cacheResults = true;
            TimeSpan cacheTimeout = new TimeSpan(0, 0, 30);             //by default we'll have our cache timeout after 30 seconds

            if (String.IsNullOrEmpty(this.KeyWords))
            {
                cacheTimeout = new TimeSpan(0, 1, 0);                 //if there's no keyword search, we'll up the timeout to a minute
            }
            //get the current filter
            //(ECF will automatically pull filters from the query string)
            SearchFilterHelper filter = SearchFilterHelper.Current;


            string keyWords = this.KeyWords;
            ////check to see if the KeyWords matches an ISBN Pattern
            //if(System.Text.RegularExpressions.Regex.IsMatch(keyWords, @"^[0-9-]+[a-z-0-9]?$")){ //any string of all hyphens or numbers and possibly an alpha character at the end
            //    keyWords = keyWords.Replace("-",string.Empty);
            //}


            //build the criteria based on sort and keywords
            CatalogEntrySearchCriteria criteria = filter.CreateSearchCriteria(keyWords, this.SortBy);


            // the current catalog if that's not been added yet (which it shouldn't be)
            if (criteria.CatalogNames.Count == 0)
            {
                CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId);
                if (catalogs.Catalog.Count > 0)
                {
                    foreach (CatalogDto.CatalogRow row in catalogs.Catalog)
                    {
                        if (row.IsActive && row.StartDate <= FrameworkContext.Current.CurrentDateTime && row.EndDate >= FrameworkContext.Current.CurrentDateTime)
                        {
                            criteria.CatalogNames.Add(row.Name);
                        }
                    }
                }
            }

            //Incorporate the state availablity flag
            criteria.Add(
                global::NWTD.Catalog.UserStateAvailablityField,
                new SimpleValue()
            {
                key          = string.Empty,
                value        = "y",
                locale       = "en-us",
                Descriptions = new Descriptions()
                {
                    defaultLocale = "en-us"
                }
            });

            //setting this in the helper class now
            //Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(Int32.MaxValue);
            //exectute the search
            Entries entries = filter.SearchEntries(
                criteria,
                this.StartIndex,
                this.ItemsPerPage,
                out count,
                new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo),
                cacheResults,
                cacheTimeout
                );

            //Lucene.Net.Search.BooleanQuery.SetMaxClauseCount(1024);
            //the number of results that were returned
            int resultsCount = entries.Entry != null?entries.Entry.Count() : 0;

            if (entries.Entry != null && entries.Entry.Count() > this.ItemsPerPage)               //ECF's search helper pads the results by 5
            {
                Entry[] entryset = entries.Entry;
                Array.Resize <Entry>(ref entryset, this.ItemsPerPage);

                entries.Entry = entryset;
            }

            int fromResult = (this.StartIndex + 1);
            int toResult   = this.StartIndex + (this.ItemsPerPage > resultsCount ? resultsCount : this.ItemsPerPage);

            //indicate to the user what page we're on
            if (resultsCount > 0)
            {
                this.litPageNumber.Text = string.Format("({0}-{1} of {2})", fromResult.ToString(), toResult.ToString(), count.ToString());
            }
            else
            {
                //this.ddlSortBy.Visible = false;
            }

            decimal numberOfPages = 1 + Convert.ToDecimal(Math.Floor(Convert.ToDouble((count / this.ItemsPerPage))));

            //if we're not on page 1, add a prev button to the pager
            if (this.PageNumber != 1)
            {
                this.blPager.Items.Add(new ListItem("Prev", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber - 1).ToString())));
                this.blBottomPager.Items.Add(new ListItem("Prev", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber - 1).ToString())));
            }
            //if we're not on the last page, add a next button to the pager
            if (this.PageNumber != numberOfPages)
            {
                this.blPager.Items.Add(new ListItem("Next", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber + 1).ToString())));
                this.blBottomPager.Items.Add(new ListItem("Next", SearchFilterHelper.GetQueryStringNavigateUrl("page", (PageNumber + 1).ToString())));
            }

            //this.srBookSearch.ResultsGrid.ShowFooter = true;
            this.srBookSearch.ResultsGrid.Parent.Controls.AddAt(this.srBookSearch.ResultsGrid.Parent.Controls.IndexOf(this.srBookSearch.ResultsGrid) + 1, this.pnlBottomPager);

            //I can't figure out why this needs to be cast. For some reason VS is calling it a UserControl, not a SideMenu
            FiltersSideMenu.Filters = filter.SelectedFilters;

            //Only show facet if results are more than 1 - Heath Gardner 01/22/16 ////////////////////////////////////////
            FacetGroup[] facets = null;


            if (resultsCount > 1)
            {
                facets = filter.GetFacets(cacheResults, cacheTimeout);
            }

            FiltersSideMenu.Facets = facets;
            //End modify//////////////////////////////////////////////////////////////////////////////////////////////////

            //Original facet logic that was replaced with the above - Heath Gardner 01/22/16
            //FacetGroup[]  facets = filter.GetFacets(cacheResults, cacheTimeout);
            //FiltersSideMenu.Facets = facets;

            //Bind the results to our search results control
            this.srBookSearch.Entries      = entries;
            this.srBookSearch.TotalResults = count;

            //We don't want them to be able to just view everything with no search (for reasons unbeknownst to me)
            if (Request.QueryString.Count == 0)
            {
                this.srBookSearch.Visible     = false;
                this.blPager.Visible          = false;
                this.blBottomPager.Visible    = false;
                this.litPageNumber.Visible    = false;
                this.pnlBrowseCatalog.Visible = true;
                this.pnlSearchHead.Visible    = false;
                //return;
            }
            //if there are no results, we need to hide certain things
            else if (count == 0)
            {
                this.srBookSearch.Visible  = false;
                this.blPager.Visible       = false;
                this.blBottomPager.Visible = false;
                this.litPageNumber.Visible = false;
                this.pnlNoResults.Visible  = true;
                this.pnlSearchHead.Visible = false;
                //return;
            }

            if (!string.IsNullOrEmpty(this.KeyWords))
            {
                this.litSearchString.Text = string.Format("<span class=\"nwtd-searchString\">for \"{0}\"</span>", this.KeyWords);
            }

            DataBind();
        }
Esempio n. 28
0
 public virtual ISearchResults Search(CatalogEntrySearchCriteria criteria)
 {
     Initialize();
     return(_searchManager.Search(criteria));
 }
Esempio n. 29
0
        /// <summary>
        /// Searches the entries.
        /// </summary>
        /// <param name="keywords">The keywords.</param>
        /// <param name="sort">The sort.</param>
        /// <returns></returns>
        public virtual SearchResults SearchEntries(string keywords, SearchSort sort)
        {
            CatalogEntrySearchCriteria criteria = CreateSearchCriteria(keywords, sort);

            return(SearchEntries(criteria));
        }
        public ActionResult Search(string keyWord)
        {
            // ToDo: SearchHelper and Criteria
            SearchFilterHelper searchHelper = SearchFilterHelper.Current; // the easy way

            CatalogEntrySearchCriteria criteria = searchHelper.CreateSearchCriteria(keyWord
                                                                                    , CatalogEntrySearchCriteria.DefaultSortOrder);

            criteria.RecordsToRetrieve = 25;
            criteria.StartingRecord    = 0;
            //criteria.Locale = "en"; // needed
            criteria.Locale = ContentLanguage.PreferredCulture.Name;

            int      count       = 0; // "Out"
            bool     cacheResult = true;
            TimeSpan timeSpan    = new TimeSpan(0, 10, 0);

            // ToDo: Search
            // One way of "doing it" ... retrieve it like ISearchResults (preferred, most certainly)
            ISearchResults  searchResult = searchHelper.SearchEntries(criteria);
            ISearchDocument aDoc         = searchResult.Documents.FirstOrDefault();

            int[] ints = searchResult.GetKeyFieldValues <int>();

            /* == ways of loading, keeping some old stuff for enjoying squiggles == */
            // ECF style Entries, old-school & legacy, not recommended at all...
            // ...work with DTOs if not using the ContentModel
            Entries entries = CatalogContext.Current.GetCatalogEntries(ints // Note "ints"
                                                                       , new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo));

            // still interesting
            CatalogContext.Current.GetCatalogEntriesDto(ints
                                                        , new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo));

            // Same thing... ECF-old-style, not recommended... if not absolutely needed...
            // Use the helper and get the entries direct
            // If entries are needed ... like for calculating discounts with legacy StoreHelper()
            Entries entriesDirect = searchHelper.SearchEntries(criteria, out count // Note the different return-types ... akward!
                                                               , new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo)
                                                               , cacheResult, new TimeSpan());

            // CMS style (better)... using ReferenceConverter and ContentLoader
            List <ContentReference> refs = new List <ContentReference>();

            ints.ToList().ForEach(i => refs.Add(_referenceConverter.GetContentLink(i, CatalogContentType.CatalogEntry, 0)));

            // LoaderOptions() is new in CMS 8
            // ILanguageSelector selector = ServiceLocator.Current.GetInstance<ILanguageSelector>(); // obsolete
            _localContent = _contentLoader.GetItems(refs, new LoaderOptions()); // use this in CMS 8+

            // ToDo: Facets
            List <string> facetList = new List <string>();

            int facetGroups = searchResult.FacetGroups.Count();

            foreach (ISearchFacetGroup item in searchResult.FacetGroups)
            {
                foreach (var item2 in item.Facets)
                {
                    facetList.Add(String.Format("{0} {1} ({2})", item.Name, item2.Name, item2.Count));
                }
            }

            // Fill up the ViewModel
            var searchResultViewModel = new SearchResultViewModel();

            searchResultViewModel.totalHits = new List <string> {
                ""
            };                                                         // change
            searchResultViewModel.nodes      = _localContent.OfType <FashionNode>();
            searchResultViewModel.products   = _localContent.OfType <ShirtProduct>();
            searchResultViewModel.variants   = _localContent.OfType <ShirtVariation>();
            searchResultViewModel.allContent = _localContent;
            searchResultViewModel.facets     = facetList;

            return(View(searchResultViewModel));
        }
Esempio n. 31
0
        private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            /*
             * IClient client = new Client(serviceUrl: "https://es-eu-dev-api01.episerver.net/F05MNJ7EvA4UBTWTg2ovBmuV8LpUH9Ts/",
             *  defaultIndex: "phvinh_myindex");
             * //var vinh = new FashionProduct(){ Name = "vinh 's shoes"};
             * //var success = client.Index(vinh);
             *
             * //IContentResult<FashionProduct> result = client.Search<FashionProduct>().GetContentResult();
             * IContentResult<FashionVariant> results = client.Search<FashionVariant>().FilterOnCurrentMarket().GetContentResult();
             * ISearchDocuments documents = new SearchDocuments();
             * foreach (var variation in results)
             * {
             *  ISearchDocument doc = new SearchDocument();
             *
             *  ISearchField field = new SearchField("displayname", variation.DisplayName);
             *  doc.Add(field);
             *
             *  field = new SearchField("code", variation.Code);
             *  doc.Add(field);
             *
             *  field = new SearchField("Red", variation.Color);
             *  doc.Add(field);
             *
             *  field = new SearchField("13", variation.Size);
             *  doc.Add(field);
             *
             *  field = new SearchField("image_url", variation.DefaultImageUrl());
             *  doc.Add(field);
             *
             *  documents.Add(doc);
             * }
             * ISearchResults searchResultOfMine = new SearchResults(documents, criteria);
             * return new CustomSearchResult
             * {
             *  ProductViewModels = CreateProductViewModels(searchResultOfMine),
             *  SearchResult = searchResultOfMine,
             *  FacetGroups = new List<FacetGroupOption>()
             * };
             */

            var nodeContent = currentContent as NodeContent;

            if (nodeContent != null)
            {
                criteria.Add(GetSearchFilterForNode(nodeContent));
            }
            _search.SearchFilters.ToList().ForEach(criteria.Add);

            ISearchResults searchResult;

            try
            {
                searchResult = _search.Search(criteria);
            }
            catch (ParseException)
            {
                return(new CustomSearchResult
                {
                    FacetGroups = new List <FacetGroupOption>(),
                    ProductViewModels = new List <ProductTileViewModel>()
                });
            }

            var facetGroups = new List <FacetGroupOption>();

            foreach (var searchFacetGroup in searchResult.FacetGroups)
            {
                // Only add facet group if more than one value is available
                if (searchFacetGroup.Facets.Count == 0)
                {
                    continue;
                }
                facetGroups.Add(new FacetGroupOption
                {
                    GroupName      = searchFacetGroup.Name,
                    GroupFieldName = searchFacetGroup.FieldName,
                    Facets         = searchFacetGroup.Facets.OfType <Facet>().Select(y => new FacetOption
                    {
                        Name     = y.Name,
                        Selected = y.IsSelected,
                        Count    = y.Count,
                        Key      = y.Key
                    }).ToList()
                });
            }

            return(new CustomSearchResult
            {
                ProductViewModels = CreateProductViewModels(searchResult),
                SearchResult = searchResult,
                FacetGroups = facetGroups
            });
        }
        private void CreateFacetsByCode(CatalogEntrySearchCriteria criteria)
        {
            #region Simple Values to be added to filters
            SimpleValue svWhite = new SimpleValue
            {
                value        = "white",
                key          = "white",
                locale       = "en",
                Descriptions = new Descriptions
                {
                    defaultLocale = "en",
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "White"
                        }
                    }
                }
            };

            SimpleValue svBlue = new SimpleValue
            {
                value        = "blue",
                key          = "blue",
                locale       = "en",
                Descriptions = new Descriptions
                {
                    defaultLocale = "en",
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Blue"
                        }
                    }
                }
            };

            SimpleValue svRed = new SimpleValue
            {
                value        = "red",
                key          = "red",
                locale       = "en",
                Descriptions = new Descriptions
                {
                    defaultLocale = "en",
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Red"
                        }
                    }
                }
            };

            SimpleValue svVolvo = new SimpleValue
            {
                value        = "volvo",
                key          = "volvo",
                locale       = "en",
                Descriptions = new Descriptions
                {
                    defaultLocale = "en",
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Volvo"
                        }
                    }
                }
            };

            SimpleValue svSaab = new SimpleValue
            {
                value        = "saab",
                key          = "saab",
                locale       = "en",
                Descriptions = new Descriptions
                {
                    defaultLocale = "en",
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Saab"
                        }
                    }
                }
            };
            #endregion

            #region Search Filters
            var _langResolver = ServiceLocator.Current.GetInstance <LanguageResolver>();

            SearchFilter searchFilterColor = new SearchFilter
            {
                field = "color",

                // mandatory
                Descriptions = new Descriptions
                {
                    defaultLocale = _langResolver.GetPreferredCulture().Name,
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Color"
                        }
                    }
                },

                Values = new SearchFilterValues
                {
                    SimpleValue = new SimpleValue[]
                    {
                        svWhite,
                        svBlue,
                        svRed
                    }
                }
            };

            SearchFilter searchFilterBrand = new SearchFilter
            {
                field = "brand",

                Descriptions = new Descriptions
                {
                    defaultLocale = _langResolver.GetPreferredCulture().Name,
                    Description   = new Description[]
                    {
                        new Description {
                            locale = "en", Value = "Brand"
                        }
                    }
                },

                Values = new SearchFilterValues
                {
                    SimpleValue = new SimpleValue[]
                    {
                        svSaab,
                        svVolvo
                    }
                }
            };
            #endregion

            criteria.Add(searchFilterColor);
            criteria.Add(searchFilterBrand);
        }
Esempio n. 33
0
        /// <summary>
        /// Binds the results.
        /// </summary>
        private void BindResults(bool list)
        {
            SearchSort sortObject = CatalogEntrySearchCriteria.DefaultSortOrder;
            //string sort = SortBy.SelectedValue;
            //if (!String.IsNullOrEmpty(sort))
            //{
            //    if (sort.Equals("name", StringComparison.OrdinalIgnoreCase))
            //        sortObject = new SearchSort("displayname");
            //    else if (sort.Equals("plh", StringComparison.OrdinalIgnoreCase))
            //        sortObject =
            //            new SearchSort(String.Format("saleprice{0}", SiteContext.Current.CurrencyCode).ToLower());
            //    else if (sort.Equals("phl", StringComparison.OrdinalIgnoreCase))
            //        sortObject =
            //            new SearchSort(String.Format("saleprice{0}", SiteContext.Current.CurrencyCode).ToLower(), true);
            //}

            var group = new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull);
            SearchFilterHelper         helper   = SearchFilterHelper.Current;
            CatalogEntrySearchCriteria criteria = helper.CreateSearchCriteria("", sortObject);

            //AddNodesToCriteria(criteria);
            criteria.RecordsToRetrieve = 25;
            criteria.StartingRecord    = _startRowIndex;
            criteria.ClassTypes.Add("Product");

            var searchManager = new SearchManager(AppContext.Current.ApplicationName);

            try
            {
                var results = searchManager.Search(criteria);
                if (results == null)
                {
                    return;
                }

                var resultIndexes = results.GetKeyFieldValues <int>();
                var entries       = CatalogContext.Current.GetCatalogEntries(resultIndexes, group);
                if (entries.Entry != null)
                {
                    var ds = CreateDataSource(entries, results.TotalCount);
                    if (!list)
                    {
                        EntriesList.DataSource = ds;
                        EntriesList.DataBind();
                        EntriesList.Visible = true;
                        listView.Visible    = false;
                    }
                    else
                    {
                        listView.DataSource = ds;
                        listView.DataBind();
                        EntriesList.Visible = false;
                        listView.Visible    = true;
                    }

                    if (results.TotalCount < 25)
                    {
                        DataPager3.Visible = false;
                    }
                }

                _filters = helper.SelectedFilters;
                _facets  = results.FacetGroups;

                if (_filters != null && _filters.Length > 0)
                {
                    ActiveFilterList.DataSource = _filters;
                    ActiveFilterList.DataBind();
                    ActiveFilterList.Visible = true;
                }
                else
                {
                    ActiveFilterList.Visible = false;
                }

                if (_facets != null && _facets.Length > 0)
                {
                    FilterList.Visible    = true;
                    FilterList.DataSource = _facets;
                    FilterList.DataBind();
                }
                else
                {
                    FilterList.Visible = false;
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger(GetType()).Error(ex.Message, ex);
            }
        }
        public ActionResult ProviderModelFilteredSearch(string keyWord, string group, string facet)
        {
            var vmodel = new PMSearchResultViewModel();

            vmodel.SearchQueryText = keyWord;

            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                RecordsToRetrieve = 200, // there is a default of 50
                                         // Locale have to be there… else no hits
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            #region Options
            //criteria.Sort = CatalogEntrySearchCriteria.DefaultSortOrder;
            //criteria.CatalogNames.Add("Fashion");
            //criteria.ClassTypes.Add(EntryType.Variation);
            //criteria.MarketId = MarketId.Default;
            //criteria.IsFuzzySearch = true;
            //criteria.FuzzyMinSimilarity = 0.7F;
            //criteria.IncludeInactive = true;
            //System.Collections.Specialized.StringCollection sc =
            //    new System.Collections.Specialized.StringCollection
            //    {
            //        "Fashion/Clothes_1/Men_1/Shirts_1",
            //        "Fashion/Clothes_1/UniSex_1"
            //    };
            //criteria.Outlines = sc;

            #endregion Options

            //string _SearchConfigPath = @"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            //TextReader reader = new StreamReader(_SearchConfigPath);
            //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            //reader.Close();
            //foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            //{
            //    criteria.Add(filter);
            //}

            CreateFacetsByCode(criteria);

            foreach (SearchFilter filter in criteria.Filters)
            {
                if (filter.field.ToLower() == group.ToLower())
                {
                    var svFilter = filter.Values.SimpleValue
                                   .FirstOrDefault(x => x.value.Equals(facet, StringComparison.OrdinalIgnoreCase));
                    if (svFilter != null)
                    {
                        //This overload to Add causes the filter to be applied
                        criteria.Add(filter.field, svFilter);
                    }
                }
            }

            SearchManager manager = new SearchManager("ECApplication");

            // Do search
            ISearchResults results = manager.Search(criteria);

            vmodel.SearchResults = results.Documents.ToList();
            vmodel.FacetGroups   = results.FacetGroups.ToList();
            vmodel.ResultCount   = results.Documents.Count.ToString();

            return(View("ProviderModelQuery", vmodel));
        }
Esempio n. 35
0
        /// <summary>
        /// Creates the search criteria.
        /// </summary>
        /// <param name="keywords">The keywords.</param>
        /// <param name="sort">The sort.</param>
        /// <returns></returns>
        public CatalogEntrySearchCriteria CreateSearchCriteria(string keywords, SearchSort sort)
        {
            NameValueCollection querystring     = HttpContext.Current.Request.QueryString;
            string currentNodeCode              = querystring["nc"];
            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria();

            if (!String.IsNullOrEmpty(currentNodeCode))
            {
                criteria.CatalogNodes.Add(currentNodeCode);

                // Include all the sub nodes in our search results
                CatalogDto catalogs = CatalogContext.Current.GetCatalogDto(CMSContext.Current.SiteId);
                foreach (CatalogDto.CatalogRow catalog in catalogs.Catalog)
                {
                    CatalogNodes nodes = CatalogContext.Current.GetCatalogNodes(catalog.Name, querystring["nc"]);
                    if (nodes.CatalogNode != null && nodes.CatalogNode.Length > 0)
                    {
                        foreach (CatalogNode nodeRow in nodes.CatalogNode)
                        {
                            criteria.CatalogNodes.Add(nodeRow.ID);
                        }
                    }
                }
            }

            criteria.SearchPhrase = keywords;
            criteria.SearchIndex.Add(querystring["filter"]);
            criteria.Sort = sort;

            // Add all filters
            foreach (SearchFilter filter in SearchConfig.SearchFilters)
            {
                // Check if we already filtering
                if (querystring.Get(filter.field) != null)
                {
                    continue;
                }

                criteria.Add(filter);
            }

            // Get selected filters
            SelectedFilter[] filters = SelectedFilters;
            if (filters.Length != 0)
            {
                foreach (SelectedFilter filter in filters)
                {
                    if (filter.PriceRangeValue != null)
                    {
                        criteria.Add(filter.Filter.field, filter.PriceRangeValue);
                    }
                    if (filter.RangeValue != null)
                    {
                        criteria.Add(filter.Filter.field, filter.RangeValue);
                    }
                    if (filter.SimpleValue != null)
                    {
                        criteria.Add(filter.Filter.field, filter.SimpleValue);
                    }
                }
            }

            return(criteria);
        }