Exemplo n.º 1
0
        public void test_with_write_and_delete_document()
        {
            var lueceneSearchProvider = new BaseSearchProvider();

            var spaceOne = new SpaceObject
            {
                Id = Guid.NewGuid(),
                SpaceName = "技术空间",
                FileCount = 1,
                ParentId = Guid.NewGuid().ToString(),
                SpaceSize = 1024,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                CreateUserId = "5",
                CreateUserName = "******",
            };

            Stopwatch stopWatcher = new Stopwatch();
            stopWatcher.Start();

            lueceneSearchProvider.IndexDirectory = "write_delete_space";
            lueceneSearchProvider.Add(spaceOne);

            var results = lueceneSearchProvider.Query<SpaceObject>("空间");
            Assert.IsTrue(results.Count>= 1);

            lueceneSearchProvider.Delete(spaceOne);
            results = lueceneSearchProvider.Query<SpaceObject>("空间");
            Assert.AreEqual(results.Count, 0);

            Console.WriteLine(results.Count);
        }
Exemplo n.º 2
0
        public void should_query_with_special_string()
        {
            BaseSearchProvider lueceneBaseSearchProvider = new BaseSearchProvider();

            var spaceOne = new SpaceObject
            {
                Id = Guid.NewGuid(),
                SpaceName = "技术空间",
                FileCount = 1,
                ParentId = Guid.NewGuid().ToString(),
                SpaceSize = 1024,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                CreateUserId = "5",
                CreateUserName = "******",

            };
            lueceneBaseSearchProvider.Add(spaceOne);

            var results = lueceneBaseSearchProvider.Query<SpaceObject>("*****");
            Assert.AreEqual(results.Count, 0);

            results = lueceneBaseSearchProvider.Query<SpaceObject>("#@RF**__++||");
            Assert.AreEqual(results.Count, 0);

            results = lueceneBaseSearchProvider.Query<SpaceObject>(" || __    ");
            Assert.AreEqual(results.Count, 0);
        }
Exemplo n.º 3
0
        public void should_query_with_null_query()
        {
            BaseSearchProvider lueceneBaseSearchProvider = new BaseSearchProvider();

            string query = null;
            var results = lueceneBaseSearchProvider.Query<SpaceObject>(query);
            Assert.AreEqual(results.Count, 0);
        }
Exemplo n.º 4
0
        public void should_query_with_empty_string()
        {
            BaseSearchProvider lueceneBaseSearchProvider = new BaseSearchProvider();

            var results = lueceneBaseSearchProvider.Query<SpaceObject>(string.Empty);
            Assert.AreEqual(results.Count, 0);

            results = lueceneBaseSearchProvider.Query<SpaceObject>("      ");
            Assert.AreEqual(results.Count, 0);
        }
Exemplo n.º 5
0
        public 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);
        }
Exemplo n.º 6
0
        /// <summary>
        /// BaseSearchProvider extension to build search criteria
        /// </summary>
        /// <param name="provider">
        /// The provider.
        /// </param>
        /// <param name="searchTerm">
        /// The search term.
        /// </param>
        /// <param name="fields">
        /// The fields.
        /// </param>
        /// <returns>
        /// The <see cref="ISearchCriteria"/>.
        /// </returns>
        internal static ISearchCriteria BuildCriteria(this BaseSearchProvider provider, string searchTerm, string[] fields)
        {
            var criteria = provider.CreateSearchCriteria(BooleanOperation.Or);

            return(BuildQuery(searchTerm, criteria, fields));
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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));
        }
Exemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
 /// </summary>
 /// <param name="service">
 /// The service.
 /// </param>
 /// <param name="indexProvider">
 /// The index provider.
 /// </param>
 /// <param name="searchProvider">
 /// The search provider.
 /// </param>
 /// <param name="enableDataModifiers">
 /// A value indicating whether or not data modifiers are enabled.
 /// </param>
 public CachedProductQuery(IPageCachedService <IProduct> service, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers)
     : base(service, indexProvider, searchProvider, enableDataModifiers)
 {
     _productService = (ProductService)service;
     this.Initialize();
 }
