Ejemplo n.º 1
0
        /// <summary>
        /// Using CMS search API fills dataset with raw data.
        /// </summary>
        /// <param name="query">Text to search</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="numberOfResults">Total number of search results</param>
        private void SearchInternal(string query, int pageIndex, int pageSize, out int numberOfResults)
        {
            var documentCondition = new DocumentSearchCondition(null, mCultureName, mDefaultCulture, combineWithDefaultCulture: false);
            var condition         = new SearchCondition(documentCondition: documentCondition);
            var searchExpression  = SearchSyntaxHelper.CombineSearchCondition(query, condition);

            var parameters = new SearchParameters
            {
                SearchFor                 = searchExpression,
                Path                      = "/%",
                ClassNames                = null,
                CurrentCulture            = mCultureName,
                DefaultCulture            = mDefaultCulture,
                CombineWithDefaultCulture = false,
                CheckPermissions          = false,
                SearchInAttachments       = false,
                User                      = MembershipContext.AuthenticatedUser,
                SearchIndexes             = mSearchIndexName,
                StartingPosition          = pageIndex * pageSize,
                NumberOfResults           = 0,
                NumberOfProcessedResults  = 100,
                DisplayResults            = pageSize
            };

            // Search and save results
            mRawResults     = SearchHelper.Search(parameters);
            numberOfResults = parameters.NumberOfResults;
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Adds item to list control.
    /// </summary>
    /// <param name="row">Field row</param>
    /// <param name="value">Value</param>
    /// <param name="displayName">Display name</param>
    private void AddItem(string row, string value, string displayName)
    {
        // Create new item

        if (FilterMode != SearchFilterModeEnum.DropdownList)
        {
            displayName = HTMLHelper.HTMLEncode(displayName);
        }

        ListItem item = FilterIsConditional ? new ListItem(displayName, SearchSyntaxHelper.GetFilterCondition(row, value) ?? "") : new ListItem(displayName, row);

        switch (FilterMode)
        {
        case SearchFilterModeEnum.Checkbox:
            // Add item to checkbox list
            chklstFilter.Items.Add(item);
            break;

        case SearchFilterModeEnum.RadioButton:
            // Add item to radio button list
            radlstFilter.Items.Add(item);
            break;

        default:
            // Add item to dropdown list
            drpFilter.Items.Add(item);
            break;
        }
    }
Ejemplo n.º 3
0
        /// <summary>
        /// Performs search and populates the returned raw data into the internal search service dataset. Logs activity.
        /// </summary>
        private void PerformSearch(SearchOptions options)
        {
            var documentCondition = new DocumentSearchCondition(null, options.CultureName, options.DefaultCultureCode, options.CombineWithDefaultCulture);
            var condition         = new SearchCondition(documentCondition: documentCondition);
            var searchExpression  = SearchSyntaxHelper.CombineSearchCondition(options.Query, condition);

            var parameters = new SearchParameters
            {
                SearchFor                 = searchExpression,
                Path                      = "/%",
                ClassNames                = null,
                CurrentCulture            = options.CultureName,
                DefaultCulture            = options.DefaultCultureCode,
                CombineWithDefaultCulture = options.CombineWithDefaultCulture,
                CheckPermissions          = false,
                SearchInAttachments       = false,
                User                      = MembershipContext.AuthenticatedUser,
                SearchIndexes             = options.SearchIndexNames.Join(";"),
                StartingPosition          = (options.PageNumber - 1) * options.PageSize,
                NumberOfResults           = 0,
                NumberOfProcessedResults  = 100,
                DisplayResults            = options.PageSize
            };

            // Search and save results
            rawResults           = SearchInternal(parameters);
            totalNumberOfResults = parameters.NumberOfResults;
        }
Ejemplo n.º 4
0
    /// <summary>
    /// Performs search.
    /// </summary>
    private SearchResult PredictiveSearch(string searchText)
    {
        // Prepare search text
        var docCondition = new DocumentSearchCondition(PredictiveSearchDocumentTypes, PredictiveSearchCultureCode, CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName), PredictiveSearchCombineWithDefaultCulture);
        var condition    = new SearchCondition(PredictiveSearchCondition, PredictiveSearchMode, PredictiveSearchOptions, docCondition);

        string searchCondition = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

        // Prepare parameters
        SearchParameters parameters = new SearchParameters()
        {
            SearchFor                 = searchCondition,
            SearchSort                = PredictiveSearchSort,
            Path                      = PredictiveSearchPath,
            ClassNames                = PredictiveSearchDocumentTypes,
            CurrentCulture            = PredictiveSearchCultureCode,
            DefaultCulture            = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName),
            CombineWithDefaultCulture = PredictiveSearchCombineWithDefaultCulture,
            CheckPermissions          = PredictiveSearchCheckPermissions,
            SearchInAttachments       = false,
            User                      = MembershipContext.AuthenticatedUser,
            SearchIndexes             = PredictiveSearchIndexes,
            StartingPosition          = 0,
            DisplayResults            = PredictiveSearchMaxResults,
            NumberOfProcessedResults  = 100 > PredictiveSearchMaxResults ? PredictiveSearchMaxResults : 100,
            NumberOfResults           = 0,
            AttachmentWhere           = null,
            AttachmentOrderBy         = null,
            BlockFieldOnlySearch      = PredictiveSearchBlockFieldOnlySearch,
        };

        var results = SearchHelper.Search(parameters);

        return(results);
    }
