コード例 #1
0
        public static string FindProjects(string query, int parent, bool wildcard)
        {
            if (query.ToLower() == "useqsstring")
            {
                query = UmbracoContext.Current.Request.QueryString["term"];
            }
            if (wildcard && !query.EndsWith("*"))
            {
                query += "*";
            }
            string             searchTerm = query;
            BaseSearchProvider searcher   = ExamineManager.Instance.SearchProviderCollection["MultiIndexSearcher"];



            //Search Criteria for WIKI & Projects
            var searchCriteria = searcher.CreateSearchCriteria(BooleanOperation.Or);
            var searchQuery    = searchTerm.BuildExamineString(99, "nodeName");

            searchQuery += searchTerm.BuildExamineString(10, "description");
            searchQuery  = "(" + searchQuery + ") AND +approved:1";
            var searchFilter = searchCriteria.RawQuery(searchQuery);
            IEnumerable <SearchResult> searchResults = searcher.Search(searchFilter).OrderByDescending(x => x.Score);

            searchResults = from r in searchResults
                            where r["__IndexType"] == "content" && r["nodeTypeAlias"] == "Project"
                            select r;
            //orderby int.Parse(r["downloads"]) descending select r;

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return(serializer.Serialize(searchResults));
        }
コード例 #2
0
        private void GetUsageData()
        {
            int nodeId   = Int32.Parse(Request.QueryString["id"]);
            var criteria = searcher.CreateSearchCriteria(IndexTypes.Content);

            string[] fields = PropertyTypes.Split(new[] { ',' });

            var query = criteria.OrderBy("__nodeName");

            query = fields.Aggregate(query, (current, field) => current.Or().Field(field, nodeId.ToString()));

            _results             = searcher.Search(query.Compile());
            queryGenerated.Value = criteria.ToString();

            if (_results.Any())
            {
                rptItemUsage.DataSource = _results;
                rptItemUsage.DataBind();
                litMessage.Text = "The page is referenced by the pages listed below";
            }
            else
            {
                rptItemUsage.Visible = false;
                litMessage.Text      = NoResultstext;
            }
        }
コード例 #3
0
        protected override PagedResult <IMedia> PerformSearch(QueryStructure query)
        {
            if (query.Lucene.IsNullOrWhiteSpace())
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var result =
                SearchProvider.Search(
                    SearchProvider.CreateSearchCriteria().RawQuery(query.Lucene),
                    query.PageSize);

            var paged = result.Skip(GetSkipSize(query.PageIndex, query.PageSize)).ToArray();

            //TODO: We really need to make a model mapper from search result to IMedia, for now well just go lookup that content :(

            if (paged.Any())
            {
                var foundContent = MediaService.GetByIds(paged.Select(x => x.Id)).WhereNotNull();

                return(new PagedResult <IMedia>(result.TotalItemCount, query.PageIndex + 1, query.PageSize)
                {
                    Items = foundContent
                });
            }

            return(new PagedResult <IMedia>(result.TotalItemCount, query.PageIndex + 1, query.PageSize)
            {
                Items = Enumerable.Empty <IMedia>()
            });
        }
コード例 #4
0
        public HttpResponseMessage GetListByTags(string tags, string id)
        {
            if (string.IsNullOrEmpty(tags))
            {
                return(Request.CreateResponse(HttpStatusCode.Accepted, ""));
            }

            var currentPage = _helper.TypedContent(id);
            var tagArray    = tags.Split(',');
            var criteria    = _ExternalSearcher.CreateSearchCriteria();
            var query       = new StringBuilder();

            query.AppendFormat("__IndexType:{0} -umbracoNaviHide:1 +searchPath:{1} ", UmbracoExamine.IndexTypes.Content, currentPage.Id);
            var groupedOr = new StringBuilder();

            foreach (var tag in tagArray)
            {
                groupedOr.AppendFormat("eventTags:{0} ", tag);
            }
            query.Append("+(" + groupedOr.ToString() + ") ");

            var criteria2 = criteria.RawQuery(query.ToString());
            var results   = _ExternalSearcher.Search(criteria2);

            var listOfContent = new List <EventContentModel>();

            foreach (var result in results)
            {
                var content    = _helper.TypedContent(result.Id);
                var image      = content.GetPropertyValue("teaserImage", content.GetPropertyValue("heroImage", Enumerable.Empty <IPublishedContent>()));
                var eventStart = content.GetPropertyValue <DateTime>("eventStart");
                var startTime  = content.GetPropertyValue <DateTime>("startTime");
                var eventEnd   = content.GetPropertyValue <DateTime>("eventEnd");
                var endTime    = content.GetPropertyValue <DateTime>("endTime");
                var tagList    = content.GetPropertyValue("eventTags", Enumerable.Empty <IPublishedContent>());

                listOfContent.Add(new EventContentModel {
                    ImageUrl   = image.Any() ? image.FirstOrDefault().Url : "",
                    Headline   = content.GetPropertyValue <string>("teaserHeadline", content.GetPropertyValue <string>("headline", content.Name)),
                    Lead       = content.GetPropertyValue <string>("teaserLead", content.GetPropertyValue <string>("lead", "")),
                    Url        = content.Url,
                    StartDate  = eventStart.Year > 1 ? eventStart.ToString("d/M yyyy", CultureInfo.InvariantCulture) : "",
                    StartTime  = startTime.Year > 1 ? startTime.ToString("d/M yyyy", CultureInfo.InvariantCulture) : "",
                    EndDate    = eventEnd.Year > 1 ? eventEnd.ToString("d/M yyyy", CultureInfo.InvariantCulture) : "",
                    Endtime    = endTime.Year > 1 ? endTime.ToString("d/M yyyy", CultureInfo.InvariantCulture) : "",
                    EventPlace = content.GetPropertyValue <string>("eventPlace"),
                    Tags       = tagList.Any() ? tagList.Select(x => x.Name).ToArray() : new string[0]
                });
            }

            var jObject = JArray.FromObject(
                listOfContent,
                new JsonSerializer {
                NullValueHandling = NullValueHandling.Ignore
            }
                );

            return(Request.CreateResponse(HttpStatusCode.Accepted, jObject));
        }
コード例 #5
0
        /// <summary>
        /// queries the Lucene index to get all members with the supplied partyGuid
        /// </summary>
        /// <param name="members">the Umbraco MembershipHelper</param>
        /// <param name="partyGuid">Guid identifying a specific party</param>
        /// <returns>a collection of PartyHost / PartyGuest associated with a specific party</returns>
        public static IEnumerable <IPartier> GetPartiers(this MembershipHelper members, Guid partyGuid)
        {
            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];
            ISearchCriteria    searchCriteria = searchProvider.CreateSearchCriteria(IndexTypes.Member).Field("partyGuid", partyGuid.ToString()).Compile();
            ISearchResults     searchResults  = searchProvider.Search(searchCriteria);

            return(searchResults.Select(x => (IPartier)members.GetById(x.Id)));
        }
コード例 #6
0
        public void Can_Save_A_Customer_And_Find_It_In_The_Index()
        {
            //// Arrange
            var customer = _customerService.CreateCustomerWithKey(
                "rusty",
                "firstName",
                "lastName",
                "*****@*****.**");

            //// Act
            var criteria = _searcher.CreateSearchCriteria(IndexTypes.Customer);

            criteria.Field("loginName", "rusty");
            var results = _searcher.Search(criteria);

            //// Assert
            Assert.IsTrue(results.Any());
        }
コード例 #7
0
        ///<summary>
        /// Uses the provider specified to search, returning an XPathNodeIterator
        ///</summary>
        ///<param name="searchText"></param>
        ///<param name="useWildcards"></param>
        ///<param name="provider"></param>
        ///<param name="indexType"></param>
        ///<returns></returns>
        internal static XPathNodeIterator Search(string searchText, bool useWildcards, BaseSearchProvider provider, string indexType)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            var results = provider.Search(searchText, useWildcards, indexType);

            return(GetResultsAsXml(results));
        }
コード例 #8
0
ファイル: SearchHelper.cs プロジェクト: wigo4it/nl-app
        private IEnumerable <SearchResult> GetLinkingPages(ISearchResults initialResult, string[] linkedPageIDs)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            var linkingPageIds = GetLinkingPageIds(initialResult, linkedPageIDs);

            var secondSearchCriteria = _searcher.CreateSearchCriteria(BooleanOperation.Or);
            var secondQuery          = secondSearchCriteria.GroupedOr(new[] { "id" }, linkingPageIds);

            var additionalResult = _searcher.Search(secondQuery.Compile());

            var filtered = RemoveRedundantLinkingPages(additionalResult);

            sw.Stop();
            LogHelper.Info(this.GetType(), $"NLAPP: GetLinkinPages took {sw.ElapsedMilliseconds}ms.");

            return(filtered);
        }