Exemplo n.º 10
0
 /// <summary>
 /// Generally used for unit testing to use an explicit examine searcher
 /// </summary>
 /// <param name="searchProvider"></param>
 /// <param name="indexProvider"></param>
 internal DefaultPublishedMediaStore(BaseSearchProvider searchProvider, BaseIndexProvider indexProvider)
 {
     _searchProvider = searchProvider;
     _indexProvider  = indexProvider;
 }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
 private AsyncContentListController()
 {
     _helper           = new UmbracoHelper(UmbracoContext.Current);
     _ExternalSearcher = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"];
 }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
 /// </summary>
 /// <param name="service">
 /// The service.
 /// </param>
 /// <param name="indexProvider">
 /// The index provider.
 /// </param>
 /// <param name="searchProvider">
 /// The search provider.
 /// </param>
 public CachedProductQuery(IPageCachedService <IProduct> service, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider)
     : base(service, indexProvider, searchProvider)
 {
     _productService = (ProductService)service;
 }
Exemplo n.º 14
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."));
            }
        }
        protected override ApiController CreateController(Type controllerType, HttpRequestMessage msg, UmbracoHelper helper, ITypedPublishedContentQuery qry, ServiceContext serviceContext, BaseSearchProvider searchProvider)
        {
            _onServicesCreated(msg, helper.UmbracoContext, qry, serviceContext, searchProvider);

            //Create the controller with all dependencies
            var ctor = controllerType.GetConstructor(new[]
            {
                typeof(UmbracoContext),
                typeof(UmbracoHelper),
                typeof(BaseSearchProvider)
            });

            if (ctor == null)
            {
                throw new MethodAccessException("Could not find the required constructor for the controller");
            }

            var created = (ApiController)ctor.Invoke(new object[]
            {
                //ctor args
                helper.UmbracoContext,
                helper,
                searchProvider
            });

            return(created);
        }
Exemplo n.º 16
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
Exemplo n.º 17
0
 /// <summary>
 /// Internal constructor used for unit tests
 /// </summary>
 /// <param name="result"></param>
 /// <param name="indexer"></param>
 /// <param name="searcher"></param>
 internal ExamineBackedMedia(SearchResult result, BaseIndexProvider indexer, BaseSearchProvider searcher)
     : this(result)
 {
     _indexer  = indexer;
     _searcher = searcher;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedCustomerQuery"/> class.
 /// </summary>
 /// <param name="merchelloContext">
 /// The <see cref="IMerchelloContext"/>.
 /// </param>
 /// <param name="indexProvider">
 /// The index provider.
 /// </param>
 /// <param name="searchProvider">
 /// The search provider.
 /// </param>
 /// <param name="enableDataModifiers">
 /// A value indicating whether or not data modifiers are enabled.
 /// </param>
 internal CachedCustomerQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers)
     : this(merchelloContext, indexProvider, searchProvider, new CachedInvoiceQuery(merchelloContext, enableDataModifiers).GetByCustomerKey, enableDataModifiers)
 {
 }