Ejemplo n.º 5
0
        public IEnumerable <T> GetItems(IEnumerable <Guid> taxonomies, out int totalResults, int skip = 0, int take = Int32.MaxValue, string searchSort = "", string searchRootAliasPath = "/")
        {
            var taxonomyCondition = string.Empty;

            var taxonomiesList = taxonomies.ToList();

            if (taxonomiesList.Count > 0)
            {
                foreach (var type in TaxonomyRepository.GetAllTaxonomyTypes())
                {
                    var targetItems = type.TaxonomyItems.Where(x => taxonomiesList.Contains(x.NodeGUID)).ToList();
                    if (targetItems.Count > 0)
                    {
                        taxonomyCondition = SearchSyntaxHelper.AddSearchCondition(taxonomyCondition,
                                                                                  SearchSyntaxHelper.GetRequiredCondition(SearchSyntaxHelper.GetFilterCondition(
                                                                                                                              nameof(IBasePage.Taxonomy),
                                                                                                                              targetItems.Select(x => x.NodeGUID.ToString("D")).Join(" OR "))));
                    }
                }
            }

            var condition = SearchSyntaxHelper.CombineSearchCondition(string.Empty,
                                                                      new SearchCondition
            {
                DocumentCondition = new DocumentSearchCondition
                {
                    ClassNames = new T().ClassName, Culture = Constants.Cultures.Default.Name
                },
                ExtraConditions = taxonomyCondition
            });

            var parameters = new SearchParameters
            {
                SearchFor = condition,
                Path      = $"{searchRootAliasPath}%",
                CombineWithDefaultCulture = false,
                CheckPermissions          = false,
                SearchInAttachments       = false,
                User                     = MembershipContext.AuthenticatedUser,
                SearchIndexes            = Settings.Taxonomy.SearchIndex,
                StartingPosition         = skip,
                NumberOfProcessedResults = ((Int64)skip + (Int64)take) >= (Int64)Int32.MaxValue ? Int32.MaxValue : skip + take,
                DisplayResults           = take,
                SearchSort               = searchSort
            };

            var searchResults = SearchHelper.Search(parameters);

            totalResults = searchResults.Parameters.NumberOfResults;

            return(searchResults.Items.Select(x => x.Data).OfType <T>());
        }