コード例 #9
0
ファイル: ExamineService.cs プロジェクト: ziachap/LiveLink
        // TODO: Return some sort of pagination type
        public IEnumerable <IPublishedContent> Search(BaseSearchProvider searcher,
                                                      ISearchCriteria criteria, int?page, int?itemsPerPage)
        {
            if (IsPaginated(page, itemsPerPage))
            {
                return(searcher.Search(criteria, page.Value * itemsPerPage.Value)
                       .Select(x => _umbracoWrapper.TypedContent(x.Id))
                       .Skip((page.Value - 1) * itemsPerPage.Value));
            }

            return(_umbracoWrapper.TypedSearch(criteria, searcher));
        }
コード例 #10
0
        private static ISearchResults PerformSearch(this BaseSearchProvider provider, string terms, string[] fields)
        {
            var criteria = provider.CreateSearchCriteria(BooleanOperation.And);
            var filter   = (terms ?? string.Empty).Trim('?', '*').Trim();

            // Set a flag indicating whether the criteria has been built or not.
            bool criteriaBuilt = false;

            if (!string.IsNullOrWhiteSpace(filter))
            {
                var singleTerms = filter.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var sb          = new StringBuilder();
                var wrapTerm    = false;
                if (filter.Contains(' '))
                {
                    wrapTerm = true;

                    // Proximity search on all terms:
                    foreach (var field in fields)
                    {
                        sb.Append($@"{field}: ""{filter}""~10 ");
                    }
                }

                // Basic and wildcard term search:
                foreach (var field in fields)
                {
                    sb.AppendFormat("{0}:{2}{1}{2} ", field, filter, wrapTerm ? '"' : (char?)null);
                    sb.AppendFormat("{0}:{2}{1}*{2} ", field, filter, wrapTerm ? '"' : (char?)null);
                }

                criteria.RawQuery(sb.ToString());
                criteriaBuilt = true;
            }

            if (criteriaBuilt)
            {
                return(provider.Search(criteria));
            }

            return(null);
        }
コード例 #11
0
        public ISearchResults Search(string text, int homeNodeId)
        {
            var criteria = _examineSearcher.CreateSearchCriteria(BooleanOperation.Or);

            var fixedText = Regex.Replace(text, "\\s", " ");
            var textArr   = fixedText.Split(' ');

            textArr[textArr.Length - 1] = textArr[textArr.Length - 1] + "*";

            var query =
                criteria.Field("_fixedPath", homeNodeId.ToString())
                .And()
                .GroupedOr(new string[] { "_allContent" }, textArr)
                .Not()
                .Field("umbracoNaviHide", "1")
                .Not()
                .NodeTypeAlias("Movie");

            return(_examineSearcher.Search(query.Compile()));
        }
コード例 #12
0
ファイル: SearchHelper.cs プロジェクト: wigo4it/nl-app
        public IOrderedEnumerable <SearchResult> Search(string queryString, string searcherName)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            LogHelper.Info(this.GetType(), $"NLAPP: Search started. Term: {queryString}");

            var currentCulture = Thread.CurrentThread.CurrentCulture.ToString();

            _searcher = ExamineManager.Instance.SearchProviderCollection[searcherName];
            var searchCriteria = _searcher.CreateSearchCriteria();
            IOrderedEnumerable <SearchResult> retVal = null;

            // All page content is indexed per language. Search the content for the current language.
            var initialQuery = searchCriteria
                               .Field("PageContent-" + currentCulture, queryString.ToLowerInvariant().Fuzzy())
                               .And()
                               .GroupedOr(new[] { "searchablePath" }, GetSearchableNodeIds());

            var initialResult = _searcher.Search(initialQuery.Compile());
            var linkedPageIDs = GetLinkedPageIds(initialResult);

            if (linkedPageIDs.Any())
            {
                var additionalResult = GetLinkingPages(initialResult, linkedPageIDs);
                var filteredResult   = RemoveLinkedPages(initialResult, linkedPageIDs);
                retVal = filteredResult.Concat(additionalResult).OrderByDescending(x => x.Score);
            }
            else
            {
                retVal = initialResult.OrderByDescending(x => x.Score);
            }

            sw.Stop();
            LogHelper.Info(this.GetType(), $"NLAPP: Search (term: {queryString}) finished. Duration: {sw.ElapsedMilliseconds}ms");

            return(retVal);
        }
コード例 #13
0
        public static LastEditedItem[] GetLastEditedData(IDashboardSite site, int userId, int max)
        {
            // List for constructing the raw query
            List <string> query = new List <string>();

            // Get a reference to the internal searcher
            BaseSearchProvider externalSearcher = ExamineManager.Instance.SearchProviderCollection["InternalSearcher"];

            // Limit the search to pages under the specified site
            query.Add("sky_path:" + site.Id);

            // Limit the search to pages last edited by the specified user
            if (userId >= 0)
            {
                query.Add("writerID:" + userId);
            }

            // Initialize the criteria for the Examine search
            ISearchCriteria criteria = externalSearcher.CreateSearchCriteria().RawQuery(String.Join(" AND ", query));

            // Make the actual search in Examine
            ISearchResults results = externalSearcher.Search(criteria);

            // Order the results (and limit the amount of results)
            IEnumerable <SearchResult> sorted = results.OrderByDescending(x => x.Fields["updateDate"]).Take(max);

            return((
                       from result in sorted
                       select new LastEditedItem {
                Id = result.Id,
                CreateDate = ParseExamineDate(result.Fields["createDate"]),
                UpdateDate = ParseExamineDate(result.Fields["updateDate"]),
                IsPublished = UmbracoContext.Current.ContentCache.GetById(result.Id) != null,
                Name = result.Fields["nodeName"],
                Path = result.Fields["path"]
            }
                       ).ToArray());
        }
コード例 #14
0
        public static PartyHost GetPartyHost(this MembershipHelper members, string partyUrlIdentifier)
        {
            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];
            ISearchCriteria    searchCriteria = searchProvider.CreateSearchCriteria(IndexTypes.Member).Field("partyUrlIdentifier", partyUrlIdentifier).Compile();
            ISearchResults     searchResults  = searchProvider.Search(searchCriteria);

            return(searchResults.Select(x => (PartyHost)members.GetById(x.Id)).SingleOrDefault());

            //// WARNING: hits db
            //IMember partyHost = ApplicationContext
            //                        .Current
            //                        .Services
            //                        .MemberService
            //                        .GetMembersByMemberType(PartyHost.Alias)
            //                        .SingleOrDefault(x => x.GetValue<string>(PartyHost.PartyUrlIdentifierAlias).ToLower() == partyUrlIdentifier.ToLower());

            //if (partyHost != null)
            //{
            //    return new PartyHost(members.GetByUsername(partyHost.Username));
            //}

            //return null;
        }
コード例 #15
0
ファイル: LuceneDataSource.cs プロジェクト: vamone/nuPickers
        private IEnumerable <EditorDataItem> GetEditorDataItems(int contextId)
        {
            List <EditorDataItem> editorDataItems = new List <EditorDataItem>();

            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection[this.ExamineSearcher];

            if (searchProvider != null)
            {
                ISearchCriteria searchCriteria = searchProvider.CreateSearchCriteria().RawQuery(this.RawQuery);
                ISearchResults  searchResults  = searchProvider.Search(searchCriteria);

                foreach (SearchResult searchResult in searchResults)
                {
                    editorDataItems.Add(
                        new EditorDataItem()
                    {
                        Key   = searchResult.Fields.ContainsKey(this.KeyField) ? searchResult.Fields[this.KeyField] : null,
                        Label = searchResult.Fields.ContainsKey(this.LabelField) ? searchResult.Fields[this.LabelField] : null
                    });
                }
            }

            return(editorDataItems);
        }
コード例 #16
0
        /// <summary>
        /// Gets the search results.
        /// </summary>
        /// <param name="searchTerm">The search text. Search string separated whitespace.</param>
        /// <param name="searchFields">The search fields.</param>
        /// <param name="searchProviderName">Name of the search provider.</param>
        /// <param name="useAndOperation">Search with wildcard.</param>
        /// <returns>Collection of <see cref="Examine.SearchResult"/>.</returns>
        public static IEnumerable <SearchResult> GetSearchResults(string searchTerm, string[] searchFields, string searchProviderName, bool useAndOperation)
        {
            if (searchTerm == null)
            {
                throw new ArgumentNullException(nameof(searchTerm));
            }
            if (searchFields == null)
            {
                throw new ArgumentNullException(nameof(searchFields));
            }
            if (searchProviderName == null)
            {
                throw new ArgumentNullException(nameof(searchProviderName));
            }

            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection[searchProviderName];
            ISearchCriteria    criteria       = searchProvider.CreateSearchCriteria(BooleanOperation.Or);

            string[]             terms      = searchTerm.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            IEnumerable <string> rawQueries = GetRawQueries(searchFields, useAndOperation, searchFields.Length, terms);
            ISearchCriteria      filter     = criteria.RawQuery(rawQueries.ToStringWithBrackets());

            return(searchProvider.Search(filter).DistinctBy(sr => sr.Id));
        }
