コード例 #1
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);
            }
        }
    }
コード例 #2
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);
            }
        }
    }