Ejemplo n.º 6
0
        public IEnumerable <DataRow> Search(string phrase, string indexName, string path, int results, bool checkPermissions)
        {
            var index = SearchIndexInfoProvider.GetSearchIndexInfo(indexName);

            if (index == null)
            {
                yield break;
            }

            var searchText = string.Format("+({0})", phrase);
            var culture    = LocalizationContext.CurrentCulture.CultureCode;

            var documentSearchCondition = new DocumentSearchCondition {
                Culture = culture
            };
            var condition = new SearchCondition(documentCondition: documentSearchCondition);

            searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

            SearchParameters parameters = new SearchParameters()
            {
                SearchFor                 = searchText,
                SearchSort                = "##SCORE##",
                Path                      = path,
                CurrentCulture            = culture,
                DefaultCulture            = null,
                CombineWithDefaultCulture = false,
                CheckPermissions          = checkPermissions,
                SearchInAttachments       = false,
                User                      = (UserInfo)MembershipContext.AuthenticatedUser,
                SearchIndexes             = index.IndexName,
                StartingPosition          = 0,
                DisplayResults            = results,
                NumberOfProcessedResults  = 5000,
                NumberOfResults           = results,
                AttachmentWhere           = String.Empty,
                AttachmentOrderBy         = String.Empty,
            };

            var dataset = CacheHelper.Cache <DataSet>(() => SearchHelper.Search(parameters), new CacheSettings(1, $"search|{indexName}|{path}|{phrase}|{results}|{checkPermissions}|{culture}"));

            if (dataset != null)
            {
                foreach (DataTable table in dataset.Tables)
                {
                    foreach (DataRow dr in table.Rows)
                    {
                        yield return(dr);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public void Search_CheckParameters_Query(string searchQuery, string culture, string defaultCulture, bool combineWithDefaultCulture)
        {
            var parameters = Search(
                query: searchQuery,
                culture: culture,
                defaultCulture: defaultCulture,
                combineWithDefaultCulture: combineWithDefaultCulture
                )
                             .Parameters;

            var documentCondition = new DocumentSearchCondition(null, culture, defaultCulture, combineWithDefaultCulture);
            var condition         = new SearchCondition(documentCondition: documentCondition);
            var searchExpression  = SearchSyntaxHelper.CombineSearchCondition(searchQuery, condition);

            CMSAssert.All(
                () => Assert.AreEqual(parameters.SearchFor, searchExpression),
                () => Assert.AreEqual(parameters.CurrentCulture, culture),
                () => Assert.AreEqual(parameters.DefaultCulture, defaultCulture),
                () => Assert.AreEqual(parameters.CombineWithDefaultCulture, combineWithDefaultCulture)
                );
        }
Ejemplo n.º 8
0
    /// <summary>
    /// Gets selected items.
    /// </summary>
    /// <param name="control">Control</param>
    /// <param name="ids">Id's of selected values separated by semicolon</param>
    private string GetSelectedItems(ListControl control, out string ids)
    {
        ids = "";
        string selected = "";

        // loop through all items
        for (int i = 0; i != control.Items.Count; i++)
        {
            if (control.Items[i].Selected)
            {
                selected = SearchSyntaxHelper.AddSearchCondition(selected, control.Items[i].Value);
                ids     += ValidationHelper.GetString(i, "") + ";";
            }
        }

        if (String.IsNullOrEmpty(selected) && (control.SelectedItem != null))
        {
            selected = control.SelectedItem.Value;
            ids      = control.SelectedIndex.ToString();
        }

        return(selected);
    }
Ejemplo n.º 9
0
    /// <summary>
    /// Page load.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!RequestHelper.IsPostBack() && (FilterMode != SearchFilterModeEnum.TextBox))
            {
                // If query name filled - execute it
                if (!string.IsNullOrEmpty(FilterQueryName))
                {
                    // Execute query
                    DataSet ds = ConnectionHelper.ExecuteQuery(FilterQueryName, null, FilterWhere, FilterOrderBy);
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        // Check that dataset has at least 3 columns
                        if (ds.Tables[0].Columns.Count < 3)
                        {
                            lblError.ResourceString = "srch.filter.fewcolumns";
                            lblError.Visible        = true;
                            return;
                        }

                        // Loop through all rows
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            AddItem(dr[0].ToString(), dr[1].ToString(), ResHelper.LocalizeString(dr[2].ToString()));
                        }
                    }
                }
                // Else if values are filled - parse them
                else if (!string.IsNullOrEmpty(FilterValues))
                {
                    // Split values into rows
                    string[] rows = FilterValues.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                    // Loop through each row
                    foreach (string row in rows)
                    {
                        string trimmedRow = row.Trim().TrimEnd('\r');
                        if (!string.IsNullOrEmpty(trimmedRow))
                        {
                            string[] values = trimmedRow.Split(';');
                            if (values.Length == 3)
                            {
                                AddItem(values[0], values[1], values[2]);
                            }
                            else
                            {
                                lblError.ResourceString = "srch.filter.badformat";
                                lblError.Visible        = true;
                                return;
                            }
                        }
                    }
                }
            }

            // Get webpart ID
            string webpartID = ValidationHelper.GetString(GetValue("WebpartControlID"), ID);

            // Try to get selected values from query string - but only if is not postback
            if (!RequestHelper.IsPostBack())
            {
                string selectedItems = QueryHelper.GetString(webpartID, "");

                // If none of items are selected - try to get default values
                if (string.IsNullOrEmpty(selectedItems))
                {
                    selectedItems = DefaultSelectedIndex;
                }

                if (!string.IsNullOrEmpty(selectedItems))
                {
                    string[] splittedItems = selectedItems.Split(';');
                    foreach (string item in splittedItems)
                    {
                        switch (FilterMode)
                        {
                        case SearchFilterModeEnum.Checkbox:
                            SelectItem(item, chklstFilter);
                            break;

                        case SearchFilterModeEnum.RadioButton:
                            SelectItem(item, radlstFilter);
                            break;

                        case SearchFilterModeEnum.DropdownList:
                            SelectItem(item, drpFilter);
                            break;

                        default:
                            txtFilter.Text = item;
                            break;
                        }
                    }
                }
            }

            string applyFilter = "";
            string ids;

            // Set up controls
            switch (FilterMode)
            {
            // Set text box
            case SearchFilterModeEnum.TextBox:
            {
                txtFilter.Visible           = true;
                txtFilter.WatermarkCssClass = WatermarkCssClass;
                txtFilter.WatermarkText     = WatermarkText;
                txtFilter.AutoPostBack      = FilterAutoPostback;

                AppendClientHandlers(txtFilter);

                if (!String.IsNullOrEmpty(DefaultSelectedIndex) && String.IsNullOrEmpty(txtFilter.Text) && !URLHelper.IsPostback())
                {
                    txtFilter.Text = DefaultSelectedIndex;
                }

                // Apply filter only of textbox contains something
                if (!String.IsNullOrEmpty(txtFilter.Text))
                {
                    // Prepare right condition when filter values aren't empty
                    if (!String.IsNullOrEmpty(FilterValues))
                    {
                        string[] rows     = FilterValues.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        var      keyWords = SearchSyntaxHelper.ProcessSearchKeywords(txtFilter.Text, SearchOptionsEnum.NoneSearch);

                        // Loop through each row
                        foreach (string row in rows)
                        {
                            string trimmedRow = row.Trim();
                            if (!string.IsNullOrEmpty(trimmedRow))
                            {
                                var rowFilter = SearchSyntaxHelper.GetFilterCondition(trimmedRow, keyWords);
                                applyFilter = SearchSyntaxHelper.AddSearchCondition(applyFilter, rowFilter);
                            }
                        }
                    }
                    else
                    {
                        applyFilter = txtFilter.Text;
                    }
                }

                ids = HttpUtility.UrlEncode(txtFilter.Text);
            }
            break;

            // Set checkbox list
            case SearchFilterModeEnum.Checkbox:
            {
                // Set visibility and layout
                chklstFilter.Visible         = true;
                chklstFilter.RepeatDirection = RepeatDirection.Vertical;
                if (FilterLayout == ControlLayoutEnum.Horizontal)
                {
                    chklstFilter.RepeatDirection = RepeatDirection.Horizontal;
                }

                chklstFilter.RepeatLayout  = GetLayoutEnumFromString(RepeatLayout);
                chklstFilter.RepeatColumns = RepeatColumns;

                // Get selected items
                applyFilter = GetSelectedItems(chklstFilter, out ids);

                // Set autopostback
                if (FilterAutoPostback)
                {
                    chklstFilter.AutoPostBack = true;
                }

                AppendClientHandlers(chklstFilter);
            }
            break;

            // Set radio list
            case SearchFilterModeEnum.RadioButton:
            {
                // Set visibility and layout
                radlstFilter.Visible         = true;
                radlstFilter.RepeatDirection = RepeatDirection.Vertical;
                if (FilterLayout == ControlLayoutEnum.Horizontal)
                {
                    radlstFilter.RepeatDirection = RepeatDirection.Horizontal;
                }

                radlstFilter.RepeatLayout  = GetLayoutEnumFromString(RepeatLayout);
                radlstFilter.RepeatColumns = RepeatColumns;

                // Get selected items
                applyFilter = GetSelectedItems(radlstFilter, out ids);

                // Set autopostback
                if (FilterAutoPostback)
                {
                    radlstFilter.AutoPostBack = true;
                }

                AppendClientHandlers(radlstFilter);
            }
            break;

            // Set dropdown list
            default:
            {
                // Set visibility
                drpFilter.Visible = true;

                // Get selected items
                applyFilter = GetSelectedItems(drpFilter, out ids);

                // Set auto postback
                if (FilterAutoPostback)
                {
                    drpFilter.AutoPostBack = true;
                }

                AppendClientHandlers(drpFilter);

                lblFilter.AssociatedControlID = drpFilter.ID;
            }
            break;
            }

            // Apply filter and add selected values to query string
            ISearchFilterable searchWebpart = (ISearchFilterable)CMSControlsHelper.GetFilter(SearchWebpartID);
            if (searchWebpart != null)
            {
                // Check if postback was caused by any control in the filter
                var postBackControl = ControlsHelper.GetPostBackControl(Page);
                var filterPostback  = (postBackControl != null) && (postBackControl.Parent == this);

                if (FilterIsConditional)
                {
                    // If filter fieldname or value is filled
                    if (!SearchSyntaxHelper.IsEmptyCondition(applyFilter))
                    {
                        // Handle filter clause
                        if (!string.IsNullOrEmpty(FilterClause))
                        {
                            applyFilter = FilterClause + SearchSyntaxHelper.GetGroup(new[] { applyFilter });
                        }

                        searchWebpart.ApplyFilter(applyFilter, null, filterPostback);
                    }

                    searchWebpart.AddFilterOptionsToUrl(webpartID, ids);
                }
                else
                {
                    searchWebpart.ApplyFilter(null, applyFilter, filterPostback);
                    searchWebpart.AddFilterOptionsToUrl(webpartID, ids);
                }
            }
        }
    }