コード例 #17
0
        private void ObtainByScripture(Models.SearchList searchList, int pageNo)
        {
            //Instantiate variables
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);

            searchList.ShowBible     = true;
            searchList.SearchInTitle = "The Scriptures";


            if (!string.IsNullOrWhiteSpace(searchList.SearchFor))
            {
                //Get all prayers
                BaseSearchProvider mySearcher    = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.ScriptureSearcher];
                ISearchCriteria    criteria      = mySearcher.CreateSearchCriteria(IndexTypes.Content);
                ISearchResults     searchResults = mySearcher.Search(searchList.SearchFor, true);


                //Get item counts and total experiences.
                searchList.Pagination.itemsPerPage = 30;
                searchList.Pagination.totalItems   = searchResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (searchList.Pagination.totalItems > searchList.Pagination.itemsPerPage)
                {
                    searchList.Pagination.totalPages = (int)Math.Ceiling((double)searchList.Pagination.totalItems / (double)searchList.Pagination.itemsPerPage);
                }
                else
                {
                    searchList.Pagination.itemsPerPage = searchList.Pagination.totalItems;
                    searchList.Pagination.totalPages   = 1;
                }


                //Determine current page number
                if (pageNo <= 0 || pageNo > searchList.Pagination.totalPages)
                {
                    pageNo = 1;
                }
                searchList.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (searchList.Pagination.totalItems > searchList.Pagination.itemsPerPage)
                {
                    searchList.Pagination.itemsToSkip = searchList.Pagination.itemsPerPage * (pageNo - 1);
                }


                //Convert list of SearchResults to list of classes
                foreach (SearchResult sRecord in searchResults.Skip(searchList.Pagination.itemsToSkip).Take(searchList.Pagination.itemsPerPage))
                {
                    var scriptureLink           = new Models.ScriptureLink();
                    IPublishedContent ipArticle = umbracoHelper.TypedContent(sRecord.Id);
                    scriptureLink.Id         = ipArticle.Id;
                    scriptureLink.Url        = ipArticle.Parent.Url + "?chapter=" + ipArticle.Name;
                    scriptureLink.Breadcrumb = GetBreadcrumbForScripture(ipArticle);

                    searchList.lstBibleLinks.Add(scriptureLink);
                }
            }
        }
コード例 #18
0
        public static List <latestUpdates> ObtainLatestMessages()
        {
            //Instantiate variables
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            List <latestUpdates> lstLatestUpdates = new List <latestUpdates>();


            try
            {
                //Get all messages
                BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.MessagesSearcher];
                ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(IndexTypes.Content);
                IBooleanOperation  query      = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items
                query.And().OrderByDescending(Common.NodeProperties.publishDate);
                query.And().OrderBy(Common.NodeProperties.nodeName);
                query.And().OrderBy(Common.miscellaneous.Path);
                ISearchResults isResults = mySearcher.Search(query.Compile());


                if (isResults.Any())
                {
                    //Instantiate variables
                    DateTime msgDate = new DateTime(1900, 1, 1);
                    //DateTime prevDate = new DateTime(1900, 1, 1);
                    latestUpdates     latestUpdate = new latestUpdates();
                    visionary         visionary    = new visionary();
                    message           message;
                    IPublishedContent ipMsg;
                    IPublishedContent ipVisionary;
                    Boolean           isFirst = true;


                    //Get top 'n' results and determine link structure
                    foreach (SearchResult srResult in isResults)
                    {
                        //Obtain message's node
                        ipMsg = umbracoHelper.TypedContent(Convert.ToInt32(srResult.Id));
                        if (ipMsg != null)
                        {
                            if (isFirst)
                            {
                                //Obtain date of latest message
                                msgDate = ipMsg.GetPropertyValue <DateTime>(Common.NodeProperties.publishDate);
                                isFirst = false;
                            }
                            else
                            {
                                //Exit loop if a different publish date exists
                                if (msgDate != ipMsg.GetPropertyValue <DateTime>(Common.NodeProperties.publishDate))
                                {
                                    break;
                                }
                            }


                            //Create a new date for messages
                            //if (msgDate != prevDate)
                            //{
                            //    //Update current date
                            //    prevDate = msgDate;

                            //Create new instances for updates and add to list of all updates.
                            latestUpdate = new latestUpdates();
                            latestUpdate.datePublished = msgDate;
                            lstLatestUpdates.Add(latestUpdate);

                            //Reset the visionary class on every new date change.
                            visionary = new visionary();
                            //}

                            //Obtain current visionary or webmaster
                            if (ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary) != null)
                            {
                                if (visionary.id != ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary).Id)
                                {
                                    //Obtain visionary node
                                    ipVisionary = ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary);

                                    //Create new visionary class and add to latest update class
                                    visionary      = new visionary();
                                    visionary.id   = ipVisionary.Id;
                                    visionary.name = ipVisionary.Name;
                                    visionary.url  = ipVisionary.UrlAbsolute();
                                    latestUpdate.lstVisionaries.Add(visionary);
                                }
                            }
                            else if (ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList) != null)
                            {
                                if (visionary.id != ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList).Id)
                                {
                                    //Obtain visionary node
                                    ipVisionary = ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList);

                                    //Create new visionary class and add to latest update class
                                    visionary      = new visionary();
                                    visionary.id   = ipVisionary.Id;
                                    visionary.name = ipVisionary.Name;
                                    visionary.url  = ipVisionary.UrlAbsolute();
                                    latestUpdate.lstVisionaries.Add(visionary);
                                }
                            }

                            //Create new message and add to existing visionary class.
                            message       = new message();
                            message.id    = ipMsg.Id;
                            message.title = ipMsg.Name;
                            message.url   = ipMsg.UrlAbsolute();
                            visionary.lstMessages.Add(message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //StringBuilder sb = new StringBuilder();
                //sb.AppendLine(@"MessageController.cs : RenderLatestMessages()");
                //sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(lstLatestUpdates));
                //Common.saveErrorMessage(ex.ToString(), sb.ToString());


                //ModelState.AddModelError("", "*An error occured while creating the latest message list.");
                //return CurrentUmbracoPage();
            }


            //
            return(lstLatestUpdates);
        }
