Exemple #1
0
        /// <summary>
        /// Performs a search using the specified <paramref name="options"/>.
        /// </summary>
        /// <param name="operation">The boolean operation the search should be based on.</param>
        /// <param name="options">The options specyfing how the results should be sorted.</param>
        /// <param name="results">The results of the search.</param>
        /// <param name="total">The total amount of results returned by the search.</param>
        protected virtual void Execute(IBooleanOperation operation, ISearchOptions options, out IEnumerable <ISearchResult> results, out long total)
        {
            // Cast the boolean operation to IQueryExecutor
            IQueryExecutor executor = operation;

            // Start the search in Examine
            ISearchResults allResults = executor.Execute(int.MaxValue);

            // Update the total amount of results
            total = allResults.TotalItemCount;

            results = allResults;

            // If "options" implements the interface, results are sorted using the "Sort" method
            if (options is IPostSortOptions postSort)
            {
                results = postSort.Sort(results);
            }

            // If "options" implements implement the interface, the results are paginated
            if (options is IOffsetOptions offset)
            {
                results = results.Skip(offset.Offset).Take(offset.Limit);
            }
        }
Exemple #2
0
        /// <summary>
        /// Performs a lucene search using Examine.
        /// </summary>
        /// <param name="documentTypes">Array of document type aliases to search for.</param>
        /// <param name="searchGroups">A list of search groupings, if you have more than one group it will apply an and to the search criteria</param>
        /// <returns>Examine search results</returns>
        public Examine.ISearchResults SearchUsingExamine(string[] documentTypes, List <SearchGroup> searchGroups)
        {
            if (!ExamineManager.Instance.TryGetIndex("ExternalIndex", out var index))
            {
                throw new InvalidOperationException($"No index found by name 'External Index'");
            }

            var searcher = index.GetSearcher();

            var searchCriteria = searcher.CreateQuery(IndexTypes.Content);

            //only shows results for visible documents.
            IBooleanOperation queryNodes = searchCriteria.GroupedOr(new string[] { "umbracoNaviHide" }, "0", "");

            if (documentTypes != null && documentTypes.Length > 0)
            {
                //only get results for documents of a certain type - changed And() to Or()
                queryNodes = queryNodes.And().GroupedOr(new string[] { _docTypeAliasFieldName }, documentTypes);
            }

            if (searchGroups != null && searchGroups.Any())
            {
                //in each search group it looks for a match where the specified fields contain any of the specified search terms
                //usually would only have 1 search group, unless you want to filter out further, i.e. using categories as well as search terms
                foreach (SearchGroup searchGroup in searchGroups)
                {
                    queryNodes = queryNodes.And().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms);
                }
            }
            //return the results of the search
            return(queryNodes.Execute());
        }
Exemple #3
0
        /// <summary>
        /// Performs a lucene search using Examine.
        /// </summary>
        /// <param name="documentTypes">Array of document type aliases to search for.</param>
        /// <param name="searchGroups">A list of search groupings, if you have more than one group it will apply an and to the search criteria</param>
        /// <returns>Examine search results</returns>
        public Examine.ISearchResults SearchUsingExamine(string[] documentTypes, List <SearchGroup> searchGroups)
        {
            ISearchCriteria   searchCriteria = ExamineManager.Instance.CreateSearchCriteria(BooleanOperation.And);
            IBooleanOperation queryNodes     = null;

            //only shows results for visible documents.
            queryNodes = searchCriteria.GroupedNot(new string[] { "umbracoNaviHide" }, "1");

            if (documentTypes != null && documentTypes.Length > 0)
            {
                //only get results for documents of a certain type
                queryNodes = queryNodes.And().GroupedOr(new string[] { _docTypeAliasFieldName }, documentTypes);
            }

            if (searchGroups != null && searchGroups.Any())
            {
                //in each search group it looks for a match where the specified fields contain any of the specified search terms
                //usually would only have 1 search group, unless you want to filter out further, i.e. using categories as well as search terms
                foreach (SearchGroup searchGroup in searchGroups)
                {
                    queryNodes = queryNodes.And().GroupedOr(searchGroup.FieldsToSearchIn, searchGroup.SearchTerms);
                }
            }

            //return the results of the search
            return(ExamineManager.Instance.Search(queryNodes.Compile()));;
        }