Ejemplo n.º 10
0
    /// <summary>
    /// Perform search.
    /// </summary>
    protected void Search()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Check if the search was triggered
            bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext");

            // Get query strings
            string searchText = QueryHelper.GetString("searchtext", "");
            // Check whether string passes text requirements settings
            bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText));

            // Proceed when search was triggered and search text is passing requirements settings.
            // Requirements setting could be overriden on this level by obsolete web.config key. The reason is backward compatibility.
            // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true.
            // This default value had the same effect as this new web part setting. When somenone changed the web.config key to false and then upgraded the solution,
            // required wep part setting with default value true would override previous behaviour. That's the reason why this obsolete key can override this setting.
            if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent))
            {
                string         searchMode     = QueryHelper.GetString("searchMode", "");
                SearchModeEnum searchModeEnum = searchMode.ToEnum <SearchModeEnum>();

                // Get current culture
                string culture = CultureCode;
                if (string.IsNullOrEmpty(culture))
                {
                    culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode);
                }

                // Get default culture
                string defaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName);

                // Resolve path
                string path = Path;
                if (!string.IsNullOrEmpty(path))
                {
                    path = MacroResolver.ResolveCurrentPath(Path);
                }

                if (PortalContext.ViewMode.IsLiveSite())
                {
                    if (AnalyticsHelper.JavascriptLoggingEnabled(SiteContext.CurrentSiteName))
                    {
                        ScriptHelper.RegisterWebServiceCallFunction(Page);
                        string script = "WebServiceCall('" + URLHelper.GetAbsoluteUrl("~/CMSPages/WebAnalyticsService.asmx") +
                                        "','LogSearch', '{\"keyword\":" +
                                        // Serialize raw search text to encode '<' and similar characters, then escape '\'
                                        new JavaScriptSerializer().Serialize(searchText).Replace(@"\", @"\\") +
                                        ", \"pageGUID\":\"" + DocumentContext.CurrentPageInfo.DocumentGUID + "\"}')";
                        ScriptHelper.RegisterStartupScript(Page, typeof(string), "logSearch", script, true);
                    }
                    else
                    {
                        // Log on site keywords
                        AnalyticsHelper.LogOnSiteSearchKeywords(SiteContext.CurrentSiteName, DocumentContext.CurrentAliasPath, culture, searchText, 0, 1);
                    }
                }

                // Prepare search text
                var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture);

                var searchCond = SearchCondition;
                if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms))
                {
                    // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded)
                    searchCond     = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture);
                    searchModeEnum = SearchModeEnum.AnyWord;
                }

                var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch);

                searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

                // Get positions and ranges for search method
                int startPosition     = 0;
                int numberOfProceeded = 100;
                int displayResults    = 100;
                if (pgr.PageSize != 0 && pgr.GroupSize != 0)
                {
                    // Reset pager if needed
                    if (mResetPager)
                    {
                        pgr.CurrentPage = 1;
                    }

                    startPosition = (pgr.CurrentPage - 1) * pgr.PageSize;
                    // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging.
                    numberOfProceeded = (((pgr.CurrentPage / pgr.GroupSize) + 1) * pgr.PageSize * pgr.GroupSize) + pgr.PageSize;
                    displayResults    = pgr.PageSize;
                }

                if ((MaxResults > 0) && (numberOfProceeded > MaxResults))
                {
                    numberOfProceeded = MaxResults;
                }

                // Combine regular search sort with filter sort
                string srt       = ValidationHelper.GetString(SearchSort, String.Empty).Trim();
                string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim();

                if (!String.IsNullOrEmpty(filterSrt))
                {
                    if (!String.IsNullOrEmpty(srt))
                    {
                        srt += ", ";
                    }

                    srt += filterSrt;
                }

                // Prepare parameters
                SearchParameters parameters = new SearchParameters
                {
                    SearchFor                 = searchText,
                    SearchSort                = srt,
                    Path                      = path,
                    ClassNames                = DocumentTypes,
                    CurrentCulture            = culture,
                    DefaultCulture            = defaultCulture,
                    CombineWithDefaultCulture = CombineWithDefaultCulture,
                    CheckPermissions          = CheckPermissions,
                    SearchInAttachments       = SearchInAttachments,
                    User                      = MembershipContext.AuthenticatedUser,
                    SearchIndexes             = Indexes,
                    StartingPosition          = startPosition,
                    DisplayResults            = displayResults,
                    NumberOfProcessedResults  = numberOfProceeded,
                    NumberOfResults           = 0,
                    AttachmentWhere           = AttachmentsWhere,
                    AttachmentOrderBy         = AttachmentsOrderBy,
                    BlockFieldOnlySearch      = BlockFieldOnlySearch,
                };

                // Search
                DataSet results = SearchHelper.Search(parameters);

                int numberOfResults = parameters.NumberOfResults;

                if ((MaxResults > 0) && (numberOfResults > MaxResults))
                {
                    numberOfResults = MaxResults;
                }

                // Fill repeater with results
                repSearchResults.DataSource = results;
                repSearchResults.PagerForceNumberOfResults = numberOfResults;
                PagerForceNumberOfResults = numberOfResults;
                repSearchResults.DataBind();

                // Call page binding event
                if (OnPageBinding != null)
                {
                    OnPageBinding(this, null);
                }

                // Show now results found ?
                if (numberOfResults == 0)
                {
                    if (ShowParsingErrors)
                    {
                        Exception searchError = SearchContext.LastError;
                        if (searchError != null)
                        {
                            ShowError(GetString("smartsearch.searcherror") + " " + searchError.Message);
                        }
                    }
                    lblNoResults.Text    = NoResultsText;
                    lblNoResults.Visible = true;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed)
                {
                    pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass);
                    lblNoResults.Text    = SearchTextValidationFailedText;
                    lblNoResults.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }

            // Invoke search completed event
            if (OnSearchCompleted != null)
            {
                OnSearchCompleted(Visible);
            }
        }
    }