コード例 #19
0
        public static LatestUpdateList ObtainAllMessages(int pageNo = 1)
        {
            //Instantiate variables
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            LatestUpdateList lstLatestUpdates = new LatestUpdateList();


            //try
            //{
            //Get all ...
            BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.MessagesSearcher];
            ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(IndexTypes.Content);
            IBooleanOperation  query      = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items

            query.And().OrderByDescending(Common.NodeProperties.publishDate);
            query.And().OrderBy(Common.NodeProperties.nodeName);
            query.And().OrderBy(Common.miscellaneous.Path);
            ISearchResults isResults = mySearcher.Search(query.Compile());

            if (isResults.Any())
            {
                //Instantiate variables
                DateTime          msgDate      = new DateTime(1900, 1, 1);
                DateTime          prevDate     = new DateTime(1900, 1, 1);
                latestUpdates     latestUpdate = new latestUpdates();
                visionary         visionary    = new visionary();
                message           message;
                IPublishedContent ipMsg;
                IPublishedContent ipVisionary;



                //Get item counts and total experiences.
                lstLatestUpdates.Pagination.itemsPerPage = 20;
                lstLatestUpdates.Pagination.totalItems   = isResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (lstLatestUpdates.Pagination.totalItems > lstLatestUpdates.Pagination.itemsPerPage)
                {
                    lstLatestUpdates.Pagination.totalPages = (int)Math.Ceiling((double)lstLatestUpdates.Pagination.totalItems / (double)lstLatestUpdates.Pagination.itemsPerPage);
                }
                else
                {
                    lstLatestUpdates.Pagination.itemsPerPage = lstLatestUpdates.Pagination.totalItems;
                    lstLatestUpdates.Pagination.totalPages   = 1;
                }


                //Determine current page number
                if (pageNo <= 0 || pageNo > lstLatestUpdates.Pagination.totalPages)
                {
                    pageNo = 1;
                }
                lstLatestUpdates.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (lstLatestUpdates.Pagination.totalItems > lstLatestUpdates.Pagination.itemsPerPage)
                {
                    lstLatestUpdates.Pagination.itemsToSkip = lstLatestUpdates.Pagination.itemsPerPage * (pageNo - 1);
                }



                //Get top 'n' results and determine link structure
                //foreach (SearchResult srResult in isResults.Take(30))
                foreach (SearchResult srResult in isResults.Skip(lstLatestUpdates.Pagination.itemsToSkip).Take(lstLatestUpdates.Pagination.itemsPerPage))
                {
                    //Obtain message's node
                    ipMsg = umbracoHelper.TypedContent(Convert.ToInt32(srResult.Id));
                    if (ipMsg != null)
                    {
                        //Obtain date of message
                        msgDate = ipMsg.GetPropertyValue <DateTime>(Common.NodeProperties.publishDate);

                        //Create a new date for messages
                        if (msgDate != prevDate)
                        {
                            //Update current date
                            prevDate = msgDate;

                            //Create new instances for updates and add to list of all updates.
                            latestUpdate = new latestUpdates();
                            latestUpdate.datePublished = msgDate;
                            lstLatestUpdates.LstLatestUpdates.Add(latestUpdate);

                            //Reset the visionary class on every new date change.
                            visionary = new visionary();
                        }

                        //Obtain current visionary or webmaster
                        if (ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary) != null)
                        {
                            if (visionary.id != ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary).Id)
                            {
                                //Obtain visionary node
                                ipVisionary = ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.Visionary);

                                //Create new visionary class and add to latest update class
                                visionary      = new visionary();
                                visionary.id   = ipVisionary.Id;
                                visionary.name = ipVisionary.Name;
                                visionary.url  = ipVisionary.Url;
                                latestUpdate.lstVisionaries.Add(visionary);
                            }
                        }
                        else if (ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList) != null)
                        {
                            if (visionary.id != ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList).Id)
                            {
                                //Obtain visionary node
                                ipVisionary = ipMsg.AncestorsOrSelf().FirstOrDefault(x => x.DocumentTypeAlias == Common.docType.WebmasterMessageList);

                                //Create new visionary class and add to latest update class
                                visionary      = new visionary();
                                visionary.id   = ipVisionary.Id;
                                visionary.name = ipVisionary.Name;
                                visionary.url  = ipVisionary.Url;
                                latestUpdate.lstVisionaries.Add(visionary);
                            }
                        }

                        //Create new message and add to existing visionary class.
                        message       = new message();
                        message.id    = ipMsg.Id;
                        message.title = ipMsg.Name;
                        message.url   = ipMsg.Url;
                        visionary.lstMessages.Add(message);
                    }
                }
            }


            //}
            //catch (Exception ex)
            //{
            //    //StringBuilder sb = new StringBuilder();
            //    //sb.AppendLine(@"MessageController.cs : RenderLatestMessages()");
            //    //sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(lstLatestUpdates));
            //    //Common.SaveErrorMessage(ex, sb, typeof(MessageController));


            //    //ModelState.AddModelError("", "*An error occured while creating the latest message list.");
            //    //return CurrentUmbracoPage();
            //}


            //Return data to partialview
            return(lstLatestUpdates);
        }
コード例 #20
0
        public ActionResult RenderAllMessages()
        {
            //Instantiate variables
            MsgList msgList       = new MsgList();
            var     umbracoHelper = new UmbracoHelper(UmbracoContext.Current);


            try
            {
                //Get all prayers
                BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.MessagesSearcher];
                ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(IndexTypes.Content);
                IBooleanOperation  query      = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items
                query.And().OrderByDescending(Common.NodeProperties.publishDate);
                query.And().OrderBy(Common.NodeProperties.nodeName);
                ISearchResults isResults = mySearcher.Search(query.Compile());


                //Get item counts and total experiences.
                msgList.Pagination.itemsPerPage = 20;
                msgList.Pagination.totalItems   = isResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
                {
                    msgList.Pagination.totalPages = (int)Math.Ceiling((double)msgList.Pagination.totalItems / (double)msgList.Pagination.itemsPerPage);
                }
                else
                {
                    msgList.Pagination.itemsPerPage = msgList.Pagination.totalItems;
                    msgList.Pagination.totalPages   = 1;
                }


                //Determine current page number
                var pageNo = 1;
                if (!string.IsNullOrEmpty(Request.QueryString[Common.miscellaneous.PageNo]))
                {
                    int.TryParse(Request.QueryString[Common.miscellaneous.PageNo], out pageNo);
                    if (pageNo <= 0 || pageNo > msgList.Pagination.totalPages)
                    {
                        pageNo = 1;
                    }
                }
                msgList.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
                {
                    msgList.Pagination.itemsToSkip = msgList.Pagination.itemsPerPage * (pageNo - 1);
                }


                //Convert list of SearchResults to list of classes
                foreach (SearchResult sRecord in isResults.Skip(msgList.Pagination.itemsToSkip).Take(msgList.Pagination.itemsPerPage))
                {
                    var msgLink = new Models.MsgLink();
                    msgLink.Id       = sRecord.Id;
                    msgLink.Title    = sRecord.Fields[Common.NodeProperties.nodeName];
                    msgLink.Subtitle = sRecord.Fields[Common.NodeProperties.subtitle];
                    msgLink.Url      = Umbraco.NiceUrl(sRecord.Id);
                    //msgLink.Date = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]);
                    msgLink.Dates = (Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate])).ToString("MMMM dd");

                    msgList.lstMsgLinks.Add(msgLink);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"MessageController.cs : RenderAllMessages()");
                sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(msgList));
                Common.SaveErrorMessage(ex, sb, typeof(MessageController));


                ModelState.AddModelError("", "*An error occured while retrieving all messages.");
                return(CurrentUmbracoPage());
            }


            //Return data to partialview
            return(PartialView("~/Views/Partials/MessagesFromHeaven/_msgList.cshtml", msgList));
        }
