Beispiel #1
0
 public SearchResultModel(ISearchResults searchResults, double totalmilliseconds, string searchTerm, string orderBy)
 {
     SearchResults = searchResults;
     Totalmilliseconds = totalmilliseconds;
     SearchTerm = searchTerm;
     OrderBy = orderBy;
 }
 public void ShouldReturnSearchSettings(ISearchResults searchResults,[Substitute] SearchService service, SearchSettings searchSettings, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository,   IRenderingPropertiesRepository renderingPropertiesRepository, string query)
 {
   settingsRepository.Get(Arg.Any<string>()).Returns(searchSettings);
   var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
   var result = controller.SearchSettings(query) as ViewResult;
   result.Model.Should().BeOfType<SearchSettings>();
 }
Beispiel #3
0
        public void GivenIndexingDocument_WhenRichTextPropertyData_CanStoreImmenseFields()
        {
            using (GetSynchronousContentIndex(false, out UmbracoContentIndex index, out _, out ContentValueSetBuilder contentValueSetBuilder, null))
            {
                index.CreateIndex();

                ContentType contentType = ContentTypeBuilder.CreateBasicContentType();
                contentType.AddPropertyType(new PropertyType(TestHelper.ShortStringHelper, "test", ValueStorageType.Ntext)
                {
                    Alias = "rte",
                    Name  = "RichText",
                    PropertyEditorAlias = Cms.Core.Constants.PropertyEditors.Aliases.TinyMce
                });

                Content content = ContentBuilder.CreateBasicContent(contentType);
                content.Id   = 555;
                content.Path = "-1,555";

                var luceneStringFieldMaxLength = ByteBlockPool.BYTE_BLOCK_SIZE - 2;
                var faker       = new Faker();
                var immenseText = faker.Random.String(length: luceneStringFieldMaxLength + 10);

                content.Properties["rte"].SetValue(immenseText);

                IEnumerable <ValueSet> valueSet = contentValueSetBuilder.GetValueSets(content);
                index.IndexItems(valueSet);

                ISearchResults results = index.Searcher.CreateQuery().Id(555).Execute();
                ISearchResult  result  = results.First();

                var key = $"{UmbracoExamineFieldNames.RawFieldPrefix}rte";
                Assert.IsTrue(result.Values.ContainsKey(key));
                Assert.Greater(result.Values[key].Length, luceneStringFieldMaxLength);
            }
        }
 private void PrepareCompleted(ISearchResults searchResults)
 {
     if (!this.isTaskAborted && this.OnPrepareCompleted != null)
     {
         this.OnPrepareCompleted(searchResults);
     }
 }
