/// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumreable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable <SitecoreItem> Search(this Item itm, out int hitCount, string relatedIds = "", string indexName = "itembuckets_buckets", string text = "", string templates = "", string location = "", string sortDirection = "", string language = "en", string id = "", string sortField = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20, int pageNumber = 0)
        {
            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                {
                    ItemName      = itemName,
                    FullTextQuery = text,
                    RelatedIds    = relatedIds,
                    TemplateIds   = templates,
                    LocationIds   = location.IsEmpty() ? itm.ID.ToString() : location,
                    Language      = language,
                    ID            = id,
                    SortDirection = sortDirection,
                    SortByField   = sortField,
                    PageSize      = numberOfItemsToReturn,
                    PageNumber    = pageNumber,
                    Ranges        = SearchHelper.GetDateRefinements(startDate, endDate)
                };
                var keyValuePair = searcher.GetItems(dateSearchParam);

                hitCount = keyValuePair.Key;
                return(keyValuePair.Value);
            }
        }
        /// <summary>
        /// An extension of Item that allows you to launch a Search from an item
        /// </summary>
        /// <returns>List of Results of Type IEnumerable List of SitecoreItem (which implements IItem)</returns>
        /// <param name="startLocationItem">The start location of the search</param>
        /// <param name="hitCount">This will output the hitCount of the search</param>
        /// <param name="currentSearchString">The raw JSON Parse query</param>
        /// <param name="indexName">Force query to run on a particular index</param>
        /// <param name="sortField">Sort query by field (must be in index)</param>
        /// <param name="sortDirection">Sort in either "asc" or "desc"</param>
        /// <example>BucketManager.Search(Sitecore.Context.Item, SearchModel)</example>
        public static IEnumerable <SitecoreItem> Search(Item startLocationItem, out int hitCount, List <SearchStringModel> currentSearchString, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "")
        {
            var refinements        = new SafeDictionary <string>();
            var searchStringModels = SearchHelper.GetTags(currentSearchString);

            if (searchStringModels.Count > 0)
            {
                foreach (var ss in searchStringModels)
                {
                    var query = ss.Value;
                    if (query.Contains("tagid="))
                    {
                        query = query.Split('|')[1].Replace("tagid=", string.Empty);
                    }
                    var db = Context.ContentDatabase ?? Context.Database;
                    refinements.Add("_tags", db.GetItem(query).ID.ToString());
                }
            }
            using (var searcher = new IndexSearcher(indexName))
            {
                var keyValuePair = searcher.GetItems(new DateRangeSearchParam {
                    FullTextQuery = SearchHelper.GetText(currentSearchString), RelatedIds = string.Empty, SortDirection = sortDirection, TemplateIds = SearchHelper.GetTemplates(currentSearchString), LocationIds = startLocationItem.ID.ToString(), SortByField = sortField, Refinements = refinements
                });
                hitCount = keyValuePair.Key;
                return(keyValuePair.Value);
            }
        }