コード例 #21
0
        //public ActionResult RenderMsgs_byVisionary(IPublishedContent ipVisionary)
        //{
        //    //Instantiate variables
        //    MsgList msgList = new MsgList();
        //    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);


        //    try
        //    {
        //        msgList.VisionaryName = "working";

        //        //Get all prayers
        //        BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.MessagesSearcher];
        //        ISearchCriteria criteria = mySearcher.CreateSearchCriteria(IndexTypes.Content);
        //        IBooleanOperation query = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items when this exists for every record.
        //        query.And().OrderByDescending(Common.NodeProperties.publishDate);
        //        query.And().OrderBy(Common.NodeProperties.nodeName);
        //        query.And().Field(Common.miscellaneous.Path, ipVisionary.Path.MultipleCharacterWildcard());
        //        ISearchResults isResults = mySearcher.Search(query.Compile());


        //        //Get item counts and total experiences.
        //        msgList.Pagination.itemsPerPage = 30;
        //        msgList.Pagination.totalItems = isResults.Count();


        //        //Determine how many pages/items to skip and take, as well as the total page count for the search result.
        //        if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
        //        {
        //            msgList.Pagination.totalPages = (int)Math.Ceiling((double)msgList.Pagination.totalItems / (double)msgList.Pagination.itemsPerPage);
        //        }
        //        else
        //        {
        //            msgList.Pagination.itemsPerPage = msgList.Pagination.totalItems;
        //            msgList.Pagination.totalPages = 1;
        //        }


        //        //Determine current page number
        //        var pageNo = 1;
        //        if (!string.IsNullOrEmpty(Request.QueryString[Common.miscellaneous.PageNo]))
        //        {
        //            int.TryParse(Request.QueryString[Common.miscellaneous.PageNo], out pageNo);
        //            if (pageNo <= 0 || pageNo > msgList.Pagination.totalPages)
        //            {
        //                pageNo = 1;
        //            }
        //        }
        //        msgList.Pagination.pageNo = pageNo;


        //        //Determine how many pages/items to skip
        //        if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
        //        {
        //            msgList.Pagination.itemsToSkip = msgList.Pagination.itemsPerPage * (pageNo - 1);
        //        }


        //        //Convert list of SearchResults to list of classes
        //        foreach (SearchResult sRecord in isResults.Skip(msgList.Pagination.itemsToSkip).Take(msgList.Pagination.itemsPerPage))
        //        {
        //            var msgLink = new Models.MsgLink();
        //            msgLink.Id = sRecord.Id;
        //            msgLink.Title = sRecord.Fields[Common.NodeProperties.nodeName];
        //            msgLink.Subtitle = sRecord.Fields[Common.NodeProperties.subtitle];
        //            msgLink.Url = Umbraco.NiceUrl(sRecord.Id);


        //            //msgLink.Date = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]);


        //            //Obtain list of all dates
        //            var ipMsg = Umbraco.TypedContent(sRecord.Id);
        //            List<DateTime> lstDateRange = ipMsg.GetPropertyValue<List<DateTime>>(Common.NodeProperties.dateOfMessages);


        //            //Determine proper date range for messages
        //            if (lstDateRange != null && lstDateRange.Count > 0)
        //            {
        //                if (lstDateRange.Count == 1)
        //                {
        //                    msgLink.Dates = lstDateRange.First().ToString("MMM d");
        //                }
        //                else
        //                {
        //                    StringBuilder sbDateRange = new StringBuilder();
        //                    sbDateRange.Append(lstDateRange.First().ToString("MMM d"));
        //                    sbDateRange.Append(" — ");
        //                    sbDateRange.Append(lstDateRange.Last().ToString("MMM d"));

        //                    msgLink.Dates = sbDateRange.ToString();
        //                }
        //            }
        //            else
        //            {
        //                msgLink.Dates = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]).ToString("MMM d");
        //            }

        //            msgList.lstMsgLinks.Add(msgLink);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        StringBuilder sb = new StringBuilder();
        //        sb.AppendLine(@"MessageController.cs : RenderMsgs_byVisionary()");
        //        //sb.AppendLine("ipVisionary:" + Newtonsoft.Json.JsonConvert.SerializeObject(ipVisionary));
        //        sb.AppendLine("msgList:" + Newtonsoft.Json.JsonConvert.SerializeObject(msgList));
        //        Common.SaveErrorMessage(ex, sb, typeof(MessageController));


        //        ModelState.AddModelError("", "*An error occured while retrieving messages by visionary.");
        //    }


        //    //Return data to partialview
        //    return PartialView("~/Views/Partials/MessagesFromHeaven/_msgList.cshtml", msgList);
        //}



        public ActionResult RenderMsgs_byVisionary(IPublishedContent ipVisionary)
        {
            //Instantiate variables
            MsgList msgList       = new MsgList();
            var     umbracoHelper = new UmbracoHelper(UmbracoContext.Current);


            try
            {
                msgList.VisionaryName = "working";

                //Get all prayers
                BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.MessagesSearcher];
                ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(IndexTypes.Content);
                IBooleanOperation  query      = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items when this exists for every record.
                query.And().OrderByDescending(Common.NodeProperties.publishDate);
                query.And().OrderBy(Common.NodeProperties.nodeName);
                query.And().Field(Common.miscellaneous.Path, ipVisionary.Path.MultipleCharacterWildcard());
                ISearchResults isResults = mySearcher.Search(query.Compile());


                //Get item counts and total experiences.
                msgList.Pagination.itemsPerPage = 30;
                msgList.Pagination.totalItems   = isResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
                {
                    msgList.Pagination.totalPages = (int)Math.Ceiling((double)msgList.Pagination.totalItems / (double)msgList.Pagination.itemsPerPage);
                }
                else
                {
                    msgList.Pagination.itemsPerPage = msgList.Pagination.totalItems;
                    msgList.Pagination.totalPages   = 1;
                }


                //Determine current page number
                var pageNo = 1;
                if (!string.IsNullOrEmpty(Request.QueryString[Common.miscellaneous.PageNo]))
                {
                    int.TryParse(Request.QueryString[Common.miscellaneous.PageNo], out pageNo);
                    if (pageNo <= 0 || pageNo > msgList.Pagination.totalPages)
                    {
                        pageNo = 1;
                    }
                }
                msgList.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (msgList.Pagination.totalItems > msgList.Pagination.itemsPerPage)
                {
                    msgList.Pagination.itemsToSkip = msgList.Pagination.itemsPerPage * (pageNo - 1);
                }


                //Convert list of SearchResults to list of classes
                foreach (SearchResult sRecord in isResults) //.Skip(msgList.Pagination.itemsToSkip).Take(msgList.Pagination.itemsPerPage))
                {
                    var msgLink = new Models.MsgLink();
                    msgLink.Id       = sRecord.Id;
                    msgLink.Title    = sRecord.Fields[Common.NodeProperties.nodeName];
                    msgLink.Subtitle = sRecord.Fields[Common.NodeProperties.subtitle];
                    msgLink.Url      = Umbraco.NiceUrl(sRecord.Id);


                    /* msgLink.Date = */
                    Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]);


                    //Obtain list of all dates
                    var             ipMsg        = Umbraco.TypedContent(sRecord.Id);
                    List <DateTime> lstDateRange = ipMsg.GetPropertyValue <List <DateTime> >(Common.NodeProperties.dateOfMessages);


                    //Determine proper date range for messages
                    if (lstDateRange != null && lstDateRange.Count > 0)
                    {
                        if (lstDateRange.Count == 1)
                        {
                            msgLink.Dates = lstDateRange.First().ToString("MMM d");
                        }
                        else
                        {
                            StringBuilder sbDateRange = new StringBuilder();
                            sbDateRange.Append(lstDateRange.First().ToString("MMM d"));
                            sbDateRange.Append(" — ");
                            sbDateRange.Append(lstDateRange.Last().ToString("MMM d"));

                            msgLink.Dates = sbDateRange.ToString();
                        }

                        msgLink.Date = lstDateRange.First(); //Used for resorting list before displaying
                    }
                    else
                    {
                        msgLink.Dates = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]).ToString("MMM d");
                        msgLink.Date  = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.publishDate]); //Used for resorting list before displaying
                    }

                    msgList.lstMsgLinks.Add(msgLink);
                }

                //Reorder messages by date and obtain only what is to be displayed.
                msgList.lstMsgLinks = msgList.lstMsgLinks.OrderByDescending(x => x.Date).Skip(msgList.Pagination.itemsToSkip).Take(msgList.Pagination.itemsPerPage).ToList();
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"MessageController.cs : RenderMsgs_byVisionary()");
                //sb.AppendLine("ipVisionary:" + Newtonsoft.Json.JsonConvert.SerializeObject(ipVisionary));
                sb.AppendLine("msgList:" + Newtonsoft.Json.JsonConvert.SerializeObject(msgList));
                Common.SaveErrorMessage(ex, sb, typeof(MessageController));


                ModelState.AddModelError("", "*An error occured while retrieving messages by visionary.");
            }


            //Return data to partialview
            return(PartialView("~/Views/Partials/MessagesFromHeaven/_msgList.cshtml", msgList));
        }
コード例 #22
0
 public ISearchResults Search(BaseSearchProvider searcher, ISearchCriteria criteria)
 {
     return(searcher.Search(criteria));
 }
コード例 #23
0
        public static XPathNodeIterator LuceneInContentType(string q, string types, int currentPage, int trimAtChar, int pagesize)
        {
            int _pageSize           = pagesize;
            int _page               = currentPage;
            int _fragmentCharacters = trimAtChar;
            int _googleNumbers      = 10;

            int _TotalResults;

            // Enable next, parent, headers and googleArrows
            DateTime searchStart = DateTime.Now;

            string queryText = q;

            string[] _fields = { "name", "content" };


            q = q.Replace("-", "\\-");

            new Page().Trace.Write("umbAdvancedSearch:doSearch", "Performing search! using query " + q);

            /*
             * IndexSearcher searcher = new IndexSearcher( new uSearch.Businesslogic.Settings().IndexDirectory);
             *
             * Analyzer analyzer = new StandardAnalyzer();
             *
             *
             * MultiFieldQueryParser mfqp = new MultiFieldQueryParser(_fields, analyzer);
             * Query mainquery = GetSafeQuery(mfqp,q);
             *
             * BooleanQuery filterQuery = new BooleanQuery();
             * filterQuery.Add(mainquery, BooleanClause.Occur.MUST);
             *
             * types = types.Trim(',');
             * if (!string.IsNullOrEmpty(types))
             * {
             *  string typeQuery = "";
             *  string[] t = types.Split(',');
             *  for (int i = 0; i < t.Length; i++)
             *  {
             *      typeQuery += t[i];
             *
             *      if (i < t.Length - 1)
             *          typeQuery += " OR ";
             *  }
             *
             *
             *  var parsedTypes = new QueryParser("contentType", analyzer).Parse(typeQuery);
             *  filterQuery.Add(parsedTypes, BooleanClause.Occur.MUST);
             * }
             *
             *
             *
             * Hits hits;
             * hits = searcher.Search(filterQuery);
             *
             */

            BaseSearchProvider Searcher = ExamineManager.Instance.SearchProviderCollection["ForumSearcher"];
            var searchCriteria          = Searcher.CreateSearchCriteria(BooleanOperation.Or);
            var searchQuery             = BuildExamineString(queryText, 10, "Title");

            searchQuery += BuildExamineString(queryText, 7, "CommentsContent").TrimEnd(' ');

            var searchFilter = searchCriteria.RawQuery(searchQuery);

            IEnumerable <SearchResult> searchResults;

            //little hacky just to get performant searching
            if (pagesize > 0)
            {
                searchResults = Searcher.Search(searchFilter)
                                .OrderByDescending(x => x.Score).Take(pagesize);
            }
            else
            {
                searchResults = Searcher.Search(searchFilter)
                                .OrderByDescending(x => x.Score);
            }



            _TotalResults = searchResults.Count();
            TimeSpan searchEnd   = DateTime.Now.Subtract(searchStart);
            string   searchTotal = searchEnd.Seconds + ".";

            for (int i = 4; i > searchEnd.Milliseconds.ToString().Length; i--)
            {
                searchTotal += "0";
            }
            searchTotal += searchEnd.Milliseconds.ToString();


            // Check for paging
            int pageSize  = _pageSize;
            int pageStart = _page;

            if (pageStart > 0)
            {
                pageStart = _page * pageSize;
            }
            int pageEnd = (_page + 1) * pageSize;



            //calculating total items and number of pages...
            int _firstGooglePage = _page - Convert.ToInt16(_googleNumbers / 2);

            if (_firstGooglePage < 0)
            {
                _firstGooglePage = 0;
            }
            int _lastGooglePage = _firstGooglePage + _googleNumbers;

            if (_lastGooglePage * pageSize > _TotalResults)
            {
                _lastGooglePage = (int)Math.Ceiling(_TotalResults / ((double)pageSize)); // Convert.ToInt32(hits.Length()/pageSize)+1;

                _firstGooglePage = _lastGooglePage - _googleNumbers;
                if (_firstGooglePage < 0)
                {
                    _firstGooglePage = 0;
                }
            }

            // Create xml document
            XmlDocument xd = new XmlDocument();

            xd.LoadXml("<search/>");
            xd.DocumentElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "query", queryText));
            xd.DocumentElement.AppendChild(umbraco.xmlHelper.addCDataNode(xd, "luceneQuery", q));
            xd.DocumentElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "results", _TotalResults.ToString()));
            xd.DocumentElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "currentPage", _page.ToString()));
            xd.DocumentElement.AppendChild(umbraco.xmlHelper.addTextNode(xd, "totalPages", _lastGooglePage.ToString()));

            XmlNode results = umbraco.xmlHelper.addTextNode(xd, "results", "");

            xd.DocumentElement.AppendChild(results);

            int highlightFragmentSizeInBytes = _fragmentCharacters;

            // Print results
            new Page().Trace.Write("umbSearchResult:doSearch", "printing results using start " + pageStart + " and end " + pageEnd);

            int r = 0;

            foreach (var sr in searchResults.Skip(pageStart).Take(pageSize))
            {
                XmlNode result = xd.CreateNode(XmlNodeType.Element, "result", "");
                result.AppendChild(umbraco.xmlHelper.addTextNode(xd, "score", (sr.Score * 100).ToString()));
                result.Attributes.Append(umbraco.xmlHelper.addAttribute(xd, "resultNumber", (r + 1).ToString()));

                foreach (var field in sr.Fields)
                {
                    result.AppendChild(umbraco.xmlHelper.addTextNode(xd, field.Key, field.Value));
                }

                results.AppendChild(result);
                r++;
            }

            return(xd.CreateNavigator().Select("."));
        } //end search
