コード例 #1
0
ファイル: ResourceLibraryHelper.cs プロジェクト: ossusa/3358
        public static IEnumerable <SearchResult> GetSearchResults_stv(string catalog, SearchCriteria criteria, int skip, int take, int summaryWordCount, out int hitCount)
        {
            var searchService = ServiceBus.ResolveService <ISearchService>();
            var searchQuery   = ObjectFactory.Resolve <ISearchQuery>();

            var           queryBuilder = ObjectFactory.Resolve <IQueryBuilder>();
            StringBuilder sb           = new StringBuilder();


            searchQuery.Skip              = skip;
            searchQuery.Take              = take;
            searchQuery.OrderBy           = criteria.OrderBy == null ? new string[] { "PublicationDate DESC" } : new string[] { criteria.OrderBy };
            searchQuery.HighlightedFields = null;
            searchQuery.IndexName         = catalog;
            searchQuery.SearchGroup       = BuildSearchQuery(criteria, new[] { "Title", "Content", "DocumentText" });

            var resultSet = searchService.Search(searchQuery);

            hitCount = resultSet.HitCount;

            var results         = new List <SearchResult>();
            var taxonomyManager = TaxonomyManager.GetManager();

            log.InfoFormat("ResourceLib:{0};",
                           criteria.ToQueryString());

            foreach (var result in resultSet.SetContentLinks())
            {
                var searchResult = new SearchResult();

                try
                {
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("CategoryIds").ToString()))
                    {
                        var categoryIds = result.GetValue("CategoryIds").ToString().Split(' ').ToList();

                        searchResult.CategoryPair = new List <CategoryPair>();
                        var parentGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyId");

                        foreach (var categoryId in categoryIds)
                        {
                            log.InfoFormat("ResourceLibraryTaxonomyId-cateids:{0}, parentGuidId:{1}", categoryIds, parentGuidId);
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            do
                            {
                                if (category.Parent != null && category.Parent.Id == parentGuidId)
                                {
                                    category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;
                                    var categoryPair = new CategoryPair();
                                    categoryPair.Name = category.Title.Value;
                                    categoryPair.Guid = categoryId.ToString().Replace("-", "");

                                    log.InfoFormat("CateInParent, Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                    sb.Append(String.Format("CateInParent, Title:{0}, guid:{1}", categoryPair.Name,
                                                            categoryPair.Guid));
                                    searchResult.CategoryPair.Add(categoryPair);
                                    break;
                                }

                                category = taxonomyManager.GetTaxon(category.Parent.Id) as HierarchicalTaxon;
                            } while (category.Parent != null);
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("OrganizationalAuthorsIds").ToString()))
                    {
                        var categoryIds = result.GetValue("OrganizationalAuthorsIds").ToString().Split(' ').ToList();
                        searchResult.Author = new List <CategoryPair>();
                        var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyAuthorId");

                        foreach (var categoryId in categoryIds)
                        {
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            if (category.Taxonomy.Id == taxonomyGuidId)
                            {
                                var categoryPair = new CategoryPair();
                                categoryPair.Name = category.Title.Value;
                                categoryPair.Guid = categoryId.ToString().Replace("-", "");
                                searchResult.Author.Add(categoryPair);

                                log.InfoFormat("ResourceLibraryTaxonomyAuthorId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                sb.AppendFormat("ResourceLibraryTaxonomyAuthorId-Title:{0}, guid:{1}", categoryPair.Name,
                                                categoryPair.Guid);
                            }
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ResourceTypesIds").ToString()))
                    {
                        var categoryIds = result.GetValue("ResourceTypesIds").ToString().Split(' ').ToList();
                        searchResult.ResourceTypes = new List <CategoryPair>();
                        var taxonomyGuidId = AppSettingsUtility.GetValue <Guid>("ResourceLibraryTaxonomyTypeId");

                        foreach (var categoryId in categoryIds)
                        {
                            var category = taxonomyManager.GetTaxon(Guid.Parse(categoryId)) as HierarchicalTaxon;

                            if (category.Taxonomy.Id == taxonomyGuidId)
                            {
                                var categoryPair = new CategoryPair();
                                categoryPair.Name = category.Title.Value;
                                categoryPair.Guid = categoryId.ToString().Replace("-", "");
                                searchResult.ResourceTypes.Add(categoryPair);

                                log.InfoFormat("ResourceLibraryTaxonomyTypeId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                                sb.AppendFormat("ResourceLibraryTaxonomyTypeId-Title:{0}, guid:{1}", categoryPair.Name, categoryPair.Guid);
                            }
                        }
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Title").ToString()))
                    {
                        searchResult.Title = result.GetValue("Title").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Link").ToString()))
                    {
                        searchResult.Link = result.GetValue("Link").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("PublishDate").ToString()))
                    {
                        searchResult.PublicationDate = DateTime.Parse(result.GetValue("PublishDate").ToString());
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("DocumentLibrary").ToString()))
                    {
                        searchResult.DocumentFolder = result.GetValue("DocumentLibrary").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("Summary").ToString()))
                    {
                        searchResult.Summary = result.GetValue("Summary").ToString();
                    }
                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ContentType").ToString()))
                    {
                        searchResult.Type = result.GetValue("ContentType").ToString();
                    }

                    if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ThumbnailUrl").ToString()))
                    {
                        searchResult.ImageUrl = result.GetValue("ThumbnailUrl").ToString();
                    }
                    else if (!SitefinityExtensions.IsNullOrEmpty(result.GetValue("ImageUrl").ToString()))
                    {
                        searchResult.ImageUrl = result.GetValue("ImageUrl").ToString();
                    }

                    var contentType = TypeResolutionService.ResolveType(searchResult.Type);

                    searchResult.Type = contentType.Name;



                    if (result.Fields.Any(f => f.Name == "EventStart") && !string.IsNullOrWhiteSpace(result.GetValue("EventStart").ToString()))
                    {
                        searchResult.EventStart = DateTime.Parse(result.GetValue("EventStart").ToString());
                    }

                    if (result.Fields.Any(f => f.Name == "EventEnd") && !string.IsNullOrWhiteSpace(result.GetValue("EventEnd").ToString()))
                    {
                        searchResult.EventEnd = DateTime.Parse(result.GetValue("EventEnd").ToString());
                    }
                    var content      = result.GetValue("Content").ToString().StripHtmlTags();
                    var docLink      = result.GetValue("DocumentLink");
                    var documentText = result.GetValue("DocumentText");
                    if (string.IsNullOrWhiteSpace(content) && !string.IsNullOrWhiteSpace(docLink.ToString()))
                    {
                        searchResult.Link = docLink.ToString();
                        content           = documentText.ToString();
                    }

                    if (string.IsNullOrWhiteSpace(searchResult.Summary))
                    {
                        searchResult.Summary = SummaryParser.GetSummary(content, new SummarySettings(SummaryMode.Words, summaryWordCount, true, true));
                    }
                }
                catch (Exception ex)
                {
                    //ex.ToString();
                    log.InfoFormat("Resources-Exception:{0}, details:{1}", ex.Message, sb.ToString());
                }

                results.Add(searchResult);
            }

            return(results);
        }