Пример #3
0
        /// <summary>
        /// Get Items to be loaded when the Control is loaded on the item
        /// </summary>
        /// <param name="current">
        /// The current.
        /// </param>
        /// <returns>
        /// Array of Item
        /// </returns>
        protected override Item[] GetItems(Item current)
        {
            Assert.ArgumentNotNull(current, "current");
            var values      = StringUtil.GetNameValues(Source, '=', '&');
            var refinements = new SafeDictionary <string>();

            if (values["FieldsFilter"] != null)
            {
                var splittedFields = StringUtil.GetNameValues(values["FieldsFilter"], ':', ',');
                foreach (string key in splittedFields.Keys)
                {
                    refinements.Add(key, splittedFields[key]);
                }
            }

            var locationFilter = values["StartSearchLocation"];

            locationFilter = MakeFilterQuerable(locationFilter);

            var templateFilter = values["TemplateFilter"];

            templateFilter = MakeTemplateFilterQuerable(templateFilter);

            var pageSize    = values["PageSize"];
            var searchParam = new DateRangeSearchParam
            {
                Refinements   = refinements,
                LocationIds   = locationFilter.IsNullOrEmpty() ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).GetParentBucketItemOrRootOrSelf().ID.ToString() : locationFilter,
                TemplateIds   = templateFilter,
                FullTextQuery = values["FullTextQuery"],
                Language      = values["Language"],
                PageSize      = pageSize.IsEmpty() ? 10 : int.Parse(pageSize),
                PageNumber    = this.pageNumber,
                SortByField   = values["SortField"],
                SortDirection = values["SortDirection"]
            };

            this.filter = "&location=" + (locationFilter.IsNullOrEmpty() ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).GetParentBucketItemOrRootOrSelf().ID.ToString() : locationFilter) +
                          "&filterText=" + values["FullTextQuery"] +
                          "&language=" + values["Language"] +
                          "&pageSize=" + (pageSize.IsEmpty() ? 10 : int.Parse(pageSize)) +
                          "&sort=" + values["SortField"];

            if (values["TemplateFilter"].IsNotNull())
            {
                this.filter += "&template=" + templateFilter;
            }

            using (var searcher = new IndexSearcher(Constants.Index.Name))
            {
                var keyValuePair = searcher.GetItems(searchParam);
                var items        = keyValuePair.Value;
                this.pageNumber = keyValuePair.Key / searchParam.PageSize;
                if (this.pageNumber <= 0)
                {
                    this.pageNumber = 1;
                }
                return(items.Select(sitecoreItem => sitecoreItem.GetItem()).Where(i => i != null).ToArray());
            }
        }
 /// <summary>
 /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
 /// </summary>
 /// <returns>IEnumreable List of Results that have been typed to a smaller version of the Item Object</returns>
 public static IEnumerable <SitecoreItem> Search(this Item itm, SearchParam queryParser, out int hitCount, string indexName = "itembuckets_buckets")
 {
     using (var searcher = new IndexSearcher(indexName))
     {
         var keyValuePair = searcher.GetItems(queryParser);
         hitCount = keyValuePair.Key;
         return(keyValuePair.Value);
     }
 }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumreable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable <SitecoreItem> Search(this Item itm, out int hitCount, string relatedIds = "", string indexName = "itembuckets_buckets", string text = "", string templates = "", string location = "", string sortDirection = "", string language = "en", string id = "", string sortField = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20, int pageNumber = 0)
        {
            var culture      = CultureInfo.CreateSpecificCulture("en-US");
            var startDateOut = new DateTime();
            var endDateOut   = new DateTime();
            var startFlag    = true;
            var endFlag      = true;

            if (!DateTime.TryParse(startDate, culture, DateTimeStyles.None, out startDateOut))
            {
                startDateOut = DateTime.Now;
                startFlag    = false;
            }

            if (!DateTime.TryParse(endDate, culture, DateTimeStyles.None, out endDateOut))
            {
                endDateOut = DateTime.Now.AddDays(1);
                endFlag    = false;
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                {
                    ItemName      = itemName,
                    FullTextQuery = text,
                    RelatedIds    = relatedIds,
                    TemplateIds   = templates,
                    LocationIds   = location.IsEmpty() ? itm.ID.ToString() : location,
                    Language      = language,
                    ID            = id,
                    SortDirection = sortDirection,
                    SortByField   = sortField,
                    PageSize      = numberOfItemsToReturn,
                    PageNumber    = pageNumber
                };
                var keyValuePair = searcher.GetItems(dateSearchParam);

                if (startFlag || endFlag)
                {
                    dateSearchParam.Ranges = new List <DateRangeSearchParam.DateRangeField>
                    {
                        new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDateOut, endDateOut)
                        {
                            InclusiveStart = true, InclusiveEnd = true
                        }
                    };
                }

                hitCount = keyValuePair.Key;
                return(keyValuePair.Value);
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <returns>IEnumerable List of Results that have been typed to a smaller version of the Item Object</returns>
        public static IEnumerable <SitecoreItem> Search(this Item itm, SafeDictionary <string> refinements, out int hitCount,
                                                        string relatedIds         = "",
                                                        string indexName          = "itembuckets_buckets",
                                                        string text               = "",
                                                        string templates          = "",
                                                        string location           = "",
                                                        string language           = "en",
                                                        string id                 = "",
                                                        string sortField          = "",
                                                        string itemName           = "",
                                                        string startDate          = "",
                                                        int pageNumber            = 0,
                                                        string endDate            = "",
                                                        string sortDirection      = "",
                                                        int numberOfItemsToReturn = 20,
                                                        object[] parameters       = null)
        {
            if (itm.IsNull())
            {
                Log.Warn("You are trying to run an Item Extension on an item that is null", "");
                hitCount = 0;
                return(new List <SitecoreItem>());
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var dateSearchParam = new DateRangeSearchParam
                {
                    ItemName      = itemName,
                    FullTextQuery = text,
                    RelatedIds    = relatedIds,
                    TemplateIds   = templates,
                    LocationIds   = location.IsEmpty() ? itm.ID.ToString() : location,
                    Language      = language,
                    SortDirection = sortDirection,
                    Refinements   = refinements,
                    ID            = id,
                    SortByField   = sortField,
                    PageSize      = numberOfItemsToReturn,
                    PageNumber    = pageNumber,
                    Ranges        = SearchHelper.GetDateRefinements(startDate, endDate)
                };
                var keyValuePair = searcher.GetItems(dateSearchParam);
                hitCount = keyValuePair.Key;
                return(keyValuePair.Value);
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <param name="itm">
        /// The itm.
        /// </param>
        /// <param name="currentSearchString">
        /// The current Search String.
        /// </param>
        /// <param name="hitCount">
        /// The hit Count.
        /// </param>
        /// <param name="indexName">
        /// The index Name.
        /// </param>
        /// <param name="sortField">
        /// The sort Field.
        /// </param>
        /// <param name="sortDirection">
        /// The sort Direction.
        /// </param>
        /// <param name="pageSize">
        /// The page Size.
        /// </param>
        /// <param name="pageNumber">
        /// The page Number.
        /// </param>
        /// <param name="parameters">
        /// The parameters.
        /// </param>
        /// <returns>
        /// IEnumreable List of Results that have been typed to a smaller version of the Item Object
        /// </returns>
        public static IEnumerable <SitecoreItem> FullSearch(this Item itm, List <SearchStringModel> currentSearchString, out int hitCount, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "", int pageSize = 0, int pageNumber = 0, object[] parameters = null)
        {
            using (var searcher = new IndexSearcher(indexName))
            {
                var rangeSearch        = SearchHelper.GetSearchSettings(currentSearchString, LocationFilter);
                var locationIdFromItem = itm != null?itm.ID.ToString() : string.Empty;

                rangeSearch.SortDirection = sortDirection;
                rangeSearch.SortByField   = sortField;
                rangeSearch.PageNumber    = pageNumber;
                rangeSearch.PageSize      = pageSize;
                rangeSearch.LocationIds   = rangeSearch.LocationIds == string.Empty ? locationIdFromItem : rangeSearch.LocationIds;
                var returnResult = searcher.GetItems(rangeSearch);
                hitCount = returnResult.Key;
                return(returnResult.Value);
            }
        }
        /// <summary>
        /// An extension of Item that allows you to launch a Search from an item
        /// </summary>
        /// <returns>List of Results of Type IEnumerable List of SitecoreItem (which implements IItem)</returns>
        /// <param name="startLocationItem">The start location of the search</param>
        /// <param name="hitCount">This will output the hitCount of the search</param>
        /// <param name="currentSearchString">The raw JSON Parse query</param>
        /// <param name="indexName">Force query to run on a particular index</param>
        /// <param name="sortField">Sort query by field (must be in index)</param>
        /// <param name="sortDirection">Sort in either "asc" or "desc"</param>
        /// <example>BucketManager.Search(Sitecore.Context.Item, SearchModel)</example>
        public static IEnumerable <SitecoreItem> Search(Item startLocationItem, out int hitCount, List <SearchStringModel> currentSearchString, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "")
        {
            //var refinements = new SafeDictionary<string>();
            //refinements = SearchHelper.GetTagRefinements(currentSearchString);
            var locationIdFromItem = startLocationItem != null?startLocationItem.ID.ToString() : string.Empty;

            var rangeSearch = SearchHelper.GetSearchSettings(currentSearchString, locationIdFromItem);

            using (var searcher = new IndexSearcher(indexName))
            {
                // var keyValuePair = searcher.GetItems(new DateRangeSearchParam { FullTextQuery = SearchHelper.GetText(currentSearchString), RelatedIds = string.Empty, SortDirection = sortDirection, TemplateIds = SearchHelper.GetTemplates(currentSearchString), LocationIds = startLocationItem.ID.ToString(), SortByField = sortField, Refinements = refinements});
                //hitCount = keyValuePair.Key;
                //return keyValuePair.Value;
                var returnResult = searcher.GetItems(rangeSearch);
                hitCount = returnResult.Key;
                return(returnResult.Value);
            }
        }
        /// <summary>
        /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String
        /// </summary>
        /// <param name="itm">
        /// The itm.
        /// </param>
        /// <param name="currentSearchString">
        /// The current Search String.
        /// </param>
        /// <param name="hitCount">
        /// The hit Count.
        /// </param>
        /// <param name="indexName">
        /// The index Name.
        /// </param>
        /// <param name="sortField">
        /// The sort Field.
        /// </param>
        /// <param name="sortDirection">
        /// The sort Direction.
        /// </param>
        /// <param name="pageSize">
        /// The page Size.
        /// </param>
        /// <param name="pageNumber">
        /// The page Number.
        /// </param>
        /// <param name="parameters">
        /// The parameters.
        /// </param>
        /// <returns>
        /// IEnumreable List of Results that have been typed to a smaller version of the Item Object
        /// </returns>
        public static IEnumerable <SitecoreItem> FullSearch(this Item itm, List <SearchStringModel> currentSearchString, out int hitCount, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "", int pageSize = 0, int pageNumber = 0, object[] parameters = null)
        {
            var startDate          = DateTime.Now;
            var endDate            = DateTime.Now.AddDays(1);
            var locationSearch     = LocationFilter;
            var refinements        = new SafeDictionary <string>();
            var searchStringModels = SearchHelper.GetTags(currentSearchString);

            if (searchStringModels.Count > 0)
            {
                foreach (var ss in searchStringModels)
                {
                    var query = ss.Value;
                    if (query.Contains("tagid="))
                    {
                        query = query.Split('|')[1].Replace("tagid=", string.Empty);
                    }
                    var db = Context.ContentDatabase ?? Context.Database;
                    refinements.Add("_tags", db.GetItem(query).ID.ToString());
                }
            }

            var author = SearchHelper.GetAuthor(currentSearchString);


            var languages = SearchHelper.GetLanguages(currentSearchString);

            if (languages.Length > 0)
            {
                refinements.Add("_language", languages);
            }

            var references = SearchHelper.GetReferences(currentSearchString);

            var custom = SearchHelper.GetCustom(currentSearchString);

            if (custom.Length > 0)
            {
                var customSearch = custom.Split('|');
                if (customSearch.Length > 0)
                {
                    try
                    {
                        refinements.Add(customSearch[0], customSearch[1]);
                    }
                    catch (Exception exc)
                    {
                        Log.Error("Could not parse the custom search query", exc);
                    }
                }
            }

            var search = SearchHelper.GetField(currentSearchString);

            if (search.Length > 0)
            {
                var customSearch = search;
                refinements.Add(customSearch, SearchHelper.GetText(currentSearchString));
            }

            var fileTypes = SearchHelper.GetFileTypes(currentSearchString);

            if (fileTypes.Length > 0)
            {
                refinements.Add("extension", SearchHelper.GetFileTypes(currentSearchString));
            }

            var s = SearchHelper.GetSite(currentSearchString);

            if (s.Length > 0)
            {
                SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name);
                var         db          = Context.ContentDatabase ?? Context.Database;
                var         startItemId = db.GetItem(siteContext.StartPath);
                locationSearch = startItemId.ID.ToString();
            }

            var culture   = CultureInfo.CreateSpecificCulture("en-US");
            var startFlag = true;
            var endFlag   = true;

            if (SearchHelper.GetStartDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetStartDate(currentSearchString), culture, DateTimeStyles.None, out startDate))
                {
                    startDate = DateTime.Now;
                }

                startFlag = false;
            }

            if (SearchHelper.GetEndDate(currentSearchString).Any())
            {
                if (!DateTime.TryParse(SearchHelper.GetEndDate(currentSearchString), culture, DateTimeStyles.None, out endDate))
                {
                    endDate = DateTime.Now.AddDays(1);
                }

                endFlag = false;
            }

            using (var searcher = new IndexSearcher(indexName))
            {
                var location           = SearchHelper.GetLocation(currentSearchString, locationSearch);
                var locationIdFromItem = itm != null?itm.ID.ToString() : string.Empty;

                var rangeSearch = new DateRangeSearchParam
                {
                    ID = SearchHelper.GetID(currentSearchString).IsEmpty() ? SearchHelper.GetRecent(currentSearchString) : SearchHelper.GetID(currentSearchString),
                    ShowAllVersions = false,
                    FullTextQuery   = SearchHelper.GetText(currentSearchString),
                    Refinements     = refinements,
                    RelatedIds      = references.Any() ? references : string.Empty,
                    SortDirection   = sortDirection,
                    TemplateIds     = SearchHelper.GetTemplates(currentSearchString),
                    LocationIds     = location == string.Empty ? locationIdFromItem : location,
                    Language        = languages,
                    SortByField     = sortField,
                    PageNumber      = pageNumber,
                    PageSize        = pageSize,
                    Author          = author == string.Empty ? string.Empty : author,
                };

                if (!startFlag || !endFlag)
                {
                    rangeSearch.Ranges = new List <DateRangeSearchParam.DateRangeField>
                    {
                        new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate)
                        {
                            InclusiveStart = true, InclusiveEnd = true
                        }
                    };
                }

                var returnResult = searcher.GetItems(rangeSearch);
                hitCount = returnResult.Key;
                return(returnResult.Value);
            }
        }
        /// <summary>
        /// An extension of Item that allows you to launch a Search from an item
        /// </summary>
        /// <returns>List of Results of Type IEnumerable List of SitecoreItem (which implements IItem)</returns>
        /// <param name="startLocationItem">The start location of the search</param>
        /// <param name="refinements">A collection of refinements to the query</param>
        /// <param name="hitCount">This will output the hitCount of the search</param>
        /// <param name="relatedIds">Pipe delimited string of Id to query by Links to and from items</param>
        /// <param name="indexName">Force query to run on a particular index</param>
        /// <param name="text">The raw text query</param>
        /// <param name="templates">Pipe delimited string of Id of Templates</param>
        /// <param name="location">Override the location of the search with an Id</param>
        /// <param name="language">Query by the two letter ISO country code</param>
        /// <param name="id">Query by ID</param>
        /// <param name="sortField">Sort query by field (must be in index)</param>
        /// <param name="sortDirection">Sort in either "asc" or "desc"</param>
        /// <param name="itemName">Query by item name</param>
        /// <param name="startDate">mm/dd/yyyy format of start date</param>
        /// <param name="endDate">mm/dd/yyyy format of end date</param>
        /// <param name="numberOfItemsToReturn">0-XXXXXX (The bigger this number is the less performant it will be)</param>
        /// <example>BucketManager.Search(Sitecore.Context.Item, text: "Tim", templates: "TemplateGUID")</example>
        /// <example>BucketManager.Search(Sitecore.Context.Item, text: "Tim", relatedIds: "ItemGUID", sortField: "_name")</example>
        public static IEnumerable <SitecoreItem> Search(Item startLocationItem, SafeDictionary <string> refinements, out int hitCount, string relatedIds = "", string indexName = "itembuckets_buckets", string text = "", string templates = "", string location = "", string language = "en", string id = "", string sortField = "", string sortDirection = "", string itemName = "", string startDate = "", string endDate = "", int numberOfItemsToReturn = 20)
        {
            using (var searcher = new IndexSearcher(indexName))
            {
                var culture      = CultureInfo.CreateSpecificCulture("en-US");
                var startDateOut = DateTime.Now;
                var endDateOut   = DateTime.Now.AddDays(1);
                var startFlag    = true;
                var endFlag      = true;
                if (!DateTime.TryParse(startDate, culture, DateTimeStyles.None, out startDateOut))
                {
                    startDateOut = DateTime.Now;
                    startFlag    = false;
                }

                if (!DateTime.TryParse(endDate, culture, DateTimeStyles.None, out endDateOut))
                {
                    endDateOut = DateTime.Now.AddDays(1);
                    endFlag    = false;
                }

                if (startLocationItem.IsNull())
                {
                    Log.Warn("You are trying to run an Search on an item that has a start location of null", null);
                    hitCount = 0;
                    return(new List <SitecoreItem>());
                }

                var dateSearchParam = new DateRangeSearchParam
                {
                    ItemName      = itemName,
                    FullTextQuery = text,
                    RelatedIds    = relatedIds,
                    TemplateIds   = templates,
                    LocationIds   = startLocationItem.ID.ToString(),
                    Language      = language,
                    SortDirection = sortDirection,
                    Refinements   = refinements,
                    ID            = id,
                    SortByField   = sortField,
                    PageSize      = numberOfItemsToReturn
                };

                if (startFlag || endFlag)
                {
                    dateSearchParam.Ranges = new List <DateRangeSearchParam.DateRangeField>
                    {
                        new DateRangeSearchParam.DateRangeField(
                            SearchFieldIDs.CreatedDate,
                            startDateOut,
                            endDateOut)
                        {
                            InclusiveStart = true, InclusiveEnd = true
                        }
                    };
                }

                var keyValuePair = searcher.GetItems(dateSearchParam);
                hitCount = keyValuePair.Key;
                return(keyValuePair.Value);
            }
        }