コード例 #24
0
        public ActionResult LinkTwitter(string oauth_token, string oauth_verifier)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                TwitterOAuthClient client = new TwitterOAuthClient();
                client.ConsumerKey    = WebConfigurationManager.AppSettings["twitterConsumerKey"];
                client.ConsumerSecret = WebConfigurationManager.AppSettings["twitterConsumerSecret"];

                // Grab the request token from the session
                SocialOAuthRequestToken requestToken = Session[oauth_token] as SocialOAuthRequestToken;
                if (requestToken == null)
                {
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your Twitter account again ;)"));
                }

                // Update the OAuth client with information from the request token
                client.Token       = requestToken.Token;
                client.TokenSecret = requestToken.TokenSecret;

                // Make the request to the Twitter API to get the access token
                SocialOAuthAccessTokenResponse response = client.GetAccessToken(oauth_verifier);

                // Get the access token from the response body
                TwitterOAuthAccessToken accessToken = (TwitterOAuthAccessToken)response.Body;

                // Update the OAuth client properties
                client.Token       = accessToken.Token;
                client.TokenSecret = accessToken.TokenSecret;

                // Initialize a new service instance from the OAUth client
                var service = Skybrud.Social.Twitter.TwitterService.CreateFromOAuthClient(client);

                // Get some information about the authenticated Twitter user
                TwitterAccount user;
                try
                {
                    // Initialize the options for the request (we don't need the status)
                    var options = new TwitterVerifyCrendetialsOptions
                    {
                        SkipStatus = true
                    };

                    // Make the request to the Twitter API
                    var userResponse = service.Account.VerifyCredentials(options);

                    // Update the "user" variable
                    user = userResponse.Body;
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the Twitter API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the Twitter screen name
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"twitter:{user.ScreenName}");

                // Check if there are other members with the same Twitter screen name
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting Twitter screen name for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same Twitter screen name."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "twitter" property and save the value
                mem.SetValue("twitter", user.ScreenName);
                mem.SetValue("twitterId", user.IdStr);
                mem.SetValue("twitterData", user.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with Twitter user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            InitLookUpDictionary();

            //Check we have a search term
            var orgSearchTerm = Request.QueryString["q"].Trim();

            searchTerm = orgSearchTerm.Replace(" OR ", " ").Replace(" or ", " ");

            // Replace double whitespaces with single space as they were giving errors
            searchTerm = Regex.Replace(searchTerm, @"\s{2,}", " ");

            if (string.IsNullOrEmpty(searchTerm) || searchTerm.Length == 1)
            {
                phNotValid.Visible = true;
                phResults.Visible  = false;
                return;
            }


            Searcher = ExamineManager.Instance.SearchProviderCollection["MultiIndexSearcher"];

            //Search Criteria for WIKI & Projects
            bool andSearch      = false;
            var  searchCriteria = Searcher.CreateSearchCriteria(BooleanOperation.Or);

            if (searchTerm.IndexOf("\"") == -1 && searchTerm.ToLower().IndexOf(" and ") > -1)
            {
                andSearch  = true;
                searchTerm = searchTerm.Replace(" and ", " ").Replace(" AND ", " ");
            }

            /*var searchFilter = searchCriteria.Field("a","b").Or().GroupedOr
             * .GroupedOr(new string[] { "nodeName", "bodyText", "description", "Title", "Body", "CommentsContent" }, searchTerm)
             * .Compile();*/



            var searchQuery = searchTerm.BuildExamineString(10, "nodeName", andSearch);

            searchQuery += searchTerm.BuildExamineString(8, "bodyText", andSearch);
            searchQuery += searchTerm.BuildExamineString(9, "description", andSearch);
            searchQuery += searchTerm.BuildExamineString(10, "Title", andSearch);
            searchQuery += searchTerm.BuildExamineString(8, "Body", andSearch);
            searchQuery += searchTerm.BuildExamineString(7, "CommentsContent", andSearch).TrimEnd(' ');

            var searchFilter = searchCriteria.RawQuery(searchQuery);


            searchResults = Searcher.Search(searchFilter).OrderByDescending(x => x.Score);

            // set the searchterm back for the results view
            searchTerm = orgSearchTerm;

            //Get where to search (content)
            string searchWhere = Request.QueryString["content"];

            searchResults = FilterOnContentType(searchWhere, searchResults);

            if (Request.QueryString["OrderByDate"] == "1")
            {
                var sortOrder = Request.QueryString["SortOrder"];
                if (sortOrder != null && sortOrder.ToLower() == "desc")
                {
                    OrderByDateDescLink.CssClass = OrderByDateDescLink.CssClass + "linkNoColor";
                    searchResults = searchResults.OrderByDescending(x => x.getDateSortable());
                }
                else
                {
                    OrderByDateAscLink.CssClass = OrderByDateAscLink.CssClass + "linkNoColor";
                    searchResults = searchResults.OrderBy(x => x.getDateSortable());
                }
            }
            else
            {
                OrderByNoneLink.CssClass = OrderByNoneLink.CssClass + "linkNoColor";
            }

            BindResultsAndSetUpPaging(searchResults);
        }