Beispiel #5
0
        /// <summary>
        /// Returns a collection of entities for media based on search results
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        private IEnumerable <EntityBasic> MemberFromSearchResults(ISearchResults results)
        {
            var mapped = Mapper.Map <IEnumerable <EntityBasic> >(results).ToArray();

            //add additional data
            foreach (var m in mapped)
            {
                //if no icon could be mapped, it will be set to document, so change it to picture
                if (m.Icon == "icon-document")
                {
                    m.Icon = "icon-user";
                }

                var searchResult = results.First(x => x.Id.ToInvariantString() == m.Id.ToString());
                if (searchResult.Fields.ContainsKey("email") && searchResult.Fields["email"] != null)
                {
                    m.AdditionalData["Email"] = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()).Fields["email"];
                }
                if (searchResult.Fields.ContainsKey("__key") && searchResult.Fields["__key"] != null)
                {
                    Guid key;
                    if (Guid.TryParse(searchResult.Fields["__key"], out key))
                    {
                        m.Key = key;
                    }
                }
            }
            return(mapped);
        }
 public void SearchResultsHeader_ShouldReturnModel(ISearchResults searchResults, [Substitute]SearchService service, SearchContext searchContext, ISearchServiceRepository serviceRepository, ISearchContextRepository contextRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
 {
   contextRepository.Get().Returns(searchContext);
   var controller = new SearchController(serviceRepository, contextRepository, queryRepository, renderingPropertiesRepository);
   var result = controller.SearchResultsHeader(query) as ViewResult;
   result.Model.Should().BeOfType<SearchContext>();
 }
Beispiel #7
0
        public ActionResult Index(string q)
        {
            var model = GetModel <CategoriesPageViewModel>(CurrentPage);

            model.IsSearchMode = !string.IsNullOrEmpty(q);

            if (model.IsSearchMode)
            {
                if (ExamineManager.Instance.TryGetIndex("ExternalIndex", out IIndex index))
                {
                    ISearcher searcher = index.GetSearcher();
                    var       fields   = new List <string> {
                        "nodeName", "content", "pageContent", "bodyText"
                    };

                    ISearchResults results = searcher.CreateQuery("content").GroupedOr(fields, q).Execute();
                    model.SearchResults = results.Select(result => new PageViewModel(result, model.TenantUid, Umbraco)).Where(x => !string.IsNullOrEmpty(x.Title));
                    //model.SearchResults = results.Select(result => new PageViewModel(result, Umbraco));
                }
            }
            else
            {
                model.Categories = CurrentPage.Children.Select(content => new ArticleCategoryViewModel(content));
            }

            return(CurrentTemplate(model));
        }
Beispiel #8
0
 private IEnumerable <SearchResult> RemoveRedundantLinkingPages(ISearchResults additionalResult)
 {
     return(from result in additionalResult
            group result by result.Fields["inhoudKiezer"]
            into groups
            select groups.OrderBy(r => r.Score).First());
 }
 public SearchResultModel(ISearchResults searchResults, double totalmilliseconds, string searchTerm, string orderBy)
 {
     SearchResults     = searchResults;
     Totalmilliseconds = totalmilliseconds;
     SearchTerm        = searchTerm;
     OrderBy           = orderBy;
 }
        private static List <Models.API.FacetResult> BuildFacets(ISearchResults searchResult, Tab tab)
        {
            var facetResults = new List <Models.API.FacetResult>();

            foreach (var facetConfiguration in tab.Facets)
            {
                ISearchResultFacet facet = searchResult.Facets.Where(x => x.Definition.FieldName == facetConfiguration.FieldName).FirstOrDefault();
                if (facet != null)
                {
                    FacetResult facetResult = new FacetResult();
                    facetResult.Values    = new List <FacetValue>();
                    facetResult.Name      = facetConfiguration.Name;
                    facetResult.FieldName = facetConfiguration.FieldName;

                    foreach (var facetValue in facet.Values)
                    {
                        FacetValue facetResultValue = new FacetValue();
                        facetResultValue.Count    = facetValue.Count;
                        facetResultValue.Name     = facetValue.Value.ToString();
                        facetResultValue.Selected = facetValue.Selected;
                        facetResultValue.Value    = facetValue.Value.ToString();
                        facetResult.Values.Add(facetResultValue);
                    }
                    facetResult = SortFacetValues(facetConfiguration, facetResult);
                    facetResults.Add(facetResult);
                }
            }
            return(facetResults);
        }
Beispiel #11
0
        public void BeginSearch(string fen, ISearchResults target, TimeSpan timeVailable)
        {
            var board = CreateBoard(fen);
            var eg    = EndGameReporter.ReportEndGame(board);

            if (eg != GameEnded.None)
            {
                target.SearchDone(string.Empty, eg);
            }
            else
            {
                BackgroundWorker wrk = new BackgroundWorker();
                wrk.DoWork += (e, a) =>
                {
                    int    bestMove = DoSearch(board, timeVailable);
                    string move     = string.Empty;
                    if (bestMove != 0)
                    {
                        move = MovePackHelper.GetAlgebraicString(bestMove);
                    }
                    target.SearchDone(move, EndGameReporter.ReportEndGame(board));
                };
                wrk.RunWorkerAsync();
            }
        }
        private void GetUsageData()
        {
            int nodeId   = Int32.Parse(Request.QueryString["id"]);
            var criteria = searcher.CreateSearchCriteria(IndexTypes.Content);

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

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

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

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

            if (_results.Any())
            {
                rptItemUsage.DataSource = _results;
                rptItemUsage.DataBind();
                litMessage.Text = "The page is referenced by the pages listed below";
            }
            else
            {
                rptItemUsage.Visible = false;
                litMessage.Text      = NoResultstext;
            }
        }
Beispiel #13
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);
            }
        }
Beispiel #14
0
 public static int GetIntegerPropertyAlias(ISearchResults results, string alias)
 {
     string property = GetPropertyAlias(results, alias);
        int returnInt = 0;
        int.TryParse(property, out returnInt);
        return returnInt;
 }