Exemplo n.º 19
0
        /// <summary>
        /// Before any of the index/search collections are accessed, the providers need to be loaded
        /// </summary>
        private void EnsureProviders()
        {
            if (!_providersInit)
            {
                lock (_lock)
                {
                    // Do this again to make sure _provider is still null
                    if (!_providersInit)
                    {
                        // Load registered providers and point _provider to the default provider

                        _indexProviderCollection = new IndexProviderCollection();
                        ProvidersHelper.InstantiateProviders(ExamineSettings.Instance.IndexProviders.Providers, _indexProviderCollection, typeof(BaseIndexProvider));

                        _searchProviderCollection = new SearchProviderCollection();
                        ProvidersHelper.InstantiateProviders(ExamineSettings.Instance.SearchProviders.Providers, _searchProviderCollection, typeof(BaseSearchProvider));

                        //set the default
                        if (!string.IsNullOrEmpty(ExamineSettings.Instance.SearchProviders.DefaultProvider))
                        {
                            _defaultSearchProvider = _searchProviderCollection[ExamineSettings.Instance.SearchProviders.DefaultProvider];
                        }

                        if (_defaultSearchProvider == null)
                        {
                            throw new ProviderException("Unable to load default search provider");
                        }

                        _providersInit = true;


                        //check if we need to rebuild on startup
                        if (ExamineSettings.Instance.RebuildOnAppStart)
                        {
                            foreach (IIndexer index in _indexProviderCollection)
                            {
                                var       rebuild     = false;
                                var       healthy     = true;
                                Exception unhealthyEx = null;
                                var       exists      = index.IndexExists();
                                if (!exists)
                                {
                                    rebuild = true;
                                }
                                if (!rebuild)
                                {
                                    healthy = IsIndexHealthy(index, out unhealthyEx);
                                    if (!healthy)
                                    {
                                        rebuild = true;
                                    }
                                }
                                //if it doesn't exist ... or if it's unhealthy/corrupt

                                if (rebuild)
                                {
                                    var args = new BuildingEmptyIndexOnStartupEventArgs(index, healthy, unhealthyEx);
                                    OnBuildingEmptyIndexOnStartup(args);
                                    if (!args.Cancel)
                                    {
                                        index.RebuildIndex();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 20
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));
        }
Exemplo n.º 21
0
 public TestServices(HttpRequestMessage httpRequestMessage, UmbracoContext umbracoContext, ITypedPublishedContentQuery publishedContentQuery, ServiceContext serviceContext, BaseSearchProvider searchProvider, IUmbracoSettingsSection umbracoSettings)
 {
     HttpRequestMessage    = httpRequestMessage;
     UmbracoContext        = umbracoContext;
     PublishedContentQuery = publishedContentQuery;
     ServiceContext        = serviceContext;
     SearchProvider        = searchProvider;
     UmbracoSettings       = umbracoSettings;
 }
Exemplo n.º 22
0
 /// <summary>
 /// Generally used for unit testing to use an explicit examine searcher
 /// </summary>
 /// <param name="searchProvider"></param>
 /// <param name="indexProvider"></param>
 internal PublishedMediaCache(BaseSearchProvider searchProvider, BaseIndexProvider indexProvider)
 {
     _searchProvider = searchProvider;
     _indexProvider  = indexProvider;
 }
Exemplo n.º 23
0
        //
        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);
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedCustomerQuery"/> class.
 /// </summary>
 /// <param name="service">
 /// The service.
 /// </param>
 /// <param name="indexProvider">
 /// The index provider.
 /// </param>
 /// <param name="searchProvider">
 /// The search provider.
 /// </param>
 internal CachedCustomerQuery(IPageCachedService <ICustomer> service, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider)
     : base(service, indexProvider, searchProvider)
 {
     _customerService = (CustomerService)service;
 }
        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));
        }
Exemplo n.º 26
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));
        }
Exemplo n.º 27
0
 public IEnumerable <IPublishedContent> TypedSearch(ISearchCriteria searchParameters, BaseSearchProvider searchProvider = null)
 {
     return(new UmbracoHelper(CurrentUmbracoContext()).TypedSearch(searchParameters, searchProvider));
 }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