コード例 #26
0
        public ActionResult RenderList()
        {
            //Instantiate variables
            var prayerList = new Models.PrayerList();

            try
            {
                //
                var memberShipHelper = new Umbraco.Web.Security.MembershipHelper(UmbracoContext.Current);
                var CmPrayerList     = new ContentModels.PrayerList(Umbraco.TypedContent((int)Common.siteNode.ThePrayerCorner));

                //Get all prayers
                BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.PrayersSearcher];
                ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(IndexTypes.Content);
                IBooleanOperation  query      = criteria.Field(Common.NodeProperties.indexType, Common.NodeProperties.content); //gets all items
                query.And().OrderByDescending(Common.NodeProperties.requestDate);
                query.And().OrderBy(Common.NodeProperties.prayerTitle);
                ISearchResults isResults = mySearcher.Search(query.Compile());


                //Get item counts and total experiences.
                prayerList.Pagination.itemsPerPage = 10;
                prayerList.Pagination.totalItems   = isResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (prayerList.Pagination.totalItems > prayerList.Pagination.itemsPerPage)
                {
                    prayerList.Pagination.totalPages = (int)Math.Ceiling((double)prayerList.Pagination.totalItems / (double)prayerList.Pagination.itemsPerPage);
                }
                else
                {
                    prayerList.Pagination.itemsPerPage = prayerList.Pagination.totalItems;
                    prayerList.Pagination.totalPages   = 1;
                }


                //Determine current page number
                var pageNo = 1;
                if (!string.IsNullOrEmpty(Request.QueryString[Common.miscellaneous.PageNo]))
                {
                    int.TryParse(Request.QueryString[Common.miscellaneous.PageNo], out pageNo);
                    if (pageNo <= 0 || pageNo > prayerList.Pagination.totalPages)
                    {
                        pageNo = 1;
                    }
                }
                prayerList.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (prayerList.Pagination.totalItems > prayerList.Pagination.itemsPerPage)
                {
                    prayerList.Pagination.itemsToSkip = prayerList.Pagination.itemsPerPage * (pageNo - 1);
                }


                //Convert list of SearchResults to list of classes
                foreach (SearchResult sRecord in isResults.Skip(prayerList.Pagination.itemsToSkip).Take(prayerList.Pagination.itemsPerPage))
                {
                    //Create new prayerLink class
                    var prayerLink = new Models.PrayerLink();
                    prayerLink.Id    = sRecord.Id;
                    prayerLink.Title = sRecord.Fields[Common.NodeProperties.prayerTitle];
                    prayerLink.Url   = Umbraco.NiceUrl(sRecord.Id);
                    prayerLink.Date  = Convert.ToDateTime(sRecord.Fields[Common.NodeProperties.requestDate]);


                    //Determine current percentage
                    prayerLink.currentPercentage   = int.Parse(sRecord.Fields[Common.NodeProperties.currentPercentage]);
                    prayerLink.baseCalculationDate = DateTime.Parse(sRecord.Fields[Common.NodeProperties.baseCalculationDate]);
                    int daysSinceBaseDate = (DateTime.Now - prayerLink.baseCalculationDate).Days;
                    if (daysSinceBaseDate > prayerLink.currentPercentage)
                    {
                        prayerLink.currentPercentage = 0;
                    }
                    else
                    {
                        prayerLink.currentPercentage = prayerLink.currentPercentage - daysSinceBaseDate;
                    }


                    //Determine proper candle based upon current percentage
                    prayerLink.CandleUrl = CmPrayerList.CandleOut.Url;
                    if (prayerLink.currentPercentage == 0)
                    {
                        prayerLink.CandleUrl = CmPrayerList.CandleOut.Url;
                    }
                    else if (prayerLink.currentPercentage >= 1 && prayerLink.currentPercentage <= 10)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle10.Url;
                    }
                    else if (prayerLink.currentPercentage >= 11 && prayerLink.currentPercentage <= 20)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle20.Url;
                    }
                    else if (prayerLink.currentPercentage >= 21 && prayerLink.currentPercentage <= 30)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle30.Url;
                    }
                    else if (prayerLink.currentPercentage >= 31 && prayerLink.currentPercentage <= 40)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle40.Url;
                    }
                    else if (prayerLink.currentPercentage >= 41 && prayerLink.currentPercentage <= 50)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle50.Url;
                    }
                    else if (prayerLink.currentPercentage >= 51 && prayerLink.currentPercentage <= 60)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle60.Url;
                    }
                    else if (prayerLink.currentPercentage >= 61 && prayerLink.currentPercentage <= 70)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle70.Url;
                    }
                    else if (prayerLink.currentPercentage >= 71 && prayerLink.currentPercentage <= 80)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle80.Url;
                    }
                    else if (prayerLink.currentPercentage >= 81 && prayerLink.currentPercentage <= 90)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle90.Url;
                    }
                    else if (prayerLink.currentPercentage >= 91 && prayerLink.currentPercentage <= 100)
                    {
                        prayerLink.CandleUrl = CmPrayerList.Candle100.Url;
                    }


                    //
                    IEnumerable <string> prayerSummary = sRecord.Fields[Common.NodeProperties.prayer].Split().Take(32);
                    prayerLink.PrayerSummary = string.Join(" ", prayerSummary) + "...";


                    //Obtain member
                    ContentModels.Member CmMember;
                    int memberId;
                    if (int.TryParse(sRecord.Fields[Common.NodeProperties.prayerRequestMember], out memberId))
                    {
                        IPublishedContent ipMember = memberShipHelper.GetById(memberId);
                        CmMember = new ContentModels.Member(ipMember);
                    }
                    else
                    {
                        CmMember = new ContentModels.Member(Udi.Parse(sRecord.Fields[Common.NodeProperties.prayerRequestMember]).ToPublishedContent());
                    }

                    StringBuilder sbAuthor = new StringBuilder();
                    sbAuthor.Append(CmMember.FirstName);
                    sbAuthor.Append("&nbsp;&nbsp;&nbsp;");
                    sbAuthor.Append(CmMember.LastName);
                    sbAuthor.Append(".");
                    prayerLink.MemberName = sbAuthor.ToString();


                    //
                    prayerList.lstPrayerLinks.Add(prayerLink);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"PrayerController.cs : RenderList()");
                sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(prayerList));
                Common.SaveErrorMessage(ex, sb, typeof(PrayerController));


                ModelState.AddModelError("", "*An error occured while creating the prayer list.");
                return(CurrentUmbracoPage());
            }


            //Return data to partialview
            return(PartialView("~/Views/Partials/PrayerCorner/_prayerList.cshtml", prayerList));
        }
コード例 #27
0
        public ActionResult LinkGitHub(string state, string code = null)
        {
            // Get the member of the current ID
            int memberId = Members.GetCurrentMemberId();

            if (memberId <= 0)
            {
                return(GetErrorResult("Oh noes! An error happened."));
            }

            try
            {
                IPublishedContent profilePage = Umbraco.TypedContent(1057);
                if (profilePage == null)
                {
                    return(GetErrorResult("Oh noes! This really shouldn't happen."));
                }

                // Initialize the OAuth client
                GitHubOAuthClient client = new GitHubOAuthClient
                {
                    ClientId     = WebConfigurationManager.AppSettings["GitHubClientId"],
                    ClientSecret = WebConfigurationManager.AppSettings["GitHubClientSecret"]
                };

                // Validate state - Step 1
                if (String.IsNullOrWhiteSpace(state))
                {
                    LogHelper.Info <ProfileController>("No OAuth state specified in the query string.");
                    return(GetErrorResult("No state specified in the query string."));
                }

                // Validate state - Step 2
                string session = Session["GitHub_" + state] as string;
                if (String.IsNullOrWhiteSpace(session))
                {
                    LogHelper.Info <ProfileController>("Failed finding OAuth session item. Most likely the session expired.");
                    return(GetErrorResult("Session expired? Please click the link below and try to link with your GitHub account again ;)"));
                }

                // Remove the state from the session
                Session.Remove("GitHub_" + state);

                // Exchange the auth code for an access token
                GitHubTokenResponse accessTokenResponse;
                try
                {
                    accessTokenResponse = client.GetAccessTokenFromAuthorizationCode(code);
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to retrieve access token from GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Initialize a new service instance from the retrieved access token
                var service = Skybrud.Social.GitHub.GitHubService.CreateFromAccessToken(accessTokenResponse.Body.AccessToken);

                // Get some information about the authenticated GitHub user
                GitHubGetUserResponse userResponse;
                try
                {
                    userResponse = service.User.GetUser();
                }
                catch (Exception ex)
                {
                    LogHelper.Error <ProfileController>("Unable to get user information from the GitHub API", ex);
                    return(GetErrorResult("Oh noes! An error happened."));
                }

                // Get the GitHub username from the API response
                string githubUsername = userResponse.Body.Login;

                // Get a reference to the member searcher
                BaseSearchProvider searcher = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];

                // Initialize new search criteria for the GitHub username
                ISearchCriteria criteria = searcher.CreateSearchCriteria();
                criteria = criteria.RawQuery($"github:{githubUsername}");

                // Check if there are other members with the same GitHub username
                foreach (var result in searcher.Search(criteria))
                {
                    if (result.Id != memberId)
                    {
                        LogHelper.Info <ProfileController>("Failed setting GitHub username for user with ID " + memberId + ". Username is already used by member with ID " + result.Id + ".");
                        return(GetErrorResult("Another member already exists with the same GitHub username."));
                    }
                }

                // Get the member from the member service
                var ms  = ApplicationContext.Services.MemberService;
                var mem = ms.GetById(memberId);

                // Update the "github" property and save the value
                mem.SetValue("github", githubUsername);
                mem.SetValue("githubId", userResponse.Body.Id);
                mem.SetValue("githubData", userResponse.Body.JObject.ToString());
                ms.Save(mem);

                // Clear the runtime cache for the member
                ApplicationContext.ApplicationCache.RuntimeCache.ClearCacheItem("MemberData" + mem.Username);

                // Redirect the member back to the profile page
                return(RedirectToUmbracoPage(1057));
            }
            catch (Exception ex)
            {
                LogHelper.Error <ProfileController>("Unable to link with GitHub user for member with ID " + memberId, ex);
                return(GetErrorResult("Oh noes! An error happened."));
            }
        }