Ejemplo n.º 11
0
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // Get current index id
        int indexId = QueryHelper.GetInteger("indexId", 0);

        // Get current index info object
        SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(indexId);

        // Show warning if indes isn't ready yet
        if ((sii != null) && (sii.IndexStatus == IndexStatusEnum.NEW))
        {
            ShowWarning(GetString("srch.index.needrebuild"));
        }

        if (!RequestHelper.IsPostBack())
        {
            // Get current search text from query string
            string searchText = QueryHelper.GetString("searchtext", "");
            // Check whether search text is defined
            if (!string.IsNullOrEmpty(searchText))
            {
                // Get current search mode from query string
                string         searchMode     = QueryHelper.GetString("searchmode", "");
                SearchModeEnum searchModeEnum = searchMode.ToEnum <SearchModeEnum>();

                // Check whether index info exists
                if (sii != null)
                {
                    // Keep search text in search textbox
                    //txtSearchFor.Text = searchText;
                    var condition = new SearchCondition(null, searchModeEnum, SearchOptionsEnum.FullSearch);

                    searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

                    // Get positions and ranges for search method
                    int startPosition     = 0;
                    int numberOfProceeded = 100;
                    int displayResults    = 100;
                    if (pgrSearch.CurrentPageSize != 0 && pgrSearch.GroupSize != 0)
                    {
                        startPosition     = (pgrSearch.CurrentPage - 1) * pgrSearch.CurrentPageSize;
                        numberOfProceeded = (((pgrSearch.CurrentPage / pgrSearch.GroupSize) + 1) * pgrSearch.CurrentPageSize * pgrSearch.GroupSize) + pgrSearch.CurrentPageSize;
                        displayResults    = pgrSearch.CurrentPageSize;
                    }

                    // Prepare parameters
                    SearchParameters parameters = new SearchParameters()
                    {
                        SearchFor                 = searchText,
                        SearchSort                = null,
                        Path                      = null,
                        ClassNames                = null,
                        CurrentCulture            = "##ALL##",
                        DefaultCulture            = null,
                        CombineWithDefaultCulture = false,
                        CheckPermissions          = false,
                        SearchInAttachments       = false,
                        User                      = MembershipContext.AuthenticatedUser,
                        SearchIndexes             = sii.IndexName,
                        StartingPosition          = startPosition,
                        DisplayResults            = displayResults,
                        NumberOfProcessedResults  = numberOfProceeded,
                        NumberOfResults           = 0,
                        AttachmentWhere           = null,
                        AttachmentOrderBy         = null,
                    };

                    // Search
                    DataSet results = SearchHelper.Search(parameters);

                    // Fill repeater with results
                    repSearchResults.DataSource = results;
                    repSearchResults.PagerForceNumberOfResults = parameters.NumberOfResults;
                    repSearchResults.DataBind();

                    // Show now results found ?
                    if (parameters.NumberOfResults == 0)
                    {
                        lblNoResults.Text    = "<br />" + GetString("srch.results.noresults.preview");
                        lblNoResults.Visible = true;

                        Exception searchError = SearchContext.LastError;
                        if (searchError != null)
                        {
                            pnlError.Visible = true;
                            lblError.Text    = GetString("smartsearch.searcherror") + " " + searchError.Message;
                        }
                    }
                }
            }

            // Fill CMSDropDownList option with values
            ControlsHelper.FillListControlWithEnum <SearchModeEnum>(drpSearchMode, "srch.dialog", useStringRepresentation: true);
            drpSearchMode.SelectedValue = QueryHelper.GetString("searchmode", EnumHelper.GetDefaultValue <SearchModeEnum>().ToStringRepresentation());

            // Set up search text
            txtSearchFor.Text = QueryHelper.GetString("searchtext", "");
        }
    }