0
        private void Activator(HttpRequestMessage httpRequestMessage, UmbracoContext umbracoContext, ITypedPublishedContentQuery arg3, ServiceContext serviceContext, BaseSearchProvider searchProvider)
        {
            _activator(httpRequestMessage, umbracoContext, arg3, serviceContext, searchProvider);

            Mapper.Initialize(configuration =>
            {
                var contentRepresentationMapper = new ContentModelMapper();
                contentRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var mediaRepresentationMapper = new MediaModelMapper();
                mediaRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var memberRepresentationMapper = new MemberModelMapper();
                memberRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var relationRepresentationMapper = new RelationModelMapper();
                relationRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);
            });
        }
 public MembersController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, BaseSearchProvider searchProvider)
     : base(umbracoContext, umbracoHelper)
 {
     if (searchProvider == null)
     {
         throw new ArgumentNullException("searchProvider");
     }
     _searchProvider = searchProvider;
 }
        /// <summary>
        /// Searhes content
        /// </summary>
        /// <param name="skip"></param>
        /// <param name="take"></param>
        /// <param name="totalRecords"></param>
        /// <param name="criteria"></param>
        /// <param name="searchProvider"></param>
        /// <returns></returns>
        public IEnumerable <IPublishedContent> TypedSearch(int skip, int take, out int totalRecords, ISearchCriteria criteria, BaseSearchProvider searchProvider = null)
        {
            if (_typedContentQuery != null)
            {
                return(_typedContentQuery.TypedSearch(skip, take, out totalRecords, criteria, searchProvider));
            }

            var s = ExamineManager.Instance.DefaultSearchProvider;

            if (searchProvider != null)
            {
                s = searchProvider;
            }

            //if both are zero, use the simple native Examine API
            if (skip == 0 && take == 0)
            {
                var r = s.Search(criteria);
                totalRecords = r.TotalItemCount;
                return(r.ConvertSearchResultToPublishedContent(_contentCache));
            }

            var maxResults = skip + take;

            var results = s.Search(criteria,
                                   //don't return more results than we need for the paging
                                   //this is the 'trick' - we need to be able to load enough search results to fill
                                   //all items to the maxResults
                                   maxResults: maxResults);

            totalRecords = results.TotalItemCount;

            //use examine to skip, this will ensure the lucene data is not loaded for those items
            var records = results.Skip(skip);

            return(records.ConvertSearchResultToPublishedContent(_contentCache));
        }
Exemplo n.º 32
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."));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedCustomerQuery"/> class.
 /// </summary>
 /// <param name="merchelloContext">
 /// The <see cref="IMerchelloContext"/>.
 /// </param>
 /// <param name="indexProvider">
 /// The index provider.
 /// </param>
 /// <param name="searchProvider">
 /// The search provider.
 /// </param>
 /// <param name="getInvoicesByCustomer">
 /// The get Invoices By Customer.
 /// </param>
 /// <param name="enableDataModifiers">
 /// A value indicating whether or not data modifiers are enabled.
 /// </param>
 internal CachedCustomerQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, Func <Guid, IEnumerable <InvoiceDisplay> > getInvoicesByCustomer, bool enableDataModifiers)
     : base(merchelloContext.Cache, merchelloContext.Services.CustomerService, indexProvider, searchProvider, enableDataModifiers)
 {
     _customerService      = (CustomerService)merchelloContext.Services.CustomerService;
     _getInvoiceByCustomer = getInvoicesByCustomer;
 }
Exemplo n.º 34
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);
        }
Exemplo n.º 35
0
        public void test_with_write_index_singleton()
        {
            BaseSearchProvider lueceneBaseSearchProvider = new BaseSearchProvider();

            var spaceOne = new SpaceObject
            {
                Id = Guid.NewGuid(),
                SpaceName = "技术空间",
                FileCount = 1,
                ParentId = Guid.NewGuid().ToString(),
                SpaceSize = 1024,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                CreateUserId = "5",
                CreateUserName = "******",

            };

            var spaceTwo = new SpaceObject
            {
                Id = Guid.NewGuid(),
                SpaceName = "生存空间",
                FileCount = 1,
                ParentId = Guid.NewGuid().ToString(),
                SpaceSize = 1024,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                CreateUserId = "5",
                CreateUserName = "******",

            };

            Stopwatch stopWatcher = new Stopwatch();
            stopWatcher.Start();

            lueceneBaseSearchProvider.IndexDirectory = "tempspace";
            lueceneBaseSearchProvider.Add(spaceOne);
            lueceneBaseSearchProvider.Add(spaceTwo);

            var results = lueceneBaseSearchProvider.Query<SpaceObject>("空间");
            Assert.IsTrue(results.Count>= 2);

            Console.WriteLine(results.Count);
        }