コード例 #2
0
        protected override void HandleUnknownAction(string actionName = "")
        {
            try
            {
                log.Info("Begin HandleUnknownAction. view:{0}", _viewTemplate);
                var dynamicModuleManager = DynamicModuleManager.GetManager();

                /*if (string.IsNullOrEmpty(_viewTemplate))
                 * {
                 *  this.View(new EmptyResult()).ExecuteResult(ControllerContext);
                 *
                 * }*/

                var dynamicTypes     = new List <Type>();
                var dynamicTypeNames = AppSettingsUtility.GetValue <string>("RelatedItems.DynamicType.List").Split('|').ToList();

                foreach (var dynamicTypeName in dynamicTypeNames)
                {
                    if (!string.IsNullOrWhiteSpace(dynamicTypeName))
                    {
                        dynamicTypes.Add(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model." + dynamicTypeName));
                    }
                }
                // set default
                if (dynamicTypes.Count == 0)
                {
                    dynamicTypes.Add(TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.OnSceneArticles.OnSceneArticle"));
                }


                var taxonomyManager = TaxonomyManager.GetManager();
                var currentContext  = System.Web.HttpContext.Current;
                var postUrl         = currentContext.Request.Url.AbsolutePath;

                if (postUrl.Contains('?'))
                {
                    postUrl = postUrl.Split('?').First();
                    log.Trace("postUrl: {0}", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);
                }

                postUrl = currentContext.Request.Url.AbsolutePath.Split('/').Last();
                log.Debug("postUrl: {0}", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);

                foreach (var dynamicType in dynamicTypes)
                {
                    var item = dynamicModuleManager.GetDataItems(dynamicType)
                               .FirstOrDefault(bp => bp.UrlName == postUrl && bp.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live);

                    if (item != null)
                    {
                        //log.Debug("item: {0}", SitefinityExtensions.IsNullOrEmpty(item.GetValue<Lstring>("Title").Value) ? "There is no title set" : item.GetValue<Lstring>("Title").Value);
                        //---item = dynamicModuleManager.Lifecycle.GetLive(item) as DynamicContent;
                        //log.Trace("Got the live version of the Blog Post.");
                        try
                        {
                            //var allCategories = Enumerable.ToArray(item.GetValue<IList<Guid>>("Category"));
                            var allCategories = item.GetValue <IList <Guid> >("Category")?.ToArray();
                            //log.Debug("Got a list of category ids for the post, {0}.", allCategories.Count());
                            List <Guid> categories = new List <Guid>();

                            //log.Trace("Set the list for Blended List Query.");
                            int hitCount = 0;
                            //log.Trace("Set the hitcount variable required for Sitefinity Search.");
                            if (allCategories != null && allCategories.Any())
                            {
                                foreach (var currGuid in allCategories)
                                {
                                    var currTaxon = taxonomyManager.GetTaxon <HierarchicalTaxon>(currGuid);

                                    if (currTaxon != null)
                                    {
                                        //log.Debug("Got taxonomy, {0}, for the id, {1}", SitefinityExtensions.IsNullOrEmpty(currTaxon.Title.Value) ? "There is no title set" : currTaxon.Title.Value);
                                        categories.Add(currGuid);
                                        //log.Trace("Taxon added to the list for the search.");
                                    }
                                }
                            }

                            IEnumerable <IDocument> resultListItems = BlendedNewsHelper.GetNewsDocs(Providers, _searchIndex, out hitCount,
                                                                                                    categories?.ToArray(), null, 0, this.NumberOfPosts + 10);

                            List <BlendedListItem> blendedListItems = new List <BlendedListItem>();
                            if (resultListItems != null)
                            {
                                var rs = SetBlendedListItems(resultListItems);
                                if (rs != null)
                                {
                                    blendedListItems = rs
                                                       .Where(bli => !bli.Link.Contains(item.UrlName) &&
                                                              !bli.Featured).Take(this.NumberOfPosts).ToList();
                                }
                            }
                            //string template = _viewTemplate;
                            //log.Info("Finishing HandleUnknownAction");
                            this.View(_viewTemplate, blendedListItems).ExecuteResult(ControllerContext);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Source: {0}", ex.Source);
                            log.Error("Stack Trace: {0}", ex.StackTrace);
                            log.Error("HandleUnknownAction-relatedContentForDyn: {0}", ex.Message);
                        }
                    }
                    else
                    {
                        log.Debug("There was no item for the given url, ({0}).", SitefinityExtensions.IsNullOrEmpty(postUrl) ? "There is no url available" : postUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Info("exceptionRelatedContent:{0}, inner:{1}", ex.Message, ex.InnerException?.Message);
            }
        }
コード例 #3
0
ファイル: ResourceLibraryHelper.cs プロジェクト: ossusa/3358
        public static SearchQueryGroup BuildSearchQuery(SearchCriteria model, string[] searchFields)
        {
            //GOAL: (Title:[term]* Content:[term*]) AND (Title:[secondTerm]* Content:[secondTerm]*) AND (Type:[t1] OR Type:[t2] ... OR Type:[tN]) AND (Category:[c1] ... OR Category:[cN])
            //log.Trace("Keyword: {0}", keyword);
            var queryGroups = new SearchQueryGroup(QueryOperator.And);

            //var queryGroups = new List<string>();

            //**** TERMS ****
            var documentLibraryToSearch = AppSettingsUtility.GetValue <string>("ResourceLibrary.DocumentLibrary.ToSearch");

            if (!string.IsNullOrEmpty(documentLibraryToSearch))
            {
                var SearchDocumentLibraryGroup = new SearchQueryGroup(QueryOperator.Or);
                var documentLibraries          = documentLibraryToSearch.Split(',').ToList();

                foreach (var documentLibrary in documentLibraries)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "DocumentLibrary";
                    searchTerm.Value = documentLibrary;
                    SearchDocumentLibraryGroup.AddTerm(searchTerm);
                }

                queryGroups.AddGroup(SearchDocumentLibraryGroup);
            }

            //**** TERMS ****
            if (!string.IsNullOrEmpty(model.Term))
            {
                var SearchTermGroup = new SearchQueryGroup(QueryOperator.Or);
                var keyword         = model.Term + " " + model.SecondTerm;

                foreach (var field in searchFields)
                {
                    var keywords = keyword.Split(' ');
                    var count    = keywords.Count();

                    for (int i = 0; i < count; i++)
                    {
                        if (!SitefinityExtensions.IsNullOrEmpty(keywords[i]))
                        {
                            var searchTerm = new SearchTerm();
                            searchTerm.Field = field;
                            //log.Trace("Search Term Field: {0}", searchTerm.Field);
                            searchTerm.Value = keywords[i];
                            //log.Trace("Search Term Value: {0}", searchTerm.Value);
                            SearchTermGroup.AddTerm(searchTerm);
                        }
                    }
                }

                queryGroups.AddGroup(SearchTermGroup);
            }

            //**** TYPES *****
            if (model.Types != null && model.Types.Any())
            {
                var searchTypeGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var type in model.Types)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "ResourceTypesIds";
                    searchTerm.Value = type;

                    searchTypeGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchTypeGroup);
            }

            //**** TOPICS ****
            if (model.Topics != null && model.Topics.Any())
            {
                var searchCategoriesGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var cat in model.Topics)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "CategoryIds";
                    searchTerm.Value = cat.ToString().Replace("-", "");

                    searchCategoriesGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchCategoriesGroup);
            }

            //**** Authors ****
            if (model.Authors != null && model.Authors.Any())
            {
                var searchAuthorsGroup = new SearchQueryGroup(QueryOperator.Or);
                foreach (var cat in model.Authors)
                {
                    var searchTerm = new SearchTerm();
                    searchTerm.Field = "OrganizationalAuthorsIds";
                    searchTerm.Value = cat.ToString().Replace("-", "");

                    searchAuthorsGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(searchAuthorsGroup);
            }

            if (model.Types == null && model.Topics == null && string.IsNullOrEmpty(model.Term) && string.IsNullOrEmpty(model.SecondTerm))
            {
                SearchQueryGroup SearchAnyGroup = new SearchQueryGroup(QueryOperator.Or);
                var searchField = "Title";
                var sTerm       = "a* b* c* d* e* f* g* h* i* j* k* l* m* n* o* p* q* r* s* t* u* v* w* x* y* z*";

                foreach (var term in sTerm.Split(' '))
                {
                    var searchTerm = new SearchTerm
                    {
                        Field = searchField,
                        Value = term
                    };
                    //add wildcards to the query terms
                    SearchAnyGroup.AddTerm(searchTerm);
                }
                queryGroups.AddGroup(SearchAnyGroup);
            }

            return(queryGroups);
        }