Ejemplo n.º 12
0
    /// <summary>
    /// Perform search.
    /// </summary>
    protected void Search()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Check if the search was triggered
            bool searchAllowed = SearchOnEachPageLoad || QueryHelper.Contains("searchtext");

            // Get query strings
            string searchText = QueryHelper.GetString("searchtext", "");
            // Check whether string passes text requirements settings
            bool searchTextIsNotEmptyOrNotRequired = (!SearchTextRequired || !String.IsNullOrEmpty(searchText));

            // Proceed when search was triggered and search text is passing requirements settings.
            // Requirements setting could be overridden on this level by obsolete web.config key. The reason is backward compatibility.
            // Search text required web part setting was introduced after this web.config key. Key default value was at the time set to true.
            // This default value had the same effect as this new web part setting. When someone changed the web.config key to false and then upgraded the solution,
            // required web part setting with default value true would override previous behavior. That's the reason why this obsolete key can override this setting.
            if (searchAllowed && (searchTextIsNotEmptyOrNotRequired || !SearchHelper.SearchOnlyWhenContentPresent))
            {
                string         searchMode     = QueryHelper.GetString("searchMode", "");
                SearchModeEnum searchModeEnum = EnumStringRepresentationExtensions.ToEnum <SearchModeEnum>(searchMode);

                // Get current culture
                string culture = CultureCode;
                if (string.IsNullOrEmpty(culture))
                {
                    culture = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode);
                }

                var siteName = SiteContext.CurrentSiteName;

                // Get default culture
                string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName);

                // Resolve path
                string path = Path;
                if (!string.IsNullOrEmpty(path))
                {
                    path = MacroResolver.ResolveCurrentPath(Path);
                }

                // Prepare search text
                var docCondition = new DocumentSearchCondition(DocumentTypes, culture, defaultCulture, CombineWithDefaultCulture);

                var searchCond = SearchCondition;
                if (!string.IsNullOrEmpty(FilterSearchCondition) && (searchModeEnum == SearchModeEnum.AnyWordOrSynonyms))
                {
                    // Make sure the synonyms are expanded before the filter condition is applied (filter condition is Lucene syntax, cannot be expanded)
                    searchCond = SearchSyntaxHelper.ExpandWithSynonyms(searchCond, docCondition.Culture);
                }

                var condition = new SearchCondition(searchCond + FilterSearchCondition, searchModeEnum, SearchOptions, docCondition, DoFuzzySearch);

                searchText = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);

                // Get positions and ranges for search method
                int startPosition     = 0;
                int numberOfProceeded = 100;
                int displayResults    = 100;
                if (pgr.PageSize != 0 && pgr.GroupSize != 0)
                {
                    // Reset pager if needed
                    if (mResetPager)
                    {
                        pgr.CurrentPage = 1;
                    }

                    startPosition = (pgr.CurrentPage - 1) * pgr.PageSize;
                    // Only results covered by current page group are proccessed (filtered) for performance reasons. This may cause decrease of the number of results while paging.
                    numberOfProceeded = (((pgr.CurrentPage / pgr.GroupSize) + 1) * pgr.PageSize * pgr.GroupSize) + pgr.PageSize;
                    displayResults    = pgr.PageSize;
                }

                if ((MaxResults > 0) && (numberOfProceeded > MaxResults))
                {
                    numberOfProceeded = MaxResults;
                }

                // Combine regular search sort with filter sort
                string srt       = ValidationHelper.GetString(SearchSort, String.Empty).Trim();
                string filterSrt = ValidationHelper.GetString(FilterSearchSort, String.Empty).Trim();

                if (!String.IsNullOrEmpty(filterSrt))
                {
                    if (!String.IsNullOrEmpty(srt))
                    {
                        srt += ", ";
                    }

                    srt += filterSrt;
                }

                // Prepare parameters
                SearchParameters parameters = new SearchParameters
                {
                    SearchFor                 = searchText,
                    SearchSort                = srt,
                    Path                      = path,
                    ClassNames                = DocumentTypes,
                    CurrentCulture            = culture,
                    DefaultCulture            = defaultCulture,
                    CombineWithDefaultCulture = CombineWithDefaultCulture,
                    CheckPermissions          = CheckPermissions,
                    SearchInAttachments       = SearchInAttachments,
                    User                      = MembershipContext.AuthenticatedUser,
                    SearchIndexes             = Indexes,
                    StartingPosition          = startPosition,
                    DisplayResults            = displayResults,
                    NumberOfProcessedResults  = numberOfProceeded,
                    NumberOfResults           = 0,
                    AttachmentWhere           = AttachmentsWhere,
                    AttachmentOrderBy         = AttachmentsOrderBy,
                    BlockFieldOnlySearch      = BlockFieldOnlySearch,
                };

                // Search
                var results = SearchHelper.Search(parameters);

                int numberOfResults = parameters.NumberOfResults;
                if ((MaxResults > 0) && (numberOfResults > MaxResults))
                {
                    numberOfResults = MaxResults;
                }

                // Limit displayed results according to MaxPages property
                var maxDisplayedResultsOnMaxPages = MaxPages * PageSize;
                // Apply only if MaxPages and PageSize properties are set
                if ((maxDisplayedResultsOnMaxPages > 0) && (numberOfResults > maxDisplayedResultsOnMaxPages))
                {
                    numberOfResults = maxDisplayedResultsOnMaxPages;
                }

                // Fill repeater with results
                repSearchResults.DataSource = results.Items;
                repSearchResults.PagerForceNumberOfResults = numberOfResults;
                PagerForceNumberOfResults = numberOfResults;
                repSearchResults.DataBind();

                // Call page binding event
                if (OnPageBinding != null)
                {
                    OnPageBinding(this, null);
                }

                // Show no results found ?
                if (numberOfResults == 0)
                {
                    if (ShowParsingErrors)
                    {
                        Exception searchError = results.LastError;
                        if (searchError != null)
                        {
                            ShowError(GetString("smartsearch.searcherror") + " " + HTMLHelper.HTMLEncode(searchError.Message));
                        }
                    }
                    lblNoResults.Text    = NoResultsText;
                    lblNoResults.Visible = true;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(SearchTextValidationFailedText) && searchAllowed)
                {
                    pnlSearchResults.AddCssClass(SearchTextValidationFailedCssClass);
                    lblNoResults.Text    = SearchTextValidationFailedText;
                    lblNoResults.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }

            // Invoke search completed event
            if (OnSearchCompleted != null)
            {
                OnSearchCompleted(Visible);
            }
        }
    }