Exemple #4
0
        public static IEnumerable <SearchResult> GetExamineResultsForNodeTypeAlias(string nodeTypeAlias)
        {
            try
            {
                var examineprovider = ExamineManager.Instance.SearchProviderCollection[UwebshopConfiguration.Current.ExamineSearcher];
                if (examineprovider != null)
                {
                    var searcher = examineprovider.CreateSearchCriteria();
                    if (searcher != null)
                    {
                        IBooleanOperation query = searcher.Field("__NodeTypeAlias", nodeTypeAlias.ToLower().MultipleCharacterWildcard());

                        //Log.Instance.LogDebug(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + " EXAMINE GetObjectsByAlias<T> " + typeof(T).Name);
                        var searchResults = examineprovider.Search(query.Compile());
                        return(searchResults.Where(examineNode => examineNode.Fields["__NodeId"] != null).Where(examineNode => CheckNodeTypeAliasForImproperOverlap(examineNode.Fields["__NodeTypeAlias"], nodeTypeAlias)));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Instance.LogError(ex, "Error while searching Examine for type with alias " + nodeTypeAlias);
            }

            return(null);
        }
 private static IFieldSelectableOrdering ToFieldSelectableOrdering(IBooleanOperation booleanOp)
 {
     if (booleanOp is IFieldSelectableOrdering fieldSelectableQuery)
     {
         return(fieldSelectableQuery);
     }
     throw new NotSupportedException("IFieldSelectableQuery is not supported");
 }
        /// <summary>
        /// Get the results for the given query
        /// </summary>
        public ISearchResults Search(IBooleanOperation query, out int totalResults)
        {
            var searchResult = query.Execute();

            totalResults = (int)searchResult.TotalItemCount;

            return(searchResult);
        }
        /// <summary>
        /// Get paged results for the given query
        /// </summary>
        public IEnumerable <ISearchResult> Page(IBooleanOperation query, int page, int perPage, out int totalResults)
        {
            var searchResult = Search(query, out totalResults);

            var pagedResult = searchResult
                              .Skip((page - 1) * perPage)
                              .Take(perPage);

            return(pagedResult);
        }
        /// <summary>
        /// Get the results for the given query
        /// </summary>
        public IEnumerable <T> Search <T>(IBooleanOperation query, out int totalResults)
            where T : class, IPublishedContent
        {
            var searchResult = query.Execute();

            totalResults = (int)searchResult.TotalItemCount;

            var typedResult = searchResult.GetResults <T>();

            return(typedResult);
        }
        private void AddGroupedCriteria(ref IBooleanOperation filter, string field, string value)
        {
            string[] values = value.Split(',');
            var      fields = new string[values.Length];

            for (var i = 0; i < values.Length; i++)
            {
                fields[i] = field;
            }
            filter.And().GroupedOr(fields, values);
        }
        /// <summary>
        /// Get paged results for the given query
        /// </summary>
        public IEnumerable <T> Page <T>(IBooleanOperation query, int page, int perPage, out int totalResults)
            where T : class, IPublishedContent
        {
            var searchResult = Search(query, out totalResults);

            var pagedResult = searchResult
                              .Skip((page - 1) * perPage)
                              .GetResults <T>()
                              .Take(perPage);

            return(pagedResult);
        }
        /// <summary>
        /// Get the results for the given query
        /// </summary>
        public IEnumerable <T> Search <T>(IBooleanOperation query, out int totalResults)
            where T : class, IPublishedContent
        {
            var searchResult = query.Execute();

            totalResults = (int)searchResult.TotalItemCount;

            var typedResult = searchResult
                              .ToPublishedSearchResults(_publishedSnapshotAccessor.PublishedSnapshot.Content)
                              .Select(x => x.Content as T)
                              .Where(x => x != null);

            return(typedResult);
        }
        /// <summary>
        /// Get paged results for the given query
        /// </summary>
        public IEnumerable <T> Page <T>(IBooleanOperation query, int page, int perPage, out int totalResults)
            where T : class, IPublishedContent
        {
            var searchResult = Search(query, out totalResults);

            var pagedResult = searchResult
                              .Skip((page - 1) * perPage)
                              .ToPublishedSearchResults(_publishedSnapshotAccessor.PublishedSnapshot.Content)
                              .Select(x => x.Content as T)
                              .Where(x => x != null)
                              .Take(perPage);

            return(pagedResult);
        }
Exemple #13
0
        /// <summary>
        /// Performs a search using the specified <paramref name="sortOptions"/>.
        /// </summary>
        /// <param name="operation">The boolean operation the search should be based on.</param>
        /// <param name="sortOptions">The sort options specyfing how the results should be sorted.</param>
        /// <param name="results">The results of the search.</param>
        /// <param name="total">The total amount of results returned by the search.</param>
        protected virtual void Execute(IBooleanOperation operation, ISortOptions sortOptions, out IEnumerable <ISearchResult> results, out long total)
        {
            // Cast the boolean operation to IQueryExecutor
            IQueryExecutor executor = operation;

            // If "SortField" doesn't specified, we don't apply any sorting
            if (!string.IsNullOrWhiteSpace(sortOptions.SortField))
            {
                switch (sortOptions.SortOrder)
                {
                case SortOrder.Ascending:
                    executor = operation.OrderBy(new SortableField(sortOptions.SortField, sortOptions.SortType));
                    break;

                case SortOrder.Descending:
                    executor = operation.OrderByDescending(new SortableField(sortOptions.SortField, sortOptions.SortType));
                    break;

                default:
                    throw new Exception($"Unsupported sort order: {sortOptions.SortOrder}");
                }
            }

            if (sortOptions is IOffsetOptions offset)
            {
                ISearchResults allResults = executor.Execute();

                // Update the total amount of results
                total = allResults.TotalItemCount;

                // Apply limit and offset
                results = allResults
                          .Skip(offset.Offset)
                          .Take(offset.Limit);
            }
            else
            {
                // Since no offset or limit is specified, we request all results
                ISearchResults allResults = executor.Execute(int.MaxValue);

                // Update the total amount of results
                total = allResults.TotalItemCount;

                // Update "results" with the value of "allResults" as we're not filtering the results
                results = allResults;
            }
        }
        /// <summary>
        /// Metoda zwracająca klasę zawierającą elementy wyświetlane na stronie głównej BIP
        /// </summary>
        /// <param name="model">model BIPPageViewModel</param>
        /// <returns>Model zawierający elementy strony głównej BIP</returns>
        public BIPPageViewModel BIPPageViewModel(BIPPageViewModel model)
        {
            var _currentPage = _umbracoHelper.TypedContent(model.CurrentUmbracoPageId);
            var _bipPage     = new BIP(_currentPage);

            if (!string.IsNullOrEmpty(model.SearchText))
            {
                var _searcher             = ExamineManager.Instance.SearchProviderCollection["BipContentSearchSearcher"];
                var _searchCriteria       = _searcher.CreateSearchCriteria(Examine.SearchCriteria.BooleanOperation.Or);
                var q_split               = model.SearchText.Split(' ');
                var _fieldsToSearch       = new[] { "pageTitle", "articleTitle", "articleText", "pageMainTitle", "pageMainDescription", "nodeName" };
                IBooleanOperation _filter = _searchCriteria.GroupedOr(_fieldsToSearch, q_split.First());
                foreach (var term in q_split.Skip(1))
                {
                    _filter = _filter.Or().GroupedOr(_fieldsToSearch, term);
                }
                var _searchResults        = _searcher.Search(_filter.Compile()).OrderByDescending(x => x.Score);
                var _resultBipFormIds     = _searchResults.Where(q => q.Fields["nodeTypeAlias"] == DocumentTypeEnum.bIPForm.ToString()).Select(q => q.Id);
                var _resultBipArticlesIds = _searchResults.Where(q => q.Fields["nodeTypeAlias"] == DocumentTypeEnum.articleBip.ToString()).Select(q => q.Id);

                model.ItemList.AddRange(_bipPage.Descendants(DocumentTypeEnum.bIPForm.ToString()).Where(q => _resultBipFormIds.Contains(q.Id)).Select(q => new BIpform(q)).Select(q => new BipListItemModel()
                {
                    CreateDate = q.CreateDate, Url = q.Url, Description = removeHtmlTag(q.PageMainDescription.ToString()), Title = q.PageMainTitle
                }));
                model.ItemList.AddRange(_bipPage.Descendants(DocumentTypeEnum.articleBip.ToString()).Where(q => _resultBipArticlesIds.Contains(q.Id)).Select(q => new ArticleBip(q)).Select(q => new BipListItemModel()
                {
                    CreateDate = q.CreateDate, Url = q.Url, Description = removeHtmlTag(q.ArticleText.ToString()), Title = q.ArticleTitle
                }));
            }
            else
            {
                var _bipForms    = _bipPage.Descendants(DocumentTypeEnum.bIPForm.ToString()).Select(q => new BIpform(q));
                var _bipArticles = _bipPage.Descendants(DocumentTypeEnum.articleBip.ToString()).Select(q => new ArticleBip(q));

                model.ItemList.AddRange(_bipForms.Select(q => new BipListItemModel()
                {
                    CreateDate = q.CreateDate, Url = q.Url, Description = removeHtmlTag(q.PageMainDescription.ToString()), Title = q.PageMainTitle
                }));
                model.ItemList.AddRange(_bipArticles.Select(q => new BipListItemModel()
                {
                    CreateDate = q.CreateDate, Url = q.Url, Description = removeHtmlTag(q.ArticleText.ToString()), Title = q.ArticleTitle
                }));
            }

            return(model);
        }
Exemple #15
0
        public IEnumerable <T> GetAll <T>(string doctypeAlias, int?maxResults = null, bool inCurrentSite = true)
            where T : class, IPublishedContent
        {
            IBooleanOperation operation = Searcher.CreateSearchCriteria().NodeTypeAlias(doctypeAlias);

            if (inCurrentSite)
            {
                int?homepageId = UmbracoContext.Current?.PublishedContentRequest?.PublishedContent?.AncestorOrSelf <Home>()?.Id;
                if (homepageId != null)
                {
                    operation.And().Field("@homepageId", homepageId.ToString());
                }
            }

            ISearchCriteria criteria      = operation.Compile();
            ISearchResults  searchResults = maxResults.HasValue ? Searcher.Search(criteria, maxResults.Value) : Searcher.Search(criteria);

            return(searchResults.Select(sr => UmbracoHelper.TypedContent(sr.Id) as T));
        }
Exemple #16
0
        /// <summary>
        /// Performs a search using the specified <paramref name="options"/> and returns the result of that search.
        /// </summary>
        /// <param name="options">The options for the search.</param>
        /// <returns>An instance of <see cref="SearchResultList"/> representing the result of the search.</returns>
        public virtual SearchResultList Search(ISearchOptions options)
        {
            // Start measuring the elapsed time
            Stopwatch sw = Stopwatch.StartNew();

            // Get the searcher from the options
            ISearcher searcher = GetSearcher(options);

            // Create a new Examine query
            IQuery query = CreateQuery(searcher, options);

            // Get the boolean operation via the options class
            IBooleanOperation operation = options.GetBooleanOperation(this, searcher, query);

            // Declare some variables
            long total;
            IEnumerable <ISearchResult> results;

            switch (options)
            {
            case IExecuteOptions execute:
                execute.Execute(operation, out results, out total);
                break;

            case ISortOptions sortOptions:
                Execute(operation, sortOptions, out results, out total);
                break;

            default:
                Execute(operation, options, out results, out total);
                break;
            }

            sw.Stop();

            if (options is IDebugSearchOptions debug && debug.IsDebug)
            {
                _logger.Debug <SearchHelper>("Search of type {Type} completed in {Milliseconds} with {Query}", options.GetType().FullName, sw.ElapsedMilliseconds, query);
            }

            // Wrap the results
            return(new SearchResultList(options, query, total, results));
        }
        public void FluentApiTests_Cws_TextPage_OrderedByNodeName()
        {
            var criteria            = _searcher.CreateSearchCriteria("content");
            IBooleanOperation query = criteria.NodeTypeAlias("cws_textpage");

            query = query.And().OrderBy("nodeName");
            var sCriteria = query.Compile();

            Console.WriteLine(sCriteria.ToString());
            var results = _searcher.Search(sCriteria);

            criteria = _searcher.CreateSearchCriteria("content");
            IBooleanOperation query2 = criteria.NodeTypeAlias("cws_textpage");

            query2 = query2.And().OrderByDescending("nodeName");
            var sCriteria2 = query2.Compile();

            Console.WriteLine(sCriteria2.ToString());
            var results2 = _searcher.Search(sCriteria2);

            Assert.AreNotEqual(results.First().Id, results2.First().Id);
        }
Exemple #18
0
        public static IEnumerable <SearchResult> GetExamineResultsForNodeTypeAlias(string nodeTypeAlias)
        {
            try
            {
                var examineprovider = ExamineManager.Instance.SearchProviderCollection[UwebshopConfiguration.Current.ExamineSearcher];
                if (examineprovider != null)
                {
                    var searcher = examineprovider.CreateSearchCriteria();
                    if (searcher != null)
                    {
                        IBooleanOperation query = searcher.Field("__NodeTypeAlias", nodeTypeAlias.ToLower());
                        var searchResults       = examineprovider.Search(query.Compile());
                        return(searchResults.Where(examineNode => examineNode.Fields["__NodeId"] != null));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Instance.LogError(ex, "Error while searching Examine for type with alias " + nodeTypeAlias);
            }

            return(Enumerable.Empty <SearchResult>());
        }
 public IQuery WithOperation(IBooleanOperation operation)
 {
     _operation = (BaseOperation)operation;
     return(this);
 }
        public async Task <ActionResult> GetAgents(int iPageno, string sSortName, string sAgentId, string sCategory, string sService, string sCity)
        {
            int iPageSize = Convert.ToInt32(StringConstants.PAGE_SIZE);
            PagedAgentCMSView pagedView = new PagedAgentCMSView();

            try
            {
                if (Request.IsAjaxRequest())
                {
                    //AdvSearchModel srchModel = new AdvSearchModel();
                    var searcher = Examine.ExamineManager.Instance.SearchProviderCollection[StringConstants.EXMINE_MEM_SEARCHER_NAME];
                    IEnumerable <SearchResult> pagedResults;
                    IBooleanOperation          query = GetCriteria(sAgentId, sCategory, sService, sCity, ref searcher);

                    //Get the search result
                    var results = searcher.Search(query.Compile());

                    if (results.Count() > 0)
                    {
                        pagedView.TotalRecords = results.Count();
                    }
                    else
                    {
                        pagedView.TotalRecords = 0;
                    }

                    pagedResults = results.Skip((iPageno - 1) * iPageSize).Take(iPageSize);


                    if (pagedResults.Count() > 0)
                    {
                        //Prepare Property Models to be displayed on the result page
                        List <AgentViewCMSModel> properties = new List <AgentViewCMSModel>();
                        foreach (var result in pagedResults)
                        {
                            AgentViewCMSModel item = new AgentViewCMSModel();

                            //IMember member = Services.MemberService.GetById(Convert.ToInt32(result.Fields["id"]));

                            IPublishedContent node = Members.GetById(Convert.ToInt32(result.Fields["id"]));

                            item = MapNodeToModel(node);

                            properties.Add(item);
                        }
                        pagedView.CMSAgents = properties;
                    }
                }

                pagedView.TotalPages  = Convert.ToInt32(Math.Ceiling((double)pagedView.TotalRecords / iPageSize));
                pagedView.CurrentPage = iPageno;

                SetPagingValues(ref pagedView);

                PagedPropertyViews pagedresults = new PagedPropertyViews();

                //PagedPropertyCMSView pgrslt = new PagedPropertyCMSView();
                return(PartialView(StringConstants.PARTIAL_VIEW_PATH + PARTIAL_VIEW_LIST, await System.Threading.Tasks.Task.FromResult(pagedView)));
            }
            catch (Exception x)
            {
                //log the error
                return(null);
            }
        }
Exemple #21
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);
        }
Exemple #22
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);
        }
