public IEnumerable <Person> GetAll(out int totalResults, int page = 0, int pageSize = 20)
        {
            SearchResults <SearchResultItem> results;

            using (IProviderSearchContext searchContext = _index.CreateSearchContext())
            {
                results = GetBaseQueryable <SearchResultItem>(searchContext)
                          .OrderBy(i => i.Name)
                          .Page(page, pageSize)
                          .GetResults();
            }

            totalResults = results.TotalSearchResults;
            return(AsPersons(results));
        }
Exemple #2
0
        public void Items_IndexHaveNonexistentItems_ReturnsExistentItems([Content] DbItem[] contentItems, DbItem brokenItem,
                                                                         List <DbItem> indexedItems, ISearchIndex index, string indexName,
                                                                         [Frozen] SearchProvider searchProvider, Switcher <SearchProvider> searchProviderSwitcher,
                                                                         [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
        {
            //arrange
            indexedItems.AddRange(contentItems);
            indexedItems.Add(brokenItem);
            renderingPropertiesRepository.Get <QueryableDatasourceRenderingSettings>()
            .Returns(new QueryableDatasourceRenderingSettings
            {
                SearchResultsLimit = 10
            });

            var results = GetResults(indexedItems);

            InitIndexes(index, searchProvider, results);
            var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
            {
                DatasourceString = "notEmpty"
            };

            //act
            var items = renderingModel.Items.ToArray();


            //assert
            items.Count().Should().Be(contentItems.Length);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
Exemple #3
0
        public void Items_ItemTemplateSet_FiltersByTemplateId(Db db, [Content] DbTemplate templateItem, [Content] DbItem[] contentItems, ISearchIndex index, [Frozen] SearchProvider searchProvider, Switcher <SearchProvider> searchProviderSwitcher, string indexName, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
        {
            //arrange
            var dbItem = new DbItem("templated", ID.NewID, templateItem.ID);

            db.Add(dbItem);
            var dbItems = contentItems.ToList();

            dbItems.Add(dbItem);
            var results = GetResults(dbItems);

            renderingPropertiesRepository.Get <QueryableDatasourceRenderingSettings>()
            .Returns(new QueryableDatasourceRenderingSettings
            {
                SearchResultsLimit = 10
            });

            InitIndexes(index, searchProvider, results);


            var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
            {
                Rendering          = new Rendering(),
                DatasourceString   = "notEmpty",
                DatasourceTemplate = db.GetItem(templateItem.ID)
            };

            //act
            var items = renderingModel.Items;

            //assert
            items.Count().Should().Be(1);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
Exemple #4
0
        public string AutoComplete(string querytext)
        {
            var          indexName = String.Format("sitecore_{0}_index", Sitecore.Context.Database.Name);
            ISearchIndex index     = ContentSearchManager.GetIndex(indexName);
            var          tID       = new ID("{766464BE-12CA-4441-8DF2-2D3865B57B23}");

            List <string> Listtm = new List <string>();

            using (IProviderSearchContext context = index.CreateSearchContext())
            {
                var query = context.GetQueryable <TestModel>();//.Where(x => x.title.Contains("News"));
                query = query.Filter(x => x.TemplateId == tID);
                var results     = query.GetResults();
                var finalresult = results.Hits.Select(h => GetSiteCoreItem(h.Document.ItemId)).ToArray();

                foreach (var Item in finalresult)
                {
                    JsonModel tm = new JsonModel();
                    Listtm.Add(Item.Fields["title"].ToString());
                    // tm.title = Item.Fields["title"].ToString();
                    //    Listtm.Add(tm);
                }
            }
            return(JsonConvert.SerializeObject(Listtm));
        }
Exemple #5
0
        public void Items_DifferentItemLanguageExists_ReturnsOnlyContextLanguage([Content] DbItem[] contentItems, ISearchIndex index, [Frozen] SearchProvider searchProvider, Switcher <SearchProvider> searchProviderSwitcher, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
        {
            //arrange
            var results = GetResults(contentItems).ToArray();

            results.First().Language = "noncontext";
            renderingPropertiesRepository.Get <QueryableDatasourceRenderingSettings>()
            .Returns(new QueryableDatasourceRenderingSettings
            {
                SearchResultsLimit = 10
            });

            InitIndexes(index, searchProvider, results.AsQueryable());
            var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
            {
                DatasourceString = "notEmpty"
            };

            //act
            var items = renderingModel.Items;

            //assert
            items.Count().Should().Be(contentItems.Length - 1);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
Exemple #6
0
        public static Author GetAuthorByName(Item currentItem, string authorName)
        {
            try
            {
                BlogSettings settingsItem = General.DataManager.GetBlogSettingsItem(currentItem);
                ISearchIndex index        = ContentSearchManager.GetIndex(new SitecoreIndexableItem(settingsItem.AuthorFolder));

                using (IProviderSearchContext context = index.CreateSearchContext())
                {
                    Expression <Func <SearchResultItem, bool> > predicate = PredicateBuilder.True <SearchResultItem>();
                    predicate = predicate.And(item => item.TemplateId == ID.Parse(Author.AuthorTemplateId) && item.Paths.Contains(settingsItem.AuthorFolder.ID));
                    predicate = predicate.And(c => c[Author.AuthorFullNameField] == authorName);

                    IQueryable <SearchResultItem> results = context.GetQueryable <SearchResultItem>().Where(predicate).OrderBy(t => t.Name);
                    if (results.Any())
                    {
                        return(results.FirstOrDefault().GetItem().CreateAs <Author>());
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("XBlog GetCategory error", ex, new object());
            }
            return(null);
        }
        public void Items_NotLatestItemVersionExists_ReturnsOnlyLatestItems([Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
        {
            //arrange
            var results = GetResults(contentItems).ToArray();

            results.First().IsLatestVersion = false;
            renderingPropertiesRepository.Get <QueryableDatasourceRenderingSettings>()
            .Returns(new QueryableDatasourceRenderingSettings
            {
                SearchResultsLimit = 10
            });

            InitIndexes(index, searchProvider, results.AsQueryable());
            var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
            {
                DatasourceString = "notEmpty"
            };

            //act
            var items = renderingModel.Items;

            //assert
            items.Count().Should().Be(contentItems.Length - 1);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
        public IPagedList <TextSearchResultModel> GetPage(string searchText, int pageNum, int pageSize, Item siteRoot)
        {
            var indexable = new SitecoreIndexableItem(siteRoot);

            ISearchIndex index = ContentSearchManager.GetIndex(indexable);

            using (var context = index.CreateSearchContext())
            {
                var slop             = 0.0f;
                var headingBoost     = 1.0f;
                var copyBoost        = 0.9f;
                var summaryBoost     = 0.8f;
                var descriptionBoost = 0.8f;
                var keywordsBoost    = 0.7f;


                IQueryable <TextSearchResultModel> query = context.GetQueryable <TextSearchResultModel>();

                query = query
                        .Filter(i => i.Language == siteRoot.Language.Name)
                        .Filter(i => i.Paths.Contains(siteRoot.ID))
                        .Filter(i => !i.Name.StartsWith("_"))
                        .Where(i =>
                               i.Heading.Like(searchText, slop).Boost(headingBoost) ||
                               i.Copy.Like(searchText, slop).Boost(copyBoost) ||
                               i.Summary.Like(searchText, slop).Boost(summaryBoost) ||
                               i.Description.Like(searchText, slop).Boost(descriptionBoost) ||
                               i.Keywords.Like(searchText, slop).Boost(keywordsBoost) ||
                               i.AggregateText.Like(searchText, slop));

                return(query.ToPagedList(pageNum, pageSize));
            }
        }
        public new IEnumerable <TestingSearchResultItem> GetRunningTestsWithDataSourceItem(Item dataSourceItem)
        {
            ISearchIndex testingSearchIndex = GetTestingSearchIndex();

            if (testingSearchIndex == null)
            {
                return(Enumerable.Empty <Models.TestingSearchResultItem>());
            }
            using (IProviderSearchContext providerSearchContext = testingSearchIndex.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
            {
                Expression <Func <Models.TestingSearchResultItem, bool> > predicate = PredicateBuilder.True <Models.TestingSearchResultItem>();
                predicate = AddDatesSearchCriteria(predicate);
                predicate = AddDefaultSearchCriteria(predicate);

                // Querying our new field that is TriState compatible
                predicate = predicate.And((Models.TestingSearchResultItem x) => x.IsRunningString == "1");

                // https://doc.sitecore.com/developers/90/platform-administration-and-architecture/en/support-reference-for-azure-search.html
                // Quote: You must not apply queries such as StartsWith, Contains to fields with of type EDM.String that contain paths (such as /sitecore/content/home) or collections of GUIDs.
                //        This is because Azure Search matches regular expression searches to single words.
                //
                // Alright then we must fix this. DataSourceItems contains path like content...
                // "datasourceitems_s": "sitecore://{B765C5DD-E0AD-4D91-BA63-B082656ED909}?lang=en&ver=1|sitecore://{C547CF9A-D9CC-42D7-A1D5-B14AB9BBD870}?lang=en&ver=1"

                // Therefore I introduced a new field with a propper value in it that won't need any special escape characters
                string dataSourceId = dataSourceItem.ID.ToShortID().ToString().Replace("-", string.Empty);
                predicate = predicate.And((Models.TestingSearchResultItem x) => x.DataSourceItemsTidy.Contains(dataSourceId));
                var result = providerSearchContext.GetQueryable <Models.TestingSearchResultItem>().Where(predicate).ToArray();
                return(result);
            }
        }
Exemple #10
0
        private UrlString GetRedirectUrl(Uri returnUrl)
        {
            // NOTE [ILs] Don't redirect to absolute uris for redirectUrl after login, this may be a nefarious attempt to steal user information
            string result = returnUrl != null && returnUrl.IsAbsoluteUri ? string.Empty : returnUrl?.OriginalString;

            if (string.IsNullOrWhiteSpace(result))
            {
                SearchResultItem searchResult;
                using (IProviderSearchContext searchContext = _searchIndex.CreateSearchContext())
                {
                    searchResult =
                        searchContext.GetQueryable <SearchResultItem>()
                        .FirstOrDefault(
                            i => i.Paths.Contains(_siteRoot) && i.TemplateId == Templates.LoginSettings.Id);
                }

                Item loginSettingsItem = searchResult?.GetItem();
                if (loginSettingsItem != null)
                {
                    LinkField linkField  = loginSettingsItem.Fields[Templates.LoginSettings.Fields.PostLoginRedirect];
                    Item      targetItem = linkField.TargetID != (ID)null && linkField.TargetID != ID.Null
                                          ? _db.GetItem(linkField.TargetID)
                                          : null;

                    result = targetItem != null?LinkManager.GetItemUrl(targetItem) : null;
                }
            }

            return(new UrlString(result ?? "/"));
        }
        public new IEnumerable <TestingSearchResultItem> GetRunningTestsInAllLanguages(Item hostItem)
        {
            Assert.ArgumentNotNull(hostItem, "hostItem");
            ISearchIndex testingSearchIndex = GetTestingSearchIndex();

            if (testingSearchIndex == null)
            {
                return(Enumerable.Empty <Models.TestingSearchResultItem>());
            }
            List <Models.TestingSearchResultItem> list = new List <Models.TestingSearchResultItem>();

            using (IProviderSearchContext providerSearchContext = testingSearchIndex.CreateSearchContext(SearchSecurityOptions.DisableSecurityCheck))
            {
                Expression <Func <Models.TestingSearchResultItem, bool> > first = PredicateBuilder.True <Models.TestingSearchResultItem>();
                Language[] languages = hostItem.Languages;
                foreach (Language language in languages)
                {
                    Item itemInLanguage = hostItem.Database.GetItem(hostItem.ID, language);

                    // This is de wrong implementation because it only focusses on if the current item is the initiator/host of the test.
                    first = first.Or((Models.TestingSearchResultItem x) => x.HostItemPartial == FieldFormattingHelper.FormatUriForSearch(itemInLanguage));

                    // It should focus on if the current item is subject of the actual test.
                    string dataSourceId = itemInLanguage.ID.ToShortID().ToString().Replace("-", string.Empty);
                    first = first.Or((Models.TestingSearchResultItem x) => x.DataSourceItemsTidy.Contains(dataSourceId));
                }

                // Querying our new field that is TriState compatible
                first = first.And((Models.TestingSearchResultItem x) => x.IsRunningString == "1");
                list.AddRange(providerSearchContext.GetQueryable <Models.TestingSearchResultItem>().Where(first).ToArray());
                return(list);
            }
        }
    public void ShouldGetFreeProducts(
      SearchRepository sut,
      ISearchIndex searchIndex,
      IIndexable indexable,
      [Frozen]SearchProvider provider,
      Switcher<SearchProvider> switcher)
    {
      // arrange
      searchIndex
        .CreateSearchContext()
        .GetQueryable<ProductSearchResultItem>()
        .Returns(new[]
          {
            new ProductSearchResultItem { Free = true },
            new ProductSearchResultItem { Free = false },
            new ProductSearchResultItem { Free = true }
          }.AsQueryable());

      ContentSearchManager.SearchConfiguration.Indexes["indexName"] = searchIndex;
      provider.GetContextIndexName(indexable, Arg.Any<ICorePipeline>()).Returns("indexName");

      // act
      var products = sut.GetProducts(indexable);

      // assert
      Assert.Equal(2, products.Count());
    }
Exemple #13
0
        private List<Item> GetLinkedSitecoreItems(string gcId)
        {
            var result = new List<Item>();

            ISearchIndex index = ContentSearchManager.Indexes.SingleOrDefault(i => i.Name.Equals(IndexName));

            if (index == null)
            {
                Log.Warn("Index " + IndexName + " not found!", this);
                return result;
            }

            using (IProviderSearchContext context = index.CreateSearchContext())
            {
                var query = context.GetQueryable<SearchResultItem>()
                    .Where(i => i.Path.StartsWith("/sitecore/content/") &&
                                i["gc_content_id"] == gcId
                    );

                query = query.Filter(i => i.Language == Context.Language.Name);

                var res = query.GetResults();
                if (res.TotalSearchResults == 0)
                {
                    return result;
                }

                result = res.Hits
                    .Select(h => h.Document.GetItem())
                    .Where(i => i != null)
                    .ToList();

                return result;
            }
        }
        public IEnumerable <Suggestion> GetSuggestions(SuggesterModel model, out XA.Foundation.Search.Timer queryTimer, out string indexName)
        {
            bool         fuzzy       = Configuration.Settings.GetBoolSetting("AzureSearchSuggesterFuzzy", false);
            bool         highlights  = Configuration.Settings.GetBoolSetting("AzureSearchSuggesterHighlight", false);
            ISearchIndex searchIndex = IndexResolver.ResolveIndex(!model.ContextItemID.IsNull ? ContentRepository.GetItem(model.ContextItemID) : null);

            indexName = searchIndex.Name;
            searchIndex.Initialize();
            using (IProviderSearchContext searchContext = searchIndex.CreateSearchContext(SearchSecurityOptions.Default))
            {
                SuggestParameters sp = new SuggestParameters()
                {
                    UseFuzzyMatching = fuzzy, Top = 5
                };
                if (highlights)
                {
                    string tag = Configuration.Settings.GetSetting("AzureSearchSuggesterHighlightTag");
                    sp.HighlightPreTag  = $"<{tag}>";
                    sp.HighlightPostTag = $"</{tag}>";
                }

                AzureSuggestQuery term = model.Term;
                DocumentSuggestResult <Document> handlerQueryResults;
                using (queryTimer = new XA.Foundation.Search.Timer())
                    handlerQueryResults = searchContext.Suggest(term, Configuration.Settings.GetSetting("AzureSearchSuggesterName"), sp);
                return(handlerQueryResults.Results.Select(a => new Suggestion()
                {
                    Term = a.Text,
                    Payload = JsonConvert.SerializeObject(a.Document)
                }));
            }
        }
Exemple #15
0
        public void Items_ItemTemplateSet_FiltersByTemplateId(Db db, [Content] DbTemplate templateItem, [Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, string indexName, [Content] Item renderingItem)
        {
            //arrange
            var dbItem = new DbItem("templated", ID.NewID, templateItem.ID);

            db.Add(dbItem);
            var dbItems = contentItems.ToList();

            dbItems.Add(dbItem);
            var results = GetResults(dbItems);

            InitIndexes(index, searchProvider, results);


            var renderingModel = new QueryableDatasourceRenderingModel()
            {
                Rendering = new Rendering()
                {
                    DataSource = "notEmpty"
                }
            };

            renderingModel.DatasourceTemplate = db.GetItem(templateItem.ID);

            //act
            var items = renderingModel.Items;

            //assert
            items.Count().Should().Be(1);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
Exemple #16
0
 public static IEnumerable <BlogPost> GetBlogPostsMK([NotNull] Item blogRoot, int startRowIndex, int maximumRows, bool descending)
 {
     try
     {
         ISearchIndex index = ContentSearchManager.GetIndex(new SitecoreIndexableItem(blogRoot));
         using (IProviderSearchContext context = index.CreateSearchContext())
         {
             Expression <Func <SearchResultItem, bool> > predicate = GetBlogItemsQueryPredicate(blogRoot);
             if (descending)
             {
                 //.Slice(startRowIndex, maximumRows)
                 return(context.GetQueryable <SearchResultItem>().Where(predicate)
                        .OrderByDescending(result => result["TODO REPLACE THIS WITH THE PUBLISH DATE FIELD THAT LUCENE HAS"])
                        .CreateAs <BlogPost>());
             }
             else
             {
                 return(context.GetQueryable <SearchResultItem>().Where(predicate)
                        .OrderBy(result => result["TODO REPLACE THIS WITH THE PUBLISH DATE FIELD THAT LUCENE HAS"])
                        .CreateAs <BlogPost>());
             }
         }
     }
     catch (Exception ex)
     {
         Log.Error("XBlog GetBlogPosts error", ex, new object());
     }
     return(Enumerable.Empty <BlogPost>());
 }
Exemple #17
0
        public void ShouldGetFreeProducts(
            SearchRepository sut,
            ISearchIndex searchIndex,
            IIndexable indexable,
            [Frozen] SearchProvider provider,
            Switcher <SearchProvider> switcher)
        {
            // arrange
            searchIndex
            .CreateSearchContext()
            .GetQueryable <ProductSearchResultItem>()
            .Returns(new[]
            {
                new ProductSearchResultItem {
                    Free = true
                },
                new ProductSearchResultItem {
                    Free = false
                },
                new ProductSearchResultItem {
                    Free = true
                }
            }.AsQueryable());

            ContentSearchManager.SearchConfiguration.Indexes["indexName"] = searchIndex;
            provider.GetContextIndexName(indexable, Arg.Any <ICorePipeline>()).Returns("indexName");

            // act
            var products = sut.GetProducts(indexable);

            // assert
            Assert.Equal(2, products.Count());
        }
Exemple #18
0
        public void Items_IndexHaveNonexistentItems_ReturnsExistentItems([Content] DbItem[] contentItems, DbItem brokenItem, List <DbItem> indexedItems, ISearchIndex index, string indexName, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem)
        {
            //arrange
            indexedItems.AddRange(contentItems);
            indexedItems.Add(brokenItem);

            var results = GetResults(indexedItems);

            InitIndexes(index, searchProvider, results);
            var renderingModel = new QueryableDatasourceRenderingModel()
            {
                Rendering = new Rendering()
                {
                    DataSource = "notEmpty"
                }
            };

            //act
            var items = renderingModel.Items.ToArray();


            //assert
            items.Count().Should().Be(contentItems.Length);
            index.CreateSearchContext().ReceivedWithAnyArgs(1);
        }
 public static IEnumerable <string> GetAllFieldValues(this ISearchIndex index, string fieldName)
 {
     using (var context = index.CreateSearchContext())
     {
         var termsByFieldName = context.GetTermsByFieldName((fieldName ?? "").ToLowerInvariant(), null);
         return(termsByFieldName
                .Select(x => x.Term)
                .ToArray());
     }
 }
        public List <ProductSearchItem> GetProducts(ID templateId)
        {
            //var predicate = PredicateBuilder.True<Brand>()
            //    .And(p => p.TemplateId == templateId)
            //    .And(p => !p.Name.Equals("__Standard Values"));
            ////.And(p => p.Language == Context.Language.Name);
            //var results = GetSolrResult(predicate).ToList();
            //return results;
            List <ProductSearchItem> ProductResultItems = new List <ProductSearchItem>();
            //var language = Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName.ToString();
            //var index = ContentSearchManager.GetIndex("sitecore_web_index");
            //using (var context = index.CreateSearchContext())
            //{
            //    var predicate = PredicateBuilder.True<SearchResultItem>();

            //    predicate = predicate.And((p => p.TemplateId == templateId));
            //   // predicate = predicate.And((p => p.Language == language));


            //    var results = context.GetQueryable<SearchResultItem>().Where(predicate).ToList();

            //}
            ISearchIndex indexbrand = ContentSearchManager.GetIndex("website_custom_product");

            using (IProviderSearchContext context = indexbrand.CreateSearchContext())
            {
                System.Linq.Expressions.Expression <Func <Library.SC.Lucene.ProductSearchItem, bool> > predicate = PredicateBuilder.True <Library.SC.Lucene.ProductSearchItem>();
                predicate          = predicate.And(p => p._language.Equals(Garnier.Library.SC.Utility.Extensions.currentContextLanguage()));
                predicate          = predicate.And(p => p.TemplateId == Lookups.TemplateProductID);
                ProductResultItems = context.GetQueryable <Library.SC.Lucene.ProductSearchItem>()
                                     .Where(predicate)
                                     .ToList();
            }
            if (ProductResultItems != null && ProductResultItems.Count > 0)
            {
                //List<Sitecore.Data.Items.Item> ResultItems = new List<Sitecore.Data.Items.Item>();

                //foreach (Library.SC.Lucene.BrandSearchItem ProductResultItem in ProductResultItems)
                //{
                //    Sitecore.Data.Items.Item thisItem = ProductResultItem.GetContextItem(ResultItems);
                //    if (thisItem != null && thisItem.itemIsValid() && (thisItem.itemHasValidChildren()))
                //    {
                //        ResultItems.Add(thisItem);
                //    }
                //}
                //return ResultItems;
                return(ProductResultItems);
            }
            else
            {
                return(new List <Library.SC.Lucene.ProductSearchItem>());
            }

            //return list;
        }
Exemple #21
0
        public static Dictionary <string, int> GetTagCloud(Item currentItem)
        {
            Dictionary <string, int> tagItems = new Dictionary <string, int>();

            try
            {
                Item         repositorySearchItem = XBlog.General.DataManager.GetBlogHomeItem(currentItem);
                BlogSettings settingsItem         = XBlog.General.DataManager.GetBlogSettingsItem(currentItem);
                ISearchIndex index = ContentSearchManager.GetIndex(new SitecoreIndexableItem(settingsItem.AuthorFolder));

                using (IProviderSearchContext context = index.CreateSearchContext())
                {
                    // look at the pipe seperated list.  break them out and loop through.  Build dictionary based on Ids
                    // create as blog post item
                    // could even pass a max item as a dictionary definition
                    Expression <Func <SearchResultItem, bool> > predicate = PredicateBuilder.True <SearchResultItem>();
                    predicate = predicate.And(item => item.TemplateName == BlogPost.BlogPostTemplate && item.Paths.Contains(repositorySearchItem.ID));

                    IEnumerable <BlogPostTagString> resultList = context.GetQueryable <SearchResultItem>().Where(predicate).CreateAs <BlogPostTagString>();

                    List <ID> listIDs = context.GetQueryable <SearchResultItem>().Where(predicate).Select(result => result.ItemId).ToList();

                    tagItems.Add("max", 0);
                    foreach (BlogPostTagString item in resultList)
                    {
                        char[]   delimiterChars = { '|' };
                        string[] itemIDs        = item.TagString.Split(delimiterChars);

                        foreach (string itemID in itemIDs)
                        {
                            if (tagItems.ContainsKey(itemID))
                            {
                                tagItems[itemID] += 1;
                            }
                            else
                            {
                                tagItems.Add(itemID, 1);
                            }

                            if (tagItems[itemID] > tagItems["max"])
                            {
                                tagItems["max"] = tagItems[itemID];
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("XBlog GetTagCloud error", ex, new object());
            }
            return(tagItems);
        }
        private List <SearchResultItem> GetRecommendedRenderingItems()
        {
            ISearchIndex index = ContentSearchManager.GetIndex("sitecore_master_index");

            using (IProviderSearchContext context = index.CreateSearchContext())
            {
                var results = context.GetQueryable <SearchResultItem>()
                              .Where(x => x.TemplateId.Guid == Templates.AvailableRenderings.Id.Guid &&
                                     x.Name == Constants.Values.RecommendedRenderingsItemName);

                return(results.ToList());
            }
        }
 public static IEnumerable <string> GetSearchTerms(this ISearchIndex index, string prefix = "")
 {
     using (var context = index.CreateSearchContext())
     {
         var termsByFieldName = context.GetTermsByFieldName("_content", prefix)
                                .Union(context.GetTermsByFieldName("tagname", prefix))
                                .Union(context.GetTermsByFieldName("displayname", prefix));
         return(termsByFieldName
                .OrderByDescending(x => x.DocumentFrequency)
                .Select(x => x.Term)
                .Distinct()
                .ToArray());
     }
 }
Exemple #24
0
        /// <summary>
        /// Requires the following field to be patched in: <field fieldName="_templates"                 returnType="string"      type="Sitecore.ContentSearch.ComputedFields.AllTemplates, Sitecore.ContentSearch" deep="true" includeStandardTemplate="false" />
        /// </summary>
        /// <param name="index">The search index to search within.</param>
        /// <returns></returns>
        protected IEnumerable <Item> GetSpeedyPagesByTemplate(ISearchIndex index)
        {
            using (var searchContext = index.CreateSearchContext())
            {
                var speedyPages = searchContext.GetQueryable <AllTemplatesSearchResultItem>().Where(x => x.ItemBaseTemplates.Contains(SpeedyConstants.TemplateIDs.SpeedyPageTemplateId));
                if (!speedyPages.Any())
                {
                    return(new List <Item>());
                }

                var sitecoreItems = speedyPages.Select(x => x.GetItem()).ToList().Where(y => y.IsEnabled(Fields.SpeedyEnabled));
                return(sitecoreItems.ToList());
            }
        }
Exemple #25
0
        public IEnumerable <Sitecore.Data.Items.Item> BasicSearch(string querytext)
        {
            var          indexName = String.Format("sitecore_{0}_index", Sitecore.Context.Database.Name);
            ISearchIndex index     = ContentSearchManager.GetIndex(indexName);
            var          tID       = new ID("{766464BE-12CA-4441-8DF2-2D3865B57B23}");

            using (IProviderSearchContext context = index.CreateSearchContext())
            {
                var query = context.GetQueryable <TestModel>().Where(x => x.description.Contains(querytext));
                query = query.Filter(x => x.TemplateId == tID);
                var results = query.GetResults();
                return(results.Hits.Select(h => GetSiteCoreItem(h.Document.ItemId)).ToArray());
            }
        }
        public void Items_EmptyDatasource_ReturnsEmptyCollection([ResolvePipeline("getRenderingDatasource")] EmptyPipeline processor, List <DbItem> indexedItems, SearchProvider searchProvider, ISearchIndex index, string indexName, [Content] Item renderingItem)
        {
            //arrange

            InitIndexes(index, searchProvider, new List <SearchResultItem>().AsQueryable());
            var renderingModel = new QueryableDatasourceRenderingModel();

            //act
            var items = renderingModel.Items;

            //assert
            items.Count().Should().Be(0);
            index.CreateSearchContext().DidNotReceiveWithAnyArgs();
        }
        public Facets GetFacets(ISearchIndex index, string search)
        {
            if (search == null)
            {
                search = string.Empty;
            }

            int contentLength = 0;
            var renderings    = PageContext.CurrentOrNull.PageDefinition.Renderings;

            if (renderings != null)
            {
                foreach (var rendering in renderings)
                {
                    if (rendering.Parameters["ContentBodyMaxLength"] != null)
                    {
                        int.TryParse(rendering.Parameters["ContentBodyMaxLength"], out contentLength);
                    }
                }
            }

            using (var context = index.CreateSearchContext())
            {
                var found = context.GetQueryable <EventDetails>().Where(j => j.Name.Contains(search));
                if (contentLength > 0)
                {
                    found = found.Where(j => j.ComputedContentLength <= contentLength);
                }
                var result    = found.FacetOn(j => j.Duration, 1).GetResults();
                var durations = result.Facets.Categories[0].Values.
                                Select(f => new Facet()
                {
                    Name = f.Name, Count = f.AggregateCount
                });

                result = found.FacetOn(j => j.DifficultyLevel, 1).GetResults();
                var diffLevels = result.Facets.Categories[0].Values.
                                 Select(f => new Facet()
                {
                    Name = f.Name, Count = f.AggregateCount
                });
                return(new Facets()
                {
                    DurationFacets = durations.OrderByDescending(i => i.Count).ThenBy(i => i.Name).ToList(),
                    DifficultyFacets = diffLevels.OrderByDescending(i => i.Count).ThenBy(i => i.Name).ToList()
                });
            }
        }
    public void Items_IndexMatchDb_ReturnsAllItems([Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem)
    {
      //arrange
      var results = GetResults(contentItems);

      InitIndexes(index, searchProvider, results);
      var renderingModel = new QueryableDatasourceRenderingModel() { Rendering = new Rendering() { DataSource = "notEmpty" } };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(contentItems.Length);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);

    }
Exemple #29
0
        public void GetSearchResult_ItemsWithDifferentProperties_ReturnItemsFulfillingPredicate(
            ISearchQueryElementProvider elementProvider,
            IIndexNameProvider indexNameProvider,
            ISearchQueryPredicateBuilder <TestIndexableEntity> predicateBuilder,
            ISearchIndex searchIndex,
            [Frozen] SearchProvider provider,
            Switcher <SearchProvider> switcher)
        {
            // Arrange
            elementProvider
            .GetSearchQueryElementRoot <TestIndexableEntity>()
            .Returns(new SearchQueryGrouping <TestIndexableEntity>(LogicalOperator.And));

            indexNameProvider
            .IndexName
            .Returns("predicateTestIndex");

            predicateBuilder
            .GetOutput()
            .Returns(x => x.Name.Contains("F"));

            var queryable = new QueryProviderStub <TestIndexableEntity>(new[]
            {
                CreateTestIndexableEntity("Faucet", paths: new List <ID> {
                    ItemIDs.ContentRoot
                }),
                CreateTestIndexableEntity("Clamp", paths: new List <ID> {
                    ItemIDs.ContentRoot
                })
            }.AsQueryable());

            searchIndex
            .CreateSearchContext()
            .GetQueryable <TestIndexableEntity>()
            .Returns(queryable);

            ContentSearchManager.SearchConfiguration.Indexes[indexNameProvider.IndexName] = searchIndex;

            var sut = new SearchResultRepository <TestIndexableEntity>(elementProvider, indexNameProvider, predicateBuilder);

            // Act
            var actual = sut.GetSearchResult(new SearchCriteria());

            // Assert
            actual.TotalSearchResults.ShouldBeEquivalentTo(1);
            actual.Hits.First().Name.Should().Contain("F");
        }
    public void Items_NotLatestItemVersionExists_ReturnsOnlyLatestItems([Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem)
    {
      //arrange
      var results = GetResults(contentItems).ToArray();
      results.First().IsLatestVersion = false;

      InitIndexes(index, searchProvider, results.AsQueryable());
      var renderingModel = new QueryableDatasourceRenderingModel() { Rendering = new Rendering() { DataSource = "notEmpty" } };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(contentItems.Length-1);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);

    }
Exemple #31
0
        public List <Item> GetSearchResultsUsingQuery(string searchString)
        {
            //Getting index from the web.config
            List <Item> returnValues = new List <Item>();

            SearchIndexName = StringUtil.GetString(SearchIndexName, CommonText.get("Search Index"));;
            ISearchIndex searchIndex = null;

            try
            {
                searchIndex = ContentSearchManager.GetIndex(SearchIndexName);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
                return(null);
            }


            using (var context = searchIndex.CreateSearchContext())
            {
                IQueryable <SearchUIResultItem>            q          = context.GetQueryable <SearchUIResultItem>();
                List <SearchResults <SearchUIResultItem> > LstResults = new List <SearchResults <SearchUIResultItem> >();

                // //Query approach
                q = BuildSearchQuery(searchString, q);
                LstResults.Add(q.GetResults());

                List <string> uniqueIds = new List <string>();
                foreach (var results in LstResults)
                {
                    var sitecoreItem = results.Hits.Select(x => x.Document);
                    foreach (var item in sitecoreItem)
                    {
                        Item item1 = item.GetItem();
                        if (item1 != null && !uniqueIds.Contains(item1.ID.ToString()))
                        {
                            returnValues.Add(item1);
                            uniqueIds.Add(item1.ID.ToString());
                        }
                    }
                }
                return(returnValues);
            }
        }
        public IEnumerable <Pet> rpSubnavigation_GetData()
        {
            string       indexName = $"sitecore_{Sitecore.Context.Database.Name.ToLower()}_index";
            ISearchIndex index     = ContentSearchManager.GetIndex(indexName);

            using (var context = index.CreateSearchContext())
            {
                var querable = context.GetQueryable <Pet>().Where(x => x.Paths.Contains(Sitecore.Context.Item.ID) && x.TemplateName.Equals("Pet")).OrderBy(x => x.CreatedDate);

                var results = querable.GetResults();

                if (results.Hits.Any())
                {
                    return(results.Hits.Select(x => x.Document).ToList());
                }
            }

            return(new List <Pet>());
        }
Exemple #33
0
        public void GetSearchResult_ItemsWithDiffentVersions_ReturnItemsWithLatestVersion(
            ISearchQueryElementProvider elementProvider,
            IIndexNameProvider indexNameProvider,
            ISearchQueryPredicateBuilder <TestIndexableEntity> predicateBuilder,
            ISearchIndex searchIndex,
            [Frozen] SearchProvider provider,
            Switcher <SearchProvider> switcher)
        {
            // Arrange
            indexNameProvider
            .IndexName
            .Returns("languageTestIndex");

            predicateBuilder
            .GetOutput()
            .Returns(x => true);

            var queryable = new QueryProviderStub <TestIndexableEntity>(new[]
            {
                CreateTestIndexableEntity("Faucet", paths: new List <ID> {
                    ItemIDs.ContentRoot
                }, latestVersion: true),
                CreateTestIndexableEntity("Fence", paths: new List <ID> {
                    ItemIDs.ContentRoot
                }, latestVersion: false),
            }.AsQueryable());

            searchIndex
            .CreateSearchContext()
            .GetQueryable <TestIndexableEntity>()
            .Returns(queryable);

            ContentSearchManager.SearchConfiguration.Indexes[indexNameProvider.IndexName] = searchIndex;

            var sut = new SearchResultRepository <TestIndexableEntity>(elementProvider, indexNameProvider, predicateBuilder);

            // Act
            var actual = sut.GetSearchResult(new SearchCriteria());

            // Assert
            actual.TotalSearchResults.ShouldBeEquivalentTo(1);
            actual.Hits.First().Fields["_latestversion"].Should().Be("1");
        }
    public void Items_NotLatestItemVersionExists_ReturnsOnlyLatestItems([Content] DbItem[] contentItems, ISearchIndex index, [Frozen] SearchProvider searchProvider, Switcher<SearchProvider> searchProviderSwitcher, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      var results = GetResults(contentItems).ToArray();
      results.First().IsLatestVersion = false;
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      InitIndexes(index, searchProvider, results.AsQueryable());
      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        DatasourceString = "notEmpty"
      };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(contentItems.Length - 1);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_DifferentItemLanguageExists_ReturnsOnlyContextLanguage([Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      var results = GetResults(contentItems).ToArray();
      results.First().Language = "noncontext";
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      InitIndexes(index, searchProvider, results.AsQueryable());
      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        DatasourceString = "notEmpty"
      };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(contentItems.Length - 1);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_IndexMatchDb_ReturnsAllItems([Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      var results = GetResults(contentItems);
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      InitIndexes(index, searchProvider, results);
      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        DatasourceString = "notEmpty"
      };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(contentItems.Length);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_EmptyDatasource_ReturnsEmptyCollection([ResolvePipeline("getRenderingDatasource")] EmptyPipeline processor, List<DbItem> indexedItems,SearchProvider searchProvider, ISearchIndex index, string indexName, [Content] Item renderingItem)
    {
      //arrange

      InitIndexes(index, searchProvider, new List<SearchResultItem>().AsQueryable());
      var renderingModel = new QueryableDatasourceRenderingModel() { Rendering = new Rendering()};

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(0);
      index.CreateSearchContext().DidNotReceiveWithAnyArgs();
 
    }
    public void Items_IndexHaveNonexistentItems_ReturnsExistentItems([Content] DbItem[] contentItems, DbItem brokenItem, List<DbItem> indexedItems, ISearchIndex index, string indexName, [ReplaceSearchProvider] SearchProvider searchProvider, [Content] Item renderingItem)
    {
      //arrange
      indexedItems.AddRange(contentItems);
      indexedItems.Add(brokenItem);

      var results = GetResults(indexedItems);

      InitIndexes(index, searchProvider, results);
      var renderingModel = new QueryableDatasourceRenderingModel() { Rendering = new Rendering() { DataSource = "notEmpty" } };

      //act
      var items = renderingModel.Items.ToArray();


      //assert
      items.Count().Should().Be(contentItems.Length);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_ItemTemplateSet_FiltersByTemplateId(Db db, [Content] DbTemplate templateItem,  [Content] DbItem[] contentItems, ISearchIndex index, [ReplaceSearchProvider] SearchProvider searchProvider, string indexName, [Content] Item renderingItem)
    {
      //arrange
      var dbItem = new DbItem("templated", ID.NewID, templateItem.ID);
      db.Add(dbItem);
      var dbItems = contentItems.ToList();
      dbItems.Add(dbItem);
      var results = GetResults(dbItems);

      InitIndexes(index, searchProvider,  results);

      
      var renderingModel = new QueryableDatasourceRenderingModel() {Rendering = new Rendering() {DataSource = "notEmpty"} };
      renderingModel.DatasourceTemplate = db.GetItem(templateItem.ID);

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(1);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_IndexEmpty_ReturnsEmptyCollection(List<DbItem> indexedItems, ISearchIndex index, string indexName, [Frozen] SearchProvider searchProvider, Switcher<SearchProvider> searchProviderSwitcher, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      InitIndexes(index, searchProvider, new List<SearchResultItem>().AsQueryable());
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        DatasourceString = "notEmpty"
      };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(0);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_IndexHaveNonexistentItems_ReturnsExistentItems([Content] DbItem[] contentItems, DbItem brokenItem,
      List<DbItem> indexedItems, ISearchIndex index, string indexName,
      [Frozen] SearchProvider searchProvider, Switcher<SearchProvider> searchProviderSwitcher,
      [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      indexedItems.AddRange(contentItems);
      indexedItems.Add(brokenItem);
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      var results = GetResults(indexedItems);

      InitIndexes(index, searchProvider, results);
      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        DatasourceString = "notEmpty"
      };

      //act
      var items = renderingModel.Items.ToArray();


      //assert
      items.Count().Should().Be(contentItems.Length);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }
    public void Items_ItemTemplateSet_FiltersByTemplateId(Db db, [Content] DbTemplate templateItem, [Content] DbItem[] contentItems, ISearchIndex index, [Frozen] SearchProvider searchProvider, Switcher<SearchProvider> searchProviderSwitcher, string indexName, [Content] Item renderingItem, IRenderingPropertiesRepository renderingPropertiesRepository)
    {
      //arrange
      var dbItem = new DbItem("templated", ID.NewID, templateItem.ID);
      db.Add(dbItem);
      var dbItems = contentItems.ToList();
      dbItems.Add(dbItem);
      var results = GetResults(dbItems);
      renderingPropertiesRepository.Get<QueryableDatasourceRenderingSettings>()
        .Returns(new QueryableDatasourceRenderingSettings
        {
          SearchResultsLimit = 10
        });

      InitIndexes(index, searchProvider, results);


      var renderingModel = new QueryableDatasourceRenderingModel(renderingPropertiesRepository)
      {
        Rendering = new Rendering(),
        DatasourceString = "notEmpty",
        DatasourceTemplate = db.GetItem(templateItem.ID)
      };

      //act
      var items = renderingModel.Items;

      //assert
      items.Count().Should().Be(1);
      index.CreateSearchContext().ReceivedWithAnyArgs(1);
    }