Beispiel #15
0
 public void ShouldReturnGlobalSearch(ISearchResults searchResults, [Substitute] SearchService service, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
 {
   service.Search(Arg.Any<IQuery>()).Returns(searchResults);
   serviceRepository.Get().Returns(service);
   var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
   var result = controller.GlobalSearch() as ViewResult;
   result.Model.Should().As<ISearchResults>();
 }
Beispiel #16
0
        /// <summary>
        /// queries the Lucene index to get all members with the supplied partyGuid
        /// </summary>
        /// <param name="members">the Umbraco MembershipHelper</param>
        /// <param name="partyGuid">Guid identifying a specific party</param>
        /// <returns>a collection of PartyHost / PartyGuest associated with a specific party</returns>
        public static IEnumerable <IPartier> GetPartiers(this MembershipHelper members, Guid partyGuid)
        {
            BaseSearchProvider searchProvider = ExamineManager.Instance.SearchProviderCollection["InternalMemberSearcher"];
            ISearchCriteria    searchCriteria = searchProvider.CreateSearchCriteria(IndexTypes.Member).Field("partyGuid", partyGuid.ToString()).Compile();
            ISearchResults     searchResults  = searchProvider.Search(searchCriteria);

            return(searchResults.Select(x => (IPartier)members.GetById(x.Id)));
        }
Beispiel #17
0
        /// <summary>
        /// Gets the hits and values for a particular facet in the results
        /// </summary>
        public static IDictionary <T, int> GetFacetHits <T>(this ISearchResults searchResults, string field)
        {
            var facetResults = searchResults.GetFacet(field);

            return(facetResults
                   .Where(x => x.GetValue <T>() != null)
                   .ToDictionary(x => x.GetValue <T>(), x => x.Hits));
        }
Beispiel #18
0
 private void RegisterSearchPageEvent(string searchQuery, ISearchResults results)
 {
     this.TrackerService.TrackPageEvent(AnalyticsIds.SearchEvent, searchQuery, searchQuery, searchQuery?.ToLowerInvariant(), results.TotalNumberOfResults);
     if (results.TotalNumberOfResults == 0)
     {
         this.TrackerService.TrackPageEvent(AnalyticsIds.NoSearchHitsFound, searchQuery, searchQuery, searchQuery?.ToLowerInvariant());
     }
 }
Beispiel #19
0
 private IEnumerable <ProductTileViewModel> CreateProductViewModels(ISearchResults searchResult)
 {
     return(searchResult.Documents.Select(x => new ProductTileViewModel()
     {
         Title = GetString(x, "Title"),    //"Title " + ((ISearchDocument)x).Value,
         Content = GetString(x, "Content") //"Content " + ((ISearchDocument)x).Value
     }));
 }
        public void SearchResultsHeader_ShouldReturnModel(ISearchResults searchResults, [Substitute] SearchService service, SearchContext searchContext, ISearchServiceRepository serviceRepository, ISearchContextRepository contextRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
        {
            contextRepository.Get().Returns(searchContext);
            var controller = new SearchController(serviceRepository, contextRepository, queryRepository, renderingPropertiesRepository);
            var result     = controller.SearchResultsHeader(query) as ViewResult;

            result.Model.Should().BeOfType <SearchContext>();
        }
 public static IEnumerable <ISearchResult> SkipTake(this ISearchResults searchResults, int skip, int?take = null)
 {
     if (!(searchResults is ISearchResults2 results2))
     {
         throw new NotSupportedException("ISearchResults2 is not implemented");
     }
     return(results2.SkipTake(skip, take));
 }
        public void ShouldReturnSearchSettings(ISearchResults searchResults, [Substitute] SearchService service, SearchSettings searchSettings, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
        {
            settingsRepository.Get(Arg.Any <string>()).Returns(searchSettings);
            var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
            var result     = controller.SearchSettings(query) as ViewResult;

            result.Model.Should().BeOfType <SearchSettings>();
        }
        public void Can_Add_A_New_Product_To_The_Index()
        {
            PreTestDataWorker.DeleteAllProducts();

            //// Arrange
            var provider = (ProductIndexer)ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"];

            provider.RebuildIndex();

            var searcher = ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"];

            var productVariantService = PreTestDataWorker.ProductVariantService;

            //// Act
            var product = MockProductDataMaker.MockProductCollectionForInserting(1).First();

            product.ProductOptions.Add(new ProductOption("Color"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Blue", "Blue"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Red", "Red"));
            product.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Green", "Green"));
            product.ProductOptions.Add(new ProductOption("Size"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Small", "Sm"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Medium", "Med"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("Large", "Lg"));
            product.ProductOptions.First(x => x.Name == "Size").Choices.Add(new ProductAttribute("X-Large", "XL"));
            product.Height      = 11M;
            product.Width       = 11M;
            product.Length      = 11M;
            product.CostOfGoods = 15M;
            product.OnSale      = true;
            product.SalePrice   = 18M;
            _productService.Save(product);


            var attributes = new ProductAttributeCollection()
            {
                product.ProductOptions.First(x => x.Name == "Color").Choices.First(x => x.Sku == "Blue"),
                product.ProductOptions.First(x => x.Name == "Size").Choices.First(x => x.Sku == "XL")
            };

            productVariantService.CreateProductVariantWithKey(product, attributes);

            provider.AddProductToIndex(product);

            //// Assert
            var criteria = searcher.CreateSearchCriteria("productvariant", BooleanOperation.And);

            criteria.Field("productKey", product.Key.ToString()).And().Field("master", "true");

            ISearchResults results = searcher.Search(criteria);

            Assert.IsTrue(results.Count() == 1);
            var result = results.First();

            Assert.NotNull(result.Fields["productOptions"]);

            provider.RebuildIndex();
        }
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            // create the XDocument
            XDocument doc = new XDocument();

            // check there are any search results
            if (results.TotalItemCount > 0)
            {
                // create the root element
                XElement root = new XElement("nodes");

                // iterate through the search results
                foreach (SearchResult result in results)
                {
                    // create a new <node> element
                    XElement node = new XElement("node");

                    // create the @id attribute
                    XAttribute nodeId = new XAttribute("id", result.Id);

                    // create the @score attribute
                    XAttribute nodeScore = new XAttribute("score", result.Score);

                    // add the content
                    node.Add(nodeId, nodeScore);

                    foreach (KeyValuePair <String, String> field in result.Fields)
                    {
                        // create a new <data> element
                        XElement data = new XElement("data");

                        // create the @alias attribute
                        XAttribute alias = new XAttribute("alias", field.Key);

                        // assign the value to a CDATA section
                        XCData value = new XCData(field.Value);

                        // append the content
                        data.Add(alias, value);

                        // append the <data> element
                        node.Add(data);
                    }

                    // add the node
                    root.Add(node);
                }

                // add the root node
                doc.Add(root);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return(doc.CreateNavigator().Select("/"));
        }
Beispiel #25
0
        internal static IEnumerable <SearchedLocation> ExamineToSearchedLocations(ISearchResults SearchResults)
        {
            var returnList = new List <SearchedLocation>();

            // check that there are any search results
            if (SearchResults.TotalItemCount > 0)
            {
                // iterate through the search results
                foreach (SearchResult result in SearchResults)
                {
                    var sl = new SearchedLocation();
                    sl.ExamineNodeId = result.Id;
                    sl.SearchScore   = result.Score;

                    var location = new IndexedLocation();
                    location.IndexNodeId      = result.Id;
                    location.Key              = result.Fields.ContainsKey("Key") ? new Guid(result.Fields["Key"]) : Guid.Empty;
                    location.Name             = result.Fields.ContainsKey("Name") ? result.Fields["Name"] : string.Empty;
                    location.LocationTypeKey  = result.Fields.ContainsKey("LocationTypeKey") ? new Guid(result.Fields["LocationTypeKey"]) : Guid.Empty;
                    location.LocationTypeName = result.Fields.ContainsKey("LocationTypeName") ? result.Fields["LocationTypeName"] : string.Empty;
                    location.Latitude         = result.Fields.ContainsKey("Latitude") ? System.Convert.ToDouble(result.Fields["Latitude"]) : 0;
                    location.Longitude        = result.Fields.ContainsKey("Longitude") ? System.Convert.ToDouble(result.Fields["Longitude"]) : 0;
                    location.Address1         = result.Fields.ContainsKey("Address1") ? result.Fields["Address1"] : string.Empty;
                    location.Address2         = result.Fields.ContainsKey("Address2") ? result.Fields["Address2"] : string.Empty;
                    location.Locality         = result.Fields.ContainsKey("Locality") ? result.Fields["Locality"] : string.Empty;
                    location.Region           = result.Fields.ContainsKey("Region") ? result.Fields["Region"] : string.Empty;
                    location.PostalCode       = result.Fields.ContainsKey("PostalCode") ? result.Fields["PostalCode"] : string.Empty;
                    location.CountryCode      = result.Fields.ContainsKey("CountryCode") ? result.Fields["CountryCode"] : string.Empty;
                    location.Email            = result.Fields.ContainsKey("Email") ? result.Fields["Email"] : string.Empty;
                    location.Phone            = result.Fields.ContainsKey("Phone") ? result.Fields["Phone"] : string.Empty;

                    //Handle Custom properties
                    List <IndexedPropertyData> customProps;

                    if (result.Fields.ContainsKey("CustomPropertyData"))
                    {
                        customProps = ExamineCustomPropsToIndexedProps(result.Fields["CustomPropertyData"]);
                    }
                    else
                    {
                        customProps = new List <IndexedPropertyData>();
                    }

                    location.CustomPropertyData = customProps;

                    //Add all properties to Dictionary
                    location.AllPropertiesDictionary = AllPropertiesToDictionary(result.Fields, customProps);

                    // add the location to SL
                    sl.IndexedLocation = location;

                    //add to list
                    returnList.Add(sl);
                }
            }

            return(returnList);
        }
Beispiel #26
0
        private List <Job> BuildJobsFromExamineResults(ISearchResults results)
        {
            var jobs = new List <Job>();

            foreach (var result in results)
            {
                var job = new Job()
                {
                    Id           = result.Fields.ContainsKey("id") ? result["id"] : String.Empty,
                    Reference    = result.Fields.ContainsKey("reference") ? result["reference"] : String.Empty,
                    JobTitle     = result.Fields.ContainsKey("titleDisplay") ? result["titleDisplay"] : String.Empty,
                    Organisation = result.Fields.ContainsKey("organisationDisplay") ? result["organisationDisplay"] : String.Empty,
                    Location     = result.Fields.ContainsKey("locationDisplay") ? result["locationDisplay"] : String.Empty,
                    JobType      = result.Fields.ContainsKey("jobTypeDisplay") ? result["jobTypeDisplay"] : String.Empty,
                    ContractType = result.Fields.ContainsKey("contractType") ? result["contractType"] : String.Empty,
                    IsPartTime   = result.Fields.ContainsKey("partTime") ? Boolean.Parse(result["partTime"]) : false,
                    IsFullTime   = result.Fields.ContainsKey("fullTime") ? Boolean.Parse(result["fullTime"]) : false,
                    Department   = result.Fields.ContainsKey("departmentDisplay") ? result["departmentDisplay"] : String.Empty,
                    WorkPattern  = new WorkPattern()
                    {
                        IsFullTime = result.Fields.ContainsKey("fullTime") && result["fullTime"].ToUpperInvariant() == "TRUE",
                        IsPartTime = result.Fields.ContainsKey("partTime") && result["partTime"].ToUpperInvariant() == "TRUE"
                    },
                    AdvertHtml = new HtmlString(result.Fields.ContainsKey("fullHtml") ? result["fullHtml"] : String.Empty),
                    AdditionalInformationHtml = new HtmlString(result.Fields.ContainsKey("additionalInfo") ? result["additionalInfo"] : String.Empty),
                    EqualOpportunitiesHtml    = new HtmlString(result.Fields.ContainsKey("equalOpportunities") ? result["equalOpportunities"] : String.Empty),
                    ApplyUrl = (result.Fields.ContainsKey("applyUrl") && !String.IsNullOrEmpty(result["applyUrl"])) ? new Uri(result["applyUrl"]) : null
                };

                job.Salary.SalaryRange = result.Fields.ContainsKey("salary") ? result["salary"] : String.Empty;
                job.Salary.SearchRange = result.Fields.ContainsKey("salaryRange") ? result["salaryRange"] : String.Empty;
                if (result.Fields.ContainsKey("salaryMin") && !String.IsNullOrEmpty(result["salaryMin"]))
                {
                    int minimumSalary;
                    Int32.TryParse(result["salaryMin"], out minimumSalary);
                    job.Salary.MinimumSalary = minimumSalary;
                }
                if (result.Fields.ContainsKey("salaryMax") && !String.IsNullOrEmpty(result["salaryMax"]))
                {
                    int maximumSalary;
                    Int32.TryParse(result["salaryMax"], out maximumSalary);
                    job.Salary.MaximumSalary = maximumSalary;
                }

                if (_urlGenerator != null)
                {
                    job.Url = _urlGenerator.GenerateUrl(job);
                }
                if (result.Fields.ContainsKey("closingDateDisplay"))
                {
                    job.ClosingDate = DateTime.Parse(result["closingDateDisplay"]);
                }

                jobs.Add(job);
            }

            return(jobs);
        }
 public void ShouldReturnPagedSearchResult([Substitute] SearchService service, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository, string query, ISearchResults searchResults, [Substitute] SearchController searchController, IRenderingPropertiesRepository renderingPropertiesRepository, [Substitute] PagingSettings pagingSettings)
 {
   renderingPropertiesRepository.Get<PagingSettings>().Returns(pagingSettings);
   service.Search(Arg.Any<IQuery>()).Returns(searchResults);
   serviceRepository.Get().Returns(service);
   var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
   var result = controller.PagedSearchResults(query, null) as ViewResult;
   result.Model.Should().BeOfType<PagedSearchResults>();
 }
        private int CountPendingUsers()
        {
            bool hasloggedin = (System.Web.HttpContext.Current.User != null) &&
                               System.Web.HttpContext.Current.User.Identity.IsAuthenticated;

            var    userService = Services.MemberService;
            string usern       = string.Empty;

            usern = System.Web.HttpContext.Current.User.Identity.Name;


            //UmbracoShipTac.Code.UiEnum.RolesId.shipcounselor

            var amember = userService.GetByEmail(usern);

            //get the rolid of the  user.. from the isinrole
            string strRoleAssigned = amember.GetValue("roleAssigned").ToString();

            string state = string.Empty;

            state = amember.GetValue("state").ToString();



            // Use the already configured member searcher
            var memberSearcher = ExamineManager.Instance
                                 .SearchProviderCollection["InternalMemberSearcher"]
                                 .CreateSearchCriteria(BooleanOperation.Or);

            Examine.SearchCriteria.IBooleanOperation filter = null;
            filter = memberSearcher.Field("hasVerifiedEmail", "0"); //just to start a dummy this is OR ? I think It is AND
            filter = filter.And().Field("umbracoMemberApproved", "0");



            if (state.ToUpper() != "ALL")
            {
                filter = filter.And().Field("state", state);
            }


            filter = filter.And().Range("roleAppliedFor", "1", strRoleAssigned, true, true);

            filter = filter.And().Field("isDenied", "0");

            ISearchResults resultsAllMembers = ExamineManager.Instance
                                               .SearchProviderCollection["InternalMemberSearcher"]
                                               .Search(filter.Compile());


            int pendingusers = resultsAllMembers.Count();

            //do not include the loggedin user..
            // if (id != amember.Id.ToString())

            return(pendingusers);
        }
Beispiel #29
0
        public void ShouldReturnGlobalSearch(ISearchResults searchResults, [Substitute] SearchService service, ISearchServiceRepository serviceRepository, ISearchSettingsRepository settingsRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
        {
            service.Search(Arg.Any <IQuery>()).Returns(searchResults);
            serviceRepository.Get().Returns(service);
            var controller = new SearchController(serviceRepository, settingsRepository, queryRepository, renderingPropertiesRepository);
            var result     = controller.GlobalSearch() as ViewResult;

            result.Model.Should().As <ISearchResults>();
        }
Beispiel #30
0
        /// <summary>
        /// Get all of the facets in the results
        /// </summary>
        public static IEnumerable <IFacetResult> GetFacets(this ISearchResults searchResults)
        {
            if (!(searchResults is IFacetResults facetResults))
            {
                throw new Exception("Result does not support facets");
            }

            return(facetResults.Facets.Values);
        }
Beispiel #31
0
        private CustomSearchResult Search(CatalogEntrySearchCriteria criteria, IContent currentContent)
        {
            ISearchResults searchResult = _search.Search(criteria);

            return(new CustomSearchResult
            {
                ProductViewModels = CreateProductViewModels(searchResult)
            });
        }
Beispiel #32
0
        /// <summary>
        /// Get the values for a particular facet in the results
        /// </summary>
        public static IFacetResult GetFacet(this ISearchResults searchResults, string field)
        {
            if (!(searchResults is IFacetResults facetResults))
            {
                throw new Exception("Result does not support facets");
            }

            facetResults.Facets.TryGetValue(field, out IFacetResult facet);

            return(facet);
        }
Beispiel #33
0
        public void GivenIOpenAmazonInABrowser()
        {
            var kernel = new StandardKernel();

            kernel.Load(Assembly.GetExecutingAssembly());

            _homePage      = kernel.Get <IHomePage>();
            _searchResults = kernel.Get <ISearchResults>();
            _categoryPage  = kernel.Get <ICategoryPage>();
            _homePage.launchSite(ConfigurationManager.AppSettings["baseUrl"]);
        }
        public ActionResult ProviderModelFilteredSearch(string keyWord, string group, string facet)
        {
            var vmodel = new PMSearchResultViewModel();

            vmodel.SearchQueryText = keyWord;

            CatalogEntrySearchCriteria criteria = new CatalogEntrySearchCriteria
            {
                Locale       = ContentLanguage.PreferredCulture.TwoLetterISOLanguageName,
                SearchPhrase = keyWord
            };

            //string _SearchConfigPath =
            //@"C:\Episerver612\CommerceTraining\CommerceTraining\Configs\Mediachase.Search.Filters.config";

            //TextReader reader = new StreamReader(_SearchConfigPath);
            //XmlSerializer serializer = new XmlSerializer((typeof(SearchConfig)));
            //var _SearchConfig = (SearchConfig)serializer.Deserialize(reader);
            //reader.Close();

            //foreach (SearchFilter filter in _SearchConfig.SearchFilters)
            //{
            //    // Step 1 - use the XML file
            //    criteria.Add(filter);
            //}

            CreateFacetsByCode(criteria);

            foreach (SearchFilter filter in criteria.Filters)
            {
                if (filter.field.ToLower() == group.ToLower())
                {
                    var svFilter = filter.Values.SimpleValue
                                   .FirstOrDefault(x => x.value.Equals(facet, StringComparison.OrdinalIgnoreCase));
                    if (svFilter != null)
                    {
                        //This overload to Add causes the filter to be applied
                        criteria.Add(filter.field, svFilter);
                    }
                }
            }

            // use the manager for search and for index management
            SearchManager manager = new SearchManager("ECApplication");

            // Do search
            ISearchResults results = manager.Search(criteria);

            vmodel.SearchResults = results.Documents.ToList();
            vmodel.FacetGroups   = results.FacetGroups.ToList();
            vmodel.ResultCount   = results.Documents.Count.ToString();

            return(View("ProviderModelQuery", vmodel));
        }
Beispiel #35
0
        private int GetFacetCount(ISearchResults results, string fieldName, string facetKey)
        {
            if (results.FacetGroups == null || results.FacetGroups.Length == 0)
            {
                return(0);
            }

            var group = (from fg in results.FacetGroups where fg.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase) select fg).SingleOrDefault();

            return(@group == null ? 0 : (from facet in @group.Facets where facet.Key == facetKey select facet.Count).FirstOrDefault());
        }
        public IEnumerable <T> HandleSearchResults <T>(ISearchResults <T> results) where T : class
        {
            if (results == null)
            {
                AddTotalCountHeader("0");
                return(new List <T>(0));
            }

            AddTotalCountHeader(results.TotalHits.ToString());
            return(results.Results);
        }
 public void SearchResults_ShouldReturnModel([Substitute]ControllerContext controllerContext, [Substitute]HttpContextBase context, ISearchResults searchResults, [Substitute]SearchService service, ISearchServiceRepository serviceRepository, ISearchContextRepository contextRepository, QueryRepository queryRepository, IRenderingPropertiesRepository renderingPropertiesRepository, string query)
 {
   service.Search(Arg.Any<IQuery>()).Returns(searchResults);
   serviceRepository.Get().Returns(service);
   var controller = new SearchController(serviceRepository, contextRepository, queryRepository, renderingPropertiesRepository)
                    {
                      ControllerContext = controllerContext
                    };
   controller.ControllerContext.HttpContext = context;
   var result = controller.SearchResults(query) as ViewResult;
   result.Model.Should().As<ISearchResults>();
 }
Beispiel #38
0
 public void GetLatestNews_IntegerAs1Parameter_ReturnsNumberOfNewsEquelToParameterValue([Frozen] ISearchServiceRepository searchServiceRepository, [Frozen] ISearchSettingsRepository searchSettingsRepository, string itemName, [Substitute] SearchService searchService, ISearchResults searchResults, List<Item> collection)
 {
   var id = ID.NewID;
   searchResults.Results.Returns(collection.Select(x=>new Foundation.Indexing.Models.SearchResult(x)));
   searchService.FindAll().Returns(searchResults);
   searchServiceRepository.Get().Returns(searchService);
   var db = new Db
   {
     new DbItem(itemName, id, Templates.NewsFolder.ID)
   };
   var contextItem = db.GetItem(id);
   var repository = new NewsRepository(contextItem, searchServiceRepository);
   var news = repository.GetLatestNews(1);
   news.Count().ShouldBeEquivalentTo(1);
 }
Beispiel #39
0
        public static string GetPropertyAlias(ISearchResults results, string alias)
        {
            if (results.TotalItemCount == 1)
            {
                var result = results.FirstOrDefault();
                if (result != null)
                {
                    if (alias == "pageName")
                    {
                        alias = "nodeName";
                    }
                    if (result.Fields.ContainsKey(alias))
                    {
                        return result.Fields[alias];
                    }
                }

            }
            return String.Empty;
        }
Beispiel #40
0
        private IEnumerable<ProductViewModel> CreateProductViewModels(ISearchResults searchResult)
        {
            var market = _currentMarket.GetCurrentMarket();
            var currency = _currencyService.GetCurrentCurrency();

            return searchResult.Documents.Select(document => new ProductViewModel
            {
                Brand = GetString(document, "brand"),
                Code = GetString(document, "code"),
                DisplayName = GetString(document, "displayname"),
                PlacedPrice = new Money(GetDecimal(document, IndexingHelper.GetOriginalPriceField(market.MarketId, currency)), currency),
                ExtendedPrice = new Money(GetDecimal(document, IndexingHelper.GetPriceField(market.MarketId, currency)), currency),
                ImageUrl = GetString(document, "image_url"),
                Url = _urlResolver.GetUrl(ContentReference.Parse(GetString(document, "content_link")))
            });
        }
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        private static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            // create the XDocument
            XDocument doc = new XDocument();

            // check there are any search results
            if (results.TotalItemCount > 0)
            {
                // create the root element
                XElement root = new XElement("nodes");

                // iterate through the search results
                foreach (SearchResult result in results)
                {
                    // create a new <node> element
                    XElement node = new XElement("node");

                    // create the @id attribute
                    XAttribute nodeId = new XAttribute("id", result.Id);

                    // create the @score attribute
                    XAttribute nodeScore = new XAttribute("score", result.Score);

                    // add the content
                    node.Add(nodeId, nodeScore);

                    foreach (KeyValuePair<String, String> field in result.Fields)
                    {
                        // create a new <data> element
                        XElement data = new XElement("data");

                        // create the @alias attribute
                        XAttribute alias = new XAttribute("alias", field.Key);

                        // assign the value to a CDATA section
                        XCData value = new XCData(field.Value);

                        // append the content
                        data.Add(alias, value);

                        // append the <data> element
                        node.Add(data);
                    }

                    // add the node
                    root.Add(node);
                }

                // add the root node
                doc.Add(root);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return doc.CreateNavigator().Select("/");
        }
        private void GetUsageData()
        {
            int nodeId = Int32.Parse(Request.QueryString["id"]);
            var criteria = searcher.CreateSearchCriteria(IndexTypes.Content);
            string[] fields = PropertyTypes.Split(new[] { ',' });

            var query = criteria.OrderBy("__nodeName");
            query = fields.Aggregate(query, (current, field) => current.Or().Field(field, nodeId.ToString()));

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

            if (_results.Any())
            {
                rptItemUsage.DataSource = _results;
                rptItemUsage.DataBind();
                litMessage.Text = "The page is referenced by the pages listed below";
            }
            else
            {
                rptItemUsage.Visible = false;
                litMessage.Text = NoResultstext;
            }
        }
Beispiel #43
0
 public void ExportedCallback(ISearchResults results)
 {
     SearchResults = results;
     CalledBack.Set();
 }
        private int GetFacetCount(ISearchResults results, string fieldName, string facetKey)
        {
            if (results.FacetGroups == null || results.FacetGroups.Length == 0)
            {
                return 0;
            }

            var group = (from fg in results.FacetGroups where fg.FieldName.Equals(fieldName, StringComparison.OrdinalIgnoreCase) select fg).SingleOrDefault();

            return @group == null ? 0 : (from facet in @group.Facets where facet.Key == facetKey select facet.Count).FirstOrDefault();
        }
Beispiel #45
0
        /// <summary>
        /// Gets the results as XML.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns>
        /// Returns an XML structure of the search results.
        /// </returns>
        internal static XPathNodeIterator GetResultsAsXml(ISearchResults results)
        {
            var legacy = uQuery.IsLegacyXmlSchema();
            var attributes = new List<string>() { "id", "nodeName", "updateDate", "writerName", "path", "nodeTypeAlias", "parentID", "loginName", "email" };
            var doc = new XDocument();

            if (results.TotalItemCount > 0)
            {
                var nodes = new XElement("results");
                foreach (SearchResult result in results)
                {
                    var node = new XElement(legacy ? "node" : result.Fields["nodeTypeAlias"]);
                    node.Add(new object[] { new XAttribute("score", result.Score) });

                    foreach (KeyValuePair<string, string> item in result.Fields)
                    {
                        // if the field key starts with '__' (double-underscore) - then skip.
                        if (item.Key.StartsWith("__"))
                        {
                            continue;
                        }
                        // if not legacy schema and 'nodeTypeAlias' - add the @isDoc attribute
                        else if (!legacy && item.Key == "nodeTypeAlias")
                        {
                            node.Add(new object[] { new XAttribute("isDoc", string.Empty) });
                        }
                        // check if the field is an attribute or a data value
                        else if (attributes.Contains(item.Key))
                        {
                            // attribute field
                            node.Add(new object[] { new XAttribute(item.Key, item.Value) });
                        }
                        else
                        {
                            // data field
                            var data = new XElement(legacy ? "data" : item.Key);

                            // if legacy add the 'alias' attribute
                            if (legacy)
                            {
                                data.Add(new object[] { new XAttribute("alias", item.Key) });
                            }

                            // CDATA the value - because we don't know what it is!
                            data.Add(new object[] { new XCData(item.Value) });

                            // add the data field to the node.
                            node.Add(data);
                        }
                    }

                    // add the node to the collection.
                    nodes.Add(node);
                }

                doc.Add(nodes);
            }
            else
            {
                doc.Add(new XElement("error", "There were no search results."));
            }

            return doc.CreateNavigator().Select("/*");
        }