コード例 #28
0
        //Search by
        private void ObtainByIlluminationStories(Models.SearchList searchList, int pageNo)
        {
            //Instantiate variables
            var memberShipHelper = new Umbraco.Web.Security.MembershipHelper(UmbracoContext.Current);

            searchList.ShowIlluminationStories = true;
            searchList.SearchInTitle           = "Illumination Stories";


            if (!string.IsNullOrWhiteSpace(searchList.SearchFor))
            {
                //Set up search criteria
                BaseSearchProvider mySearcher = ExamineManager.Instance.SearchProviderCollection[Common.searchProviders.IlluminationStoriesSearcher];
                ISearchCriteria    criteria   = mySearcher.CreateSearchCriteria(BooleanOperation.Or);


                //Setup up search fields by importance
                IBooleanOperation query = criteria.Field(Common.NodeProperties.title, searchList.SearchFor.MultipleCharacterWildcard());
                query.Or().Field(Common.NodeProperties.story, searchList.SearchFor.MultipleCharacterWildcard());
                query.Or().Field(Common.NodeProperties.experienceType, searchList.SearchFor.MultipleCharacterWildcard());
                query.Or().Field(Common.NodeProperties.member, searchList.SearchFor.MultipleCharacterWildcard());
                //IBooleanOperation query = criteria.Field(Common.NodeProperties.title, searchList.SearchFor.Boost(2));
                //query.Or().Field(Common.NodeProperties.story, searchList.SearchFor.Boost(1));
                //query.Or().Field(Common.NodeProperties.experienceType, searchList.SearchFor);
                //query.Or().Field(Common.NodeProperties.member, searchList.SearchFor);


                //Obtain result with query
                ISearchResults searchResults = mySearcher.Search(query.Compile());


                //Get item counts and total experiences.
                searchList.Pagination.totalItems = searchResults.Count();


                //Determine how many pages/items to skip and take, as well as the total page count for the search result.
                if (searchList.Pagination.totalItems > searchList.Pagination.itemsPerPage)
                {
                    searchList.Pagination.totalPages = (int)Math.Ceiling((double)searchList.Pagination.totalItems / (double)searchList.Pagination.itemsPerPage);
                }
                else
                {
                    searchList.Pagination.itemsPerPage = searchList.Pagination.totalItems;
                    searchList.Pagination.totalPages   = 1;
                }


                //Determine current page number
                if (pageNo <= 0 || pageNo > searchList.Pagination.totalPages)
                {
                    pageNo = 1;
                }
                searchList.Pagination.pageNo = pageNo;


                //Determine how many pages/items to skip
                if (searchList.Pagination.totalItems > searchList.Pagination.itemsPerPage)
                {
                    searchList.Pagination.itemsToSkip = searchList.Pagination.itemsPerPage * (pageNo - 1);
                }


                //Convert list of SearchResults to list of classes
                foreach (SearchResult sRecord in searchResults.Skip(searchList.Pagination.itemsToSkip).Take(searchList.Pagination.itemsPerPage))
                {
                    var storyLink = new Models.illuminationStoryLink();
                    storyLink.experienceType = sRecord.Fields[Common.NodeProperties.experienceType];
                    storyLink.id             = sRecord.Id;
                    storyLink.title          = sRecord.Fields[Common.NodeProperties.title];
                    storyLink.url            = Umbraco.NiceUrl(sRecord.Id);


                    //Obtain member
                    ContentModels.Member CmMember;
                    int memberId;
                    if (int.TryParse(sRecord.Fields[Common.NodeProperties.member], out memberId))
                    {
                        IPublishedContent ipMember = memberShipHelper.GetById(memberId);
                        CmMember = new ContentModels.Member(ipMember);
                    }
                    else
                    {
                        CmMember = new ContentModels.Member(Udi.Parse(sRecord.Fields[Common.NodeProperties.member]).ToPublishedContent());
                    }
                    //var CmMember = new ContentModels.Member(Udi.Parse(sRecord.Fields[Common.NodeProperties.member]).ToPublishedContent());


                    StringBuilder sbAuthor = new StringBuilder();
                    sbAuthor.Append(CmMember.FirstName);
                    sbAuthor.Append("&nbsp;&nbsp;&nbsp;");
                    sbAuthor.Append(CmMember.LastName);
                    sbAuthor.Append(".");
                    storyLink.memberName = sbAuthor.ToString();
                    storyLink.memberId   = CmMember.Id;

                    searchList.lstStoryLink.Add(storyLink);
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Executes the search.
        /// </summary>
        /// <returns>The <see cref="SearchResponse"/> containing the search results.</returns>
        public SearchResponse Execute()
        {
            SearchResponse     searchResponse = new SearchResponse();
            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection[SearchConstants.SearcherName];

            IBooleanOperation searchCriteria = searchProvider.CreateSearchCriteria().OrderBy(string.Empty);

            if (!string.IsNullOrWhiteSpace(this.Query))
            {
                searchCriteria = searchProvider
                                 .CreateSearchCriteria()
                                 .GroupedOr(SearchConstants.MergedDataField.AsEnumerableOfOne(),
                                            this.Query.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(w => w.Trim().MultipleCharacterWildcard())
                                            .ToArray());
            }

            if (this.Categories.Any())
            {
                searchCriteria.And().Field(SearchConstants.CategoryField, string.Join(" ", this.Categories));
            }

            if (searchCriteria != null)
            {
                ISearchResults searchResults = null;
                try
                {
                    searchResults = searchProvider.Search(searchCriteria.Compile());
                }
                catch (NullReferenceException)
                {
                    // If the query object can't be compiled then an exception within Examine is raised
                }

                if (searchResults != null)
                {
                    Analyzer  analyzer  = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
                    Formatter formatter = new SimpleHTMLFormatter("<strong>", "</strong>");

                    foreach (SearchResult searchResult in searchResults.OrderByDescending(x => x.Score))
                    {
                        // Check to see if the result is culture specific.
                        // This is a bit hacky but there is no way with property wrappers like Vorto to separate the results into
                        // different indexes so we have to fall back to regular expressions.
                        string       fieldResult = searchResult.Fields[SearchConstants.MergedDataField];
                        RegexOptions options     = RegexOptions.IgnoreCase | RegexOptions.Multiline;

                        string opts = $"({string.Join("|", this.Query.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries))})";

                        // First check to see if there is any matches for any installed languages and remove any
                        // That are not in our culture collection.
                        // ReSharper disable once LoopCanBeConvertedToQuery
                        foreach (Language language in this.languages)
                        {
                            if (!this.Cultures.Contains(language.CultureInfo))
                            {
                                fieldResult = Regex.Replace(
                                    fieldResult,
                                    string.Format(SearchConstants.CultureRegexTemplate, language.IsoCode, opts),
                                    string.Empty,
                                    options);
                            }
                        }

                        // Now clean up the languages we do have a result for.
                        MatchCollection matches = AllCultureRegex.Matches(fieldResult);

                        foreach (Match match in matches)
                        {
                            if (match.Success)
                            {
                                string replacement = match.Groups["replacement"].Value;

                                fieldResult = Regex.Replace(
                                    fieldResult,
                                    Regex.Escape(match.Value),
                                    replacement + " ",
                                    options);
                            }
                        }

                        // Now check to see if we have any match left over. If not, break out.
                        if (!new Regex(string.Format(SearchConstants.QueryRegexTemplate, opts), options).Match(fieldResult).Success)
                        {
                            continue;
                        }

                        this.AddSearchMatch(analyzer, formatter, searchResults, searchResponse, searchResult, fieldResult);
                    }

                    searchResponse.TotalCount = searchResponse.SearchMatches.Count;
                }
            }

            return(searchResponse);
        }
コード例 #30
0
ファイル: CachedQueryBase.cs プロジェクト: vonbv/Merchello
        /// <summary>
        /// Performs a Lucene "cache" only search
        /// </summary>
        /// <param name="criteria">
        /// The criteria.
        /// </param>
        /// <param name="mapper">
        /// The mapper.
        /// </param>
        /// <typeparam name="T">
        /// The type of results to be returned
        /// </typeparam>
        /// <returns>
        /// The collection of T.
        /// </returns>
        public IEnumerable <T> CachedSearch <T>(ISearchCriteria criteria, Func <SearchResult, T> mapper)
        {
            var results = _searchProvider.Search(criteria);

            return(results.Select(mapper));
        }