Exemple #23
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));
        }
Exemple #24
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));
        }
        //
        private IBooleanOperation GetCriteria(string sAgentId, string sCategory, string sService, string sCity, ref BaseSearchProvider searcher)
        {
            Dictionary <string, string> values    = new Dictionary <string, string>();
            AgentViewCMSModel           srchModel = new AgentViewCMSModel();


            var searchCriteria = searcher.CreateSearchCriteria(BooleanOperation.And);

            IBooleanOperation query = null;

            try
            {
                //Built the exmine query
                query = searchCriteria.Field(srchModel.TYPE_PROPERTY_NAME, "Agent");

                if (sAgentId != null && sAgentId != "")
                {
                    if (query == null)
                    {
                        //query = searchCriteria.Field(srchModel.NAME_PROPERTY_NAME, sAgentId);
                        query = searchCriteria.Field(srchModel.ID_PROPERTY_NAME, sAgentId);
                    }
                    else
                    {
                        query = query.And().Field(srchModel.ID_PROPERTY_NAME, sAgentId);
                    }
                }


                if (sCategory != null && sCategory != "")
                {
                    if (query == null)
                    {
                        query = searchCriteria.Field(srchModel.CATEGORY_PROPERTY_NAME, sCategory);
                    }
                    else
                    {
                        query = query.And().Field(srchModel.CATEGORY_PROPERTY_NAME, sCategory);
                    }
                }


                //sService

                if (sService != null && sService != "")
                {
                    if (query == null)
                    {
                        query = searchCriteria.Field(srchModel.SERVICE_PROPERTY_NAME, sService);
                    }
                    else
                    {
                        query = query.And().Field(srchModel.SERVICE_PROPERTY_NAME, sService);
                    }
                }
                //, sDevhold
                if (sCity != null && sCity != "")
                {
                    if (query == null)
                    {
                        query = searchCriteria.Field(srchModel.CITY_PROPERTY_NAME, sCity);
                    }
                    else
                    {
                        query = query.And().Field(srchModel.CITY_PROPERTY_NAME, sCity);
                    }
                }

                //If no criteria was provided from page.

                return(query);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        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));
        }
        public static IOrdering SelectFirstFieldOnly(this IBooleanOperation searchQuery)
        {
            var fieldQuery = ToFieldSelectableOrdering(searchQuery);

            return(fieldQuery.SelectFirstFieldOnly());
        }
        private IEnumerable <ISearchResult> PerformExamineSearch(long pageIndex, int pageSize, out long totalRecords,
                                                                 string orderBy, Direction orderDirection,
                                                                 string memberTypeAlias, IEnumerable <int> groups,
                                                                 string filter,
                                                                 IDictionary <string, string> additionalFilters = null,
                                                                 bool?isApproved = null, bool?isLockedOut = null)
        {
            if (!(InitialiseMemberQuery() is IQuery query))
            {
                totalRecords = 0;
                return(Enumerable.Empty <ISearchResult>());
            }

            IBooleanOperation op = null;

            if (!memberTypeAlias.IsNullOrWhiteSpace())
            {
                op = query.NodeTypeAlias(memberTypeAlias);
            }

            if (groups?.Any() ?? false)
            {
                // Get group names from ids.
                var groupNames = memberGroupService.GetByIds(groups).Select(x => x.Name);
                if (groupNames.Any())
                {
                    // Keywords need to be all lowercase for Examine 2.0
                    op = query.And(op).GroupedOr(new[] { Constants.Members.Groups }, groupNames.Select(g => new ExamineValue(Examineness.Escaped, g.ToLower())).Cast <IExamineValue>().ToArray());
                }
            }

            if (isApproved.HasValue)
            {
                op = query.And(op).BooleanField(Conventions.Member.IsApproved, isApproved.Value);
            }

            if (isLockedOut.HasValue)
            {
                op = query.And(op).BooleanField(Conventions.Member.IsLockedOut, isLockedOut.Value);
            }

            var basicFields = new List <string>()
            {
                "id", "__NodeId", "__Key", "email", "loginName"
            };

            var filterParameters = additionalFilters.Where(q => q.Key.StartsWith("f_") && !string.IsNullOrWhiteSpace(q.Value));

            //build a lucene query
            if (op == null && string.IsNullOrWhiteSpace(filter) && !filterParameters.Any())
            {
                // Generic get everything (theoretically we shouldn't even get here)...
                op = query.NativeQuery("a* b* c* d* e* f* g* h* i* j* k* l* m* n* o* p* q* r* s* t* u* v* w* x* y* z*");
            }
            else
            {
                if (!filter.IsNullOrWhiteSpace())
                {
                    // the __nodeName will be boosted 10x without wildcards
                    // then __nodeName will be matched normally with wildcards
                    // the rest will be normal without wildcards
                    if (!string.IsNullOrWhiteSpace(filter))
                    {
                        var sb = new StringBuilder();
                        sb.Append("+(");
                        //node name exactly boost x 10
                        sb.AppendFormat("__nodeName:{0}^10.0 ", filter.ToLower());

                        //node name normally with wildcards
                        sb.AppendFormat(" __nodeName:{0}* ", filter.ToLower());

                        foreach (var field in basicFields)
                        {
                            //additional fields normally
                            sb.AppendFormat("{0}:{1} ", field, filter);
                        }
                        sb.Append(")");
                        op = query.And(op).NativeQuery(sb.ToString());
                    }
                }


                // Now specific field searching. - these should be ANDed and grouped.
                foreach (var qs in filterParameters)
                {
                    string alias = qs.Key;
                    if (alias.StartsWith("f_"))
                    {
                        alias = qs.Key.Substring(2);
                    }

                    var values = qs.Value.Split(',');
                    if (values.Length > 0)
                    {
                        op = query.And(op).GroupedOr(new[] { alias }, values);
                    }
                }
            }


            //// Order the results
            // Examine Sorting seems too unreliable, particularly on nodeName
            IOrdering ordering;

            if (orderDirection == Direction.Ascending)
            {
                ordering = op.OrderBy(new SortableField(orderBy.ToLower() == "name" ? "nodeName" : orderBy, SortType.String));
            }
            else
            {
                ordering = op.OrderByDescending(new SortableField(orderBy.ToLower() == "name" ? "nodeName" : orderBy, SortType.String));
            }

#if NET5_0_OR_GREATER
            QueryOptions options = new(0, (int)(pageSize * (pageIndex + 1)));
            var          results = ordering.Execute(options);
#else
            var results = ordering.Execute((int)(pageSize * (pageIndex + 1)));
#endif
            totalRecords = results.TotalItemCount;


            if (pageSize > 0)
            {
                int skipCount = (pageIndex > 0 && pageSize > 0) ? Convert.ToInt32((pageIndex - 1) * pageSize) : 0;
                if (totalRecords < skipCount)
                {
                    skipCount = (int)totalRecords / pageSize;
                }

                return(results.Skip(skipCount).Take(pageSize));
            }

            return(results);
        }
Exemple #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);
        }
        public static IOrdering SelectFields(this IBooleanOperation booleanOp, ISet <string> fieldNames)
        {
            var fieldQuery = ToFieldSelectableOrdering(booleanOp);

            return(fieldQuery.SelectFields(fieldNames));
        }