示例#1
0
        public SearchResults Find(string terms)
        {
            Directory directory = FSDirectory.GetDirectory("./index",false);
            // Now search the index:
            var isearcher = new IndexSearcher(directory);
            // Parse a simple query that searches for "text":
            //Query query = QueryParser.Parse("text", "fieldname", analyzer);
            var qp = new QueryParser("description", _analyzer);
            Query query = qp.Parse(terms);

            Hits hits = isearcher.Search(query);

            var sr = new SearchResults();

            // Iterate through the results:
            for (int i = 0; i < hits.Length(); i++)
            {
                Document hitDoc = hits.Doc(i);

                sr.Add(new Result() { Name = hitDoc.Get("name"), Description = hitDoc.Get("description") });
            }
            isearcher.Close();
            directory.Close();

            return sr;
        }
示例#2
0
		public async Task<SearchResults> GetResultsByTitleAsync(string query, int skip, int count)
		{
			if (string.IsNullOrWhiteSpace(query))
				throw new ArgumentException();
			if (skip < 0 || count < 1)
				throw new ArgumentOutOfRangeException();

			var posts = await _postService.GetPostsByTitleAsync(query, skip, count);
			var pages = await _pageService.GetPagesByTitleAsync(query, skip, count);
			var postComments = await _postService.GetCommentsBySearchAsync(query, skip, count);
			var pageComments = await _pageService.GetCommentsBySearchAsync(query, skip, count);
			var user = await _userManager.FindByNameAsync(query);

			var results = new SearchResults
			{
				 Posts = posts.Results,
				 Pages = pages.Results,
				 PostComments = postComments.Results,
				 PageComments = pageComments.Results,
				 User = user
			};
			results.ResultCount = results.Posts.Length + results.Pages.Length + results.PostComments.Length +
					  results.PageComments.Length;
			results.TotalCount = posts.Total + pages.Total + postComments.Total + pageComments.Total;

			if (user != null)
			{
				results.ResultCount++;
				results.TotalCount++;
			}

			return results;
		}
        object IJsonDeserializer.Deserialize(JsonValue json, JsonMapper mapper)
        {
            var results = new SearchResults();
            var userJson = json.GetValue("auth_user");
            var pagingJson = json.GetValue("paging");
            var jobsJson = json.GetValue("jobs");


            results.ServerTime = json.GetValueOrDefault<long>("server_time");
            results.ProfileAccess = json.GetValueOrDefault<string>("profile_access");

            if (userJson != null)
            {
                results.AuthUser.FirstName = userJson.GetValue<string>("first_name");
                results.AuthUser.LastName = userJson.GetValue<string>("last_name");
                results.AuthUser.Username = userJson.GetValue<string>("uid");
                results.AuthUser.Email = userJson.GetValue<string>("mail");
                results.AuthUser.TimeZone = userJson.GetValue<string>("timezone");
                results.AuthUser.TimeZoneOffset = userJson.GetValue<string>("timezone_offset");
            }

            if (pagingJson != null)
            {
                results.Paging.Count = pagingJson.GetValue<int>("count");
                results.Paging.Offset = pagingJson.GetValue<int>("offset");
                results.Paging.Total = pagingJson.GetValue<int>("total");
            }

            results.Jobs = mapper.Deserialize<List<Job>>(jobsJson);

            return results;
        }
示例#4
0
 public ProfilerHierarchyGUI(IProfilerWindowController window, string columnSettingsName, ProfilerColumn[] columnsToShow, string[] columnNames, bool detailPane, ProfilerColumn sort)
 {
     this.m_Window = window;
     this.m_ColumnNames = columnNames;
     this.m_ColumnSettingsName = columnSettingsName;
     this.m_ColumnsToShow = columnsToShow;
     this.m_DetailPane = detailPane;
     this.m_SortType = sort;
     this.m_HeaderContent = new GUIContent[columnNames.Length];
     this.m_Splitter = null;
     for (int i = 0; i < this.m_HeaderContent.Length; i++)
     {
         this.m_HeaderContent[i] = !this.m_ColumnNames[i].StartsWith("|") ? new GUIContent(this.m_ColumnNames[i]) : EditorGUIUtility.IconContent("ProfilerColumn." + columnsToShow[i].ToString(), this.m_ColumnNames[i]);
     }
     if (columnsToShow.Length != columnNames.Length)
     {
         throw new ArgumentException("Number of columns to show does not match number of column names.");
     }
     this.m_SearchHeader = new GUIContent("Search");
     this.m_VisibleColumns = new bool[columnNames.Length];
     for (int j = 0; j < this.m_VisibleColumns.Length; j++)
     {
         this.m_VisibleColumns[j] = true;
     }
     this.m_SearchResults = new SearchResults();
     this.m_SearchResults.Init(100);
     this.m_Window.Repaint();
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="SearchResults" /> class.
 /// </summary>
 /// <param name="searcher">The searcher.</param>
 /// <param name="reader">The reader.</param>
 /// <param name="docs">The hits.</param>
 /// <param name="criteria">The criteria.</param>
 /// <param name="query">The query.</param>
 public LuceneSearchResults(Searcher searcher, IndexReader reader, TopDocs docs, ISearchCriteria criteria, Query query)
 {
     Results = new SearchResults(criteria, null);
     CreateDocuments(searcher, docs);
     CreateFacets(reader, query);
     CreateSuggestions(reader, criteria);
 }
示例#6
0
		public async Task<SearchResults> GetResultsByAuthorAsync(ApplicationUser user, int skip, int count)
		{
			if (user == null)
				throw new ArgumentNullException();
			if (skip < 0 || count < 1)
				throw new ArgumentOutOfRangeException();

			var posts = await _postService.GetPostsByAuthorAsync(user, skip, count);
			var pages = await _pageService.GetPagesByAuthorAsync(user, skip, count);
			var postComments = await _postService.GetCommentsByAuthorAsync(user, skip, count);
			var pageComments = await _pageService.GetCommentsByAuthorAsync(user, skip, count);

			var results = new SearchResults
			{
				Posts = posts.Results,
				Pages = pages.Results,
				PostComments = postComments.Results,
				PageComments = pageComments.Results
			};
			results.ResultCount = results.Posts.Length + results.Pages.Length + results.PostComments.Length +
			                      results.PageComments.Length;
			results.TotalCount = posts.Total + pages.Total + postComments.Total + pageComments.Total;

			return results;
		}
		public CatalogItemSearchResults(ISearchCriteria criteria, Dictionary<string, Dictionary<string, object>> items, SearchResults results)
		{
			_Items = items;
			_TotalCount = results.TotalCount;
			_Count = results.DocCount;
			_FacetGroups = results.FacetGroups;
			_SearchCriteria = criteria;
		}
示例#8
0
        public SearchResults Get(string project, string query)
        {
            var searchResults = DocIndex.Search(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "index", project), query);
            SearchResults ret = new SearchResults();

            IProject proj;
            IAssembly assembly;
            INamespace ns;
            IType type;
            IMember member;

            foreach (var r in searchResults)
            {
                switch (r[0])
                {
                    case 'T':
                        type = _service.GetTypeSync(project, r);
                        ret.Add(type.Name.DisplayName, type.Category.ToString().ToLower(), helper.Url(type), type.NamespaceName);
                        break;

                    case 'M':
                        member = _service.GetMethodSync(project, r);
                        type = _service.GetTypeSync(project, ('T' + r.Substring(1)).Remove(r.Split('(')[0].LastIndexOf('.')));
                        if (member.Type == MemberType.Constructor)
                            ret.Add(member.DisplayName, "ctor", helper.Url(member));
                        else if (member.Type == MemberType.Operator)
                            ret.Add(member.DisplayName, "operator", helper.Url(member), type.Name.DisplayName);
                        else
                            ret.Add(member.DisplayName, "method", helper.Url(member), type.Name.DisplayName);
                        break;

                    case 'F':
                        member = _service.GetFieldSync(project, r);
                        type = _service.GetTypeSync(project, ('T' + r.Substring(1)).Remove(r.LastIndexOf('.')));
                        if (type.Category == TypeCategory.Enum)
                            ret.Add(member.DisplayName, "enum-field", helper.Url(type), type.Name.DisplayName);
                        else
                            ret.Add(member.DisplayName, "field", helper.Url(member), type.Name.DisplayName);
                        break;

                    case 'P':
                        member = _service.GetPropertySync(project, r);
                        type = _service.GetTypeSync(project, ('T' + r.Substring(1)).Remove(r.LastIndexOf('.')));
                        ret.Add(member.DisplayName, "property", helper.Url(member), type.Name.DisplayName);
                        break;

                    case 'E':
                        member = _service.GetEventSync(project, r);
                        type = _service.GetTypeSync(project, ('T' + r.Substring(1)).Remove(r.LastIndexOf('.')));
                        ret.Add(member.DisplayName, "event", helper.Url(member), type.Name.DisplayName);
                        break;

                    default:
                        throw new InvalidOperationException("Unknown xml-name");
                }
            }
            return ret;
        }
        public void Patient()
        {
            //id

            results = index.Search("Patient", "_id=xds");
            Assert.IsTrue(results.Has("Patient/xds"));

            // Adres
            results = index.Search("Patient", "address=44130");
            Assert.IsTrue(results.Has("Patient/xds"));

            results = index.Search("Patient", "address=44130&address=usa");
            Assert.IsTrue(results.Has("Patient/xds"));

            results = index.Search("Patient", "address=44130&address=fr");
            Assert.IsFalse(results.Has("Patient/xds"));

            // Animal-breed
            results = index.Search("Patient", "animal-breed=58108001");
            Assert.IsTrue(results.Has("Patient/animal"));

            results = index.Search("Patient", "animal-breed=/58108001");
            Assert.IsFalse(results.Has("Patient/animal"));

            // Birthdate
            results = index.Search("Patient", "birthdate=19911225");
            Assert.IsTrue(results.Has("http://hl7.org/fhir/Patient/77"));

            results = index.Search("Patient", "birthdate:before=1992");
            Assert.IsTrue(results.Has("http://hl7.org/fhir/Patient/77"));

            results = index.Search("Patient", "birthdate:before=1991");
            Assert.IsFalse(results.Has("http://hl7.org/fhir/Patient/77"));

            results = index.Search("Patient", "birthdate:after=1991");
            Assert.IsTrue(results.Has("http://hl7.org/fhir/Patient/77"));

            // Gender
            results = index.Search("Patient", "gender=M");
            Assert.IsTrue(results.Has("Patient/example"));

            //results = Factory.TestIndex.Search("patient", "identifier=...");
            // no testable data.

            // Language
            results = index.Search("Patient", "language=");
            Assert.IsTrue(results.Has("http://hl7.org/fhir/Patient/77"));

            // Telecom
            results = index.Search("Patient", "telecom=555-555-2007");
            Assert.IsTrue(results.Has("http://hl7.org/fhir/Patient/9"));

            // Phonetic
            results = index.Search("Patient", "phonetic=chalmurs");
            Assert.IsTrue(results.Has("Patient/example"));
        }
 public static ISearchResults Create(SearchResults<SearchResultItem> results, IQuery query)
 {
     var searchResults = CreateSearchResults(results);
       return new SearchResults
       {
     Results = searchResults,
     TotalNumberOfResults = results.TotalSearchResults,
     Query = query
       };
 }
示例#11
0
        private List<BsonValue> CollectKeys(string resourceType, IEnumerable<Criterium> criteria, SearchResults results, int level)
        {
            //Mapping of original criterium and closed criterium, the former to be able to exclude it if it errors later on.
            var closedCriteria = new Dictionary<Criterium, Criterium>();
            foreach (var c in criteria)
            {
                if (c.Operator == Operator.CHAIN)
                {
                    try
                    {
                        closedCriteria.Add(c.Clone(), CloseCriterium(c, resourceType, level));
                        //CK: We don't pass the SearchResults on to the (recursive) CloseCriterium. We catch any exceptions only on the highest level.
                    }
                    catch (ArgumentException ex)
                    {
                        if (results == null) throw; //The exception *will* be caught on the highest level.
                        results.AddIssue(String.Format("Parameter [{0}] was ignored for the reason: {1}.", c.ToString(), ex.Message), OperationOutcome.IssueSeverity.Warning);
                        results.UsedCriteria.Remove(c);
                    }
                }
                else
                {
                    //If it is not a chained criterium, we don't need to 'close' it, so it is said to be 'closed' already.
                    closedCriteria.Add(c, c);
                }
            }

            //All chained criteria are 'closed' or 'rolled up' to something like subject IN (id1, id2, id3), so now we AND them with the rest of the criteria.
            IMongoQuery resultQuery = CriteriaMongoExtensions.ResourceFilter(resourceType, level);
            if (closedCriteria.Count() > 0)
            {
                var criteriaQueries = new List<IMongoQuery>();
                foreach (var crit in closedCriteria)
                {
                    try
                    {
                        criteriaQueries.Add(crit.Value.ToFilter(resourceType));
                    }
                    catch (ArgumentException ex)
                    {
                        if (results == null) throw; //The exception *will* be caught on the highest level.
                        results.AddIssue(String.Format("Parameter [{0}] was ignored for the reason: {1}.", crit.Key.ToString(), ex.Message), OperationOutcome.IssueSeverity.Warning);
                        results.UsedCriteria.Remove(crit.Key);
                    }
                }
                if (criteriaQueries.Count > 0)
                {
                    IMongoQuery criteriaQuery = M.Query.And(criteriaQueries);
                    resultQuery = M.Query.And(resultQuery, criteriaQuery);
                }
            }

            return CollectKeys(resultQuery);
        }
示例#12
0
        private SearchResults KeysToSearchResults(IEnumerable<BsonValue> keys)
        {
            MongoCursor cursor = _collection.Find(M.Query.In(InternalField.ID, keys)).SetFields(InternalField.SELFLINK);

            var results = new SearchResults();
            foreach (BsonDocument document in cursor)
            {
                string id = document.GetValue(InternalField.SELFLINK).ToString();
                //Uri rid = new Uri(id, UriKind.Relative); // NB. these MUST be relative paths. If not, the data at time of input was wrong 
                results.Add(id);
            }
            return results;
        }
        public ActionResult Index(string searchText, int? page)
        {
            var pageIndex = (page ?? 1) - 1;
            int totalItemsCount;
            var model = new SearchResults()
            {
                Items = mService.Search(searchText, pageIndex, PAGE_SIZE, out totalItemsCount),
                PageIndex = pageIndex,
                PageSize = PAGE_SIZE,
                Query = searchText,
                TotalItemCount = totalItemsCount
            };

            return View(model);
        }
示例#14
0
 public void TestSearch()
 {
     var db = Directory.EnumerateFiles(Environment.CurrentDirectory).FirstOrDefault(x => x.Contains(DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString()));
     if (db == null) return;
     using (var reader = new StreamReader(db))
     {
         var results = new SearchResults();
         results.Results = new List<SearchResult>();
         reader.ReadToEnd().Split(new char[] { '\n' }).ToList().ForEach(x => { var result = new SearchResult(); result.Raw = x; results.Results.Add(result); });
         var info = new SearchResultsInfo();
         var search = new SearchProcessor();
         Assert.IsTrue(results.Results.Count > 0, "no results returned.");
         Assert.IsTrue(search.Execute(results, info), "Search failed.");
     }
 }
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            var results = new SearchResults();
            if (DisableMt) return results;

            foreach (var provider in _provider.MtProviders)
            {
                if (SearchShouldExecute(provider, settings))
                {
                    ITranslationProviderLanguageDirection languageDirection = provider.GetLanguageDirection(_languagePair);
                    var innerSearchResult = languageDirection.SearchSegment(settings, segment);
                    SetResultInSearchResults(ref results, innerSearchResult);
                }
            }
            OnTranslationFinished();
            return results;
        }
示例#16
0
        public HttpResponseMessage Get(string query, [FromUri] string[] sort)
		{
			int results;
			var keys = Search.Query(query, sort, Paging.Start, Paging.PageSize, out results);

            var list = new List<FileHeader>();

			Storage.Batch(accessor => list.AddRange(keys.Select(accessor.ReadFile).Where(x => x != null)));

			var result = new SearchResults
			{
				Start = Paging.Start,
				PageSize = Paging.PageSize,
				Files = list,
				FileCount = results
			};

            return this.GetMessageWithObject(result);
		}
示例#17
0
        public SearchResults Search(string resourceType, SearchParams searchCommand)
        {
            SearchResults results = new SearchResults();

            var criteria = parseCriteria(searchCommand, results);

            if (!results.HasErrors)
            {
                results.UsedCriteria = criteria;
                var normalizedCriteria = NormalizeNonChainedReferenceCriteria(criteria, resourceType);
                List<BsonValue> keys = CollectKeys(resourceType, normalizedCriteria, results);

                int numMatches = keys.Count();

                results.AddRange(KeysToSearchResults(keys));
                results.MatchCount = numMatches;
            }

            return results;
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);
            this.QueryStringToken = StorefrontConstants.QueryStrings.Paging;

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 20;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * itemsPerPage;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }
        }
        /// <summary>
        /// Initializes the view model
        /// </summary>
        /// <param name="rendering">The rendering</param>
        /// <param name="products">The list of child products</param>
        /// <param name="sortFields">The fields to allow sorting on</param>
        /// <param name="searchOptions">Any search options used to find products in this category</param>
        public void Initialize(Rendering rendering, SearchResults products, IEnumerable<CommerceQuerySort> sortFields, CommerceSearchOptions searchOptions)
        {
            base.Initialize(rendering);

            int itemsPerPage = (searchOptions != null) ? searchOptions.NumberOfItemsToReturn : 0;

            if (products != null)
            {
                var alreadyShown = products.CurrentPageNumber * searchOptions.NumberOfItemsToReturn;
                Pagination = new PaginationModel
                {
                    PageNumber = products.CurrentPageNumber,
                    TotalResultCount = products.TotalItemCount,
                    NumberOfPages = products.TotalPageCount,
                    PageResultCount = itemsPerPage,
                    StartResultIndex = alreadyShown + 1,
                    EndResultIndex = System.Math.Min(products.TotalItemCount, alreadyShown + itemsPerPage)
                };
            }

            SortFields = sortFields ?? Enumerable.Empty<CommerceQuerySort>();
        }
示例#20
0
        private List<BsonValue> CollectKeys(string resourceType, IEnumerable<Criterium> criteria, SearchResults results)
        {
            //Mapping of original criterium and closed criterium, the former to be able to exclude it if it errors.
            var closedCriteria = new Dictionary<Criterium, Criterium>();
            foreach (var c in criteria)
            {
                if (c.Type == Operator.CHAIN)
                {
                    closedCriteria.Add(c, CloseCriterium(c, resourceType));
                }
                else
                {
                    closedCriteria.Add(c, c);
                }
            }

            IMongoQuery resultQuery = CriteriaMongoExtensions.ResourceFilter(resourceType);
            if (closedCriteria.Count() > 0)
            {
                var criteriaQueries = new List<IMongoQuery>();
                foreach (var crit in closedCriteria)
                {
                    try
                    {
                        criteriaQueries.Add(crit.Value.ToFilter(resourceType));
                    }
                    catch (ArgumentException ex)
                    {
                        if (results == null) throw;
                        results.AddIssue(String.Format("Parameter [{0}] was ignored for the reason: {1}.", crit.Key.ToString(), ex.Message), OperationOutcome.IssueSeverity.Warning);
                        results.UsedCriteria.Remove(crit.Key);
                    }
                }
                if (criteriaQueries.Count > 0)
                {
                    IMongoQuery criteriaQuery = M.Query.And(criteriaQueries);
                    resultQuery = M.Query.And(resultQuery, criteriaQuery);
                }
            }

            return CollectKeys(resultQuery);
        }
示例#21
0
        public override int Execute(string[] args)
        {
            // sanity check
            if (args.Length != 2)
            {
                throw new ArgumentException("incorrect number of arguments");
            }

            Progress.Message = "Searching";
            string root = args[1];

            if (!Directory.Exists(root))
            {
                throw new DirectoryNotFoundException("directory: " + root.QuoteDouble() +
                                                     " does not exists");
            }

            List <string> files = IO.GetAllFiles(root, "*.*");

            if (files.Count == 0)
            {
                throw new FileNotFoundException("unable to find any files in root: " +
                                                root.QuoteDouble());
            }

            var fileChangeResults = new List <SearchResults>();

            foreach (string file in files)
            {
                try
                {
                    Progress.Message = "Cleaning " + IO.GetFilename(file);
                    var changes = new SearchResults(file);

                    switch (IO.GetFileExtension(file).ToLower())
                    {
                    case "vb":
                        changes.AddResults(VBStyleRules.FixShortLines(file));
                        changes.AddResults(VBStyleRules.FixLineContinuations(file));
                        changes.AddResults(VBStyleRules.FixEmptyLines(file));
                        fileChangeResults.Add(changes);
                        break;

                    case "cs":
                        // skip automatically generated source
                        if (file.Contains(".Designer.cs") || file.Contains("AssemblyInfo.cs"))
                        {
                            continue;
                        }

                        string content = IO.ReadFileAsUtf8(file);
                        var    strings = CSStyleRules.RemoveStrings(ref content);
                        changes.AddResults(CSStyleRules.SortUsingDirectives(ref content));
                        changes.AddResults(CSStyleRules.FixSemicolon(ref content));
                        changes.AddResults(CSStyleRules.FixSwitchStatements(ref content));
                        changes.AddResults(CSStyleRules.FixBraces(ref content));
                        changes.AddResults(CSStyleRules.FixBrackets(ref content));
                        changes.AddResults(CSStyleRules.FixEmptyLines(ref content));
                        changes.AddResults(CSStyleRules.FixSpaces(ref content));
                        fileChangeResults.Add(changes);
                        CSStyleRules.RevertStrings(ref content, strings);
                        CSStyleRules.Save(changes, content);
                        break;

                    default:
                        break;
                    }

                    if (changes.Matches.Count > 0)
                    {
                        ConsoleHelper.WriteLine("");
                        ConsoleHelper.WriteLine(IO.GetFilename(file), ConsoleColor.Yellow);

                        foreach (var change in changes.Matches)
                        {
                            ConsoleHelper.Write("  +line ");
                            ConsoleHelper.Write(change.LineNumbrer.ToString(), ConsoleColor.White);
                            ConsoleHelper.WriteLine(": " + change.Reason);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ConsoleHelper.WriteException(ex);
                }
            }

            return(ConsoleHelper.EXIT_OK);
        }
示例#22
0
        private List <BsonValue> CollectSelfLinks(string resourceType, IEnumerable <Criterium> criteria, SearchResults results, int level, IList <Tuple <string, SortOrder> > sortItems)
        {
            Dictionary <Criterium, Criterium> closedCriteria = CloseChainedCriteria(resourceType, criteria, results, level);

            //All chained criteria are 'closed' or 'rolled up' to something like subject IN (id1, id2, id3), so now we AND them with the rest of the criteria.
            IMongoQuery  resultQuery = CreateMongoQuery(resourceType, results, level, closedCriteria);
            IMongoSortBy sortBy      = CreateSortBy(sortItems);

            return(CollectSelfLinks(resultQuery, sortBy));
        }
示例#23
0
 public SearchModel(string searchRecord)
 {
     searchSource = searchRecord;
     try
     {
         DateTime output = DateTime.Parse(searchSource);
         searchType = SearchType.DateOfBirth;
         //if (output.ToString("d/M/yy") == searchSource.ToString())
         if (searchSource.Count(c => c == '/') == 2)
         {
             searchResults = SearchResults.getMatches(output);
         }
         else
         {
             searchResults = SearchResults.getMatches(output.Month, output.Day);
         }
         isValid = true;
         return;
     }
     catch
     {
         isValid    = false;
         searchType = null;
     }
     try
     {
         if (rxText.IsMatch(searchSource))
         {
             searchType    = SearchType.Name;
             isValid       = true;
             searchResults = SearchResults.getMatches(searchSource);
             return;
         }
     }
     catch
     {
         isValid = false;
     }
     try
     {
         if (rxNumeric.IsMatch(searchSource))
         {
             search     = Int32.Parse(searchSource);
             searchType = SearchType.RecordNumber;
             isValid    = true;
         }
     }
     catch
     {
         errorMessage = string.Format("Your search text '{0}' could not be converted into the TRxxxxxx format", searchSource);
         isValid      = false;
         searchType   = null;
         return;
     }
     using (TipstaffDB db = new TipstaffDB())
     {
         tipstaffRecord = db.TipstaffRecord.Find(search);
     }
     if (tipstaffRecord == null && search > 0)
     {
         errorMessage = string.Format("No record could be found that matched '{0}' ", string.Format("TR{0}", search.ToString("D6")));
         isValid      = false;
         searchType   = null;
         return;
     }
     try
     {
         RecordType = genericFunctions.TypeOfTipstaffRecord(tipstaffRecord);
     }
     catch
     {
         errorMessage = string.Format("Type of record could not be determined");
         isValid      = false;
         searchType   = null;
         return;
     }
 }
示例#24
0
        /**
         * <summary>
         * Attempts to perform a search requests, on any exception attempts to load from local cache.
         * </summary>
         * <param name="searchText"></param>
         * <param name="sorting"></param>
         * <param name="onlyCurrentUser"></param>
         * <param name="projectKey"></param>
         * <param name="statuses"></param>
         * <param name="profile"></param>
         * <returns></returns>
         */
        async public Task <SearchResults> Search(string searchText, string sorting, bool onlyCurrentUser, string projectKey, List <string> statuses, List <string> issueTypes, Profile profile, AnonymousToken isValid)
        {
            try
            {
                var SearchParams = new SearchSettings()
                {
                    Summary = searchText,
                    Sorting = sorting,
                    AssignedToCurrentUser = onlyCurrentUser,
                    Project    = projectKey,
                    Statuses   = statuses,
                    IssueTypes = issueTypes
                };

                var results = await jira.Issues.GetIssuesFromJqlAsync(SearchParams.ToString());

                var issues = new ObservableCollection <Issue>();
                foreach (JiraIssue issue in results)
                {
                    Issue item = new Issue();
                    item.Status     = issue.Status.Name;
                    item.ProjectKey = issue.Project;
                    item.Key        = issue.Key.Value;
                    item.Value      = issue.Summary;
                    item.Summary    = issue.Summary;
                    item.Type       = issue.Type.Name;
                    item.TypeId     = issue.Type.Id;
                    item.TimeSpent  = issue.TimeTrackingData.TimeSpent;
                    issues.Add(item);
                    profile.Issues[item.Key] = item;
                }

                //save profile
                AppState.Profiles.Save();

                var searchResults = new SearchResults()
                {
                    Offline = false,
                    Issues  = issues,
                    Valid   = isValid.Valid
                };

                return(searchResults);
            }
            catch (Exception e)
            {
                AppState.Logger.Log(this, "Search", e.Message);
                var issues = new ObservableCollection <Issue>();
                foreach (Issue item in profile.Issues.Values)
                {
                    if (projectKey.Length > 0 && item.ProjectKey != projectKey)
                    {
                        continue;
                    }

                    if (statuses.Count > 0 && !statuses.Contains(item.Status))
                    {
                        continue;
                    }

                    if (!item.Value.Contains(searchText, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    if (issueTypes.Count > 0 && !issueTypes.Contains(item.TypeId))
                    {
                        continue;
                    }

                    issues.Add(item);
                }

                var searchResults = new SearchResults()
                {
                    Offline = true,
                    Issues  = issues,
                    Valid   = isValid.Valid
                };

                return(searchResults);
            }
        }
示例#25
0
        private Dictionary <Criterium, Criterium> CloseChainedCriteria(string resourceType, IEnumerable <Criterium> criteria, SearchResults results, int level)
        {
            //Mapping of original criterium and closed criterium, the former to be able to exclude it if it errors later on.
            var closedCriteria = new Dictionary <Criterium, Criterium>();

            foreach (var c in criteria)
            {
                if (c.Operator == Operator.CHAIN)
                {
                    try
                    {
                        closedCriteria.Add(c.Clone(), CloseCriterium(c, resourceType, level));
                        //CK: We don't pass the SearchResults on to the (recursive) CloseCriterium. We catch any exceptions only on the highest level.
                    }
                    catch (ArgumentException ex)
                    {
                        if (results == null)
                        {
                            throw;                  //The exception *will* be caught on the highest level.
                        }
                        results.AddIssue(String.Format("Parameter [{0}] was ignored for the reason: {1}.", c.ToString(), ex.Message), OperationOutcome.IssueSeverity.Warning);
                        results.UsedCriteria.Remove(c);
                    }
                }
                else
                {
                    //If it is not a chained criterium, we don't need to 'close' it, so it is said to be 'closed' already.
                    closedCriteria.Add(c, c);
                }
            }

            return(closedCriteria);
        }
示例#26
0
        private void AddSchemaUrl(SearchResults result, NamedId <Guid> appId, NamedId <Guid> schemaId, string name)
        {
            var schemaUrl = urlGenerator.SchemaUI(appId, schemaId);

            result.Add($"{name} Schema", SearchResultType.Schema, schemaUrl);
        }
示例#27
0
 /// <summary>
 /// Froms the specified page.
 /// </summary>
 /// <param name="page">The page.</param>
 /// <returns></returns>
 public static SearchResultsScript Initialize(SearchResults page)
 {
     SearchResultsScript searchResultsScript = new SearchResultsScript();
     searchResultsScript.Id = page.ID;
     searchResultsScript.ClientId = page.ClientID;
     searchResultsScript.TargetAccount = _integrationManager.TargetMapping.Name;
     searchResultsScript.SourceAccountId = _integrationManager.SourceAccount.Id.ToString();
     searchResultsScript.ResourceTypeName = "tradingAccount";
     searchResultsScript.OptionRefineSearchId = page.rdbRefineSearch.ClientID;
     searchResultsScript.DescriptionText = page.GetLocalResourceObject("refineSearch_DescriptionText");
     searchResultsScript.HeaderText = page.GetLocalResourceObject("refineSearch_HeaderText");
     searchResultsScript.PropertyValue = page.GetLocalResourceObject("refineSearch_PropertyValue");
     searchResultsScript.OperatorValue = page.GetLocalResourceObject("refineSearch_OperatorValue");
     searchResultsScript.SearchValue = page.GetLocalResourceObject("refineSearch_SearchValue");
     searchResultsScript.DialogCaption = page.GetLocalResourceObject("refineSearch_DialogCaption");
     searchResultsScript.ErrorSaveConfig = page.GetLocalResourceObject("refineSearch_error_saveConfig");
     searchResultsScript.CancelButton = page.GetLocalResourceObject("refineSearch_CancelButton");
     searchResultsScript.OKButton = page.GetLocalResourceObject("refineSearch_OkButton");
     searchResultsScript.RefreshGridId = page.btnRefreshGrid.ClientID;
     searchResultsScript.FiltersId = page.txtFilters.ClientID;
     searchResultsScript.RowLinkToId = page.rowLinkTo.ClientID;
     searchResultsScript.RowSearchResultsId = page.rowSearchResults.ClientID;
     searchResultsScript.ResultsMsgId = page.lblResultsMsg.ClientID;
     searchResultsScript.LoadingDisplay = page.GetLocalResourceObject("lblLoading.Caption");
     ISessionService sessionService = ApplicationContext.Current.Services.Get<ISessionService>(true);
     ISessionState sessionState = sessionService.GetSessionState();
     sessionState["IntegrationManager"] = _integrationManager;
     return searchResultsScript;
 }
示例#28
0
        public async Task CreateIndexerAsync()
        {
            await using SearchResources resources = await SearchResources.CreateWithBlobStorageAsync(this, populate : true);

            Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString());
            Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey);
            Environment.SetEnvironmentVariable("STORAGE_CONNECTION_STRING", resources.StorageAccountConnectionString);
            Environment.SetEnvironmentVariable("STORAGE_CONTAINER", resources.BlobContainerName);
            Environment.SetEnvironmentVariable("COGNITIVE_SERVICES_KEY", resources.CognitiveServicesKey);

            // Define clean up tasks to be invoked in reverse order added.
            Stack <Func <Task> > cleanUpTasks = new Stack <Func <Task> >();

            try
            {
                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateSynonymMap
                // Create a new SearchIndexClient
                Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
                AzureKeyCredential credential = new AzureKeyCredential(
                    Environment.GetEnvironmentVariable("SEARCH_API_KEY"));
                SearchIndexClient indexClient = new SearchIndexClient(endpoint, credential);
#if !SNIPPET
                indexClient = resources.GetIndexClient(new SearchClientOptions(ServiceVersion));
#endif

                // Create a synonym map from a file containing country names and abbreviations
                // using the Solr format with entry on a new line using \n, for example:
                // United States of America,US,USA\n
                string synonymMapName = "countries";
#if !SNIPPET
                synonymMapName = Recording.Random.GetName();
#endif
                string synonymMapPath = "countries.txt";
#if !SNIPPET
                synonymMapPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Samples", "countries.txt");
#endif

                SynonymMap synonyms;
#if SNIPPET
                using (StreamReader file = File.OpenText(synonymMapPath))
                {
                    synonyms = new SynonymMap(synonymMapName, file);
                }
#else
                synonyms = new SynonymMap(synonymMapName, CountriesSolrSynonymMap);
#endif

                await indexClient.CreateSynonymMapAsync(synonyms);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateSynonymMap

                // Make sure our synonym map gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexClient.DeleteSynonymMapAsync(synonymMapName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndex
                // Create the index
                string indexName = "hotels";
#if !SNIPPET
                indexName = Recording.Random.GetName();
#endif
                SearchIndex index = new SearchIndex(indexName)
                {
                    Fields =
                    {
                        new SimpleField("hotelId",                    SearchFieldDataType.String)
                        {
                            IsKey = true,                             IsFilterable = true, IsSortable  = true
                        },
                        new SearchableField("hotelName")
                        {
                            IsFilterable = true,                      IsSortable   = true
                        },
                        new SearchableField("description")
                        {
                            AnalyzerName = LexicalAnalyzerName.EnLucene
                        },
                        new SearchableField("descriptionFr")
                        {
                            AnalyzerName = LexicalAnalyzerName.FrLucene
                        },
                        new SearchableField("tags",                   collection: true)
                        {
                            IsFilterable = true,                      IsFacetable  = true
                        },
                        new ComplexField("address")
                        {
                            Fields =
                            {
                                new SearchableField("streetAddress"),
                                new SearchableField("city")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                },
                                new SearchableField("stateProvince")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                },
                                new SearchableField("country")
                                {
                                    SynonymMapNames = new[] { synonymMapName },IsFilterable               = true, IsSortable  = true,IsFacetable          = true
                                },
                                new SearchableField("postalCode")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                }
                            }
                        }
                    }
                };

                await indexClient.CreateIndexAsync(index);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndex

                // Make sure our synonym map gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexClient.DeleteIndexAsync(indexName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateDataSourceConnection
                // Create a new SearchIndexerClient
                SearchIndexerClient indexerClient = new SearchIndexerClient(endpoint, credential);
#if !SNIPPET
                indexerClient = resources.GetIndexerClient();
#endif

                string dataSourceConnectionName = "hotels";
#if !SNIPPET
                dataSourceConnectionName = Recording.Random.GetName();
#endif
                SearchIndexerDataSourceConnection dataSourceConnection = new SearchIndexerDataSourceConnection(
                    dataSourceConnectionName,
                    SearchIndexerDataSourceType.AzureBlob,
                    Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"),
                    new SearchIndexerDataContainer(Environment.GetEnvironmentVariable("STORAGE_CONTAINER")));

                await indexerClient.CreateDataSourceConnectionAsync(dataSourceConnection);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateDataSourceConnection

                // Make sure our data source gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteDataSourceConnectionAsync(dataSourceConnectionName));

#if SNIPPET
                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_SearchClientOptions
                // Create SearchIndexerClient options
                SearchClientOptions options = new SearchClientOptions()
                {
                    Transport = new HttpClientTransport(new HttpClient()
                    {
                        // Increase timeout for each request to 5 minutes
                        Timeout = TimeSpan.FromMinutes(5)
                    });
                };

                // Increase retry attempts to 6
                options.Retry.MaxRetries = 6;

                // Create a new SearchIndexerClient with options
                indexerClient = new SearchIndexerClient(endpoint, credential, options);
                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_SearchClientOptions
#endif

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Skillset
                // Translate English descriptions to French.
                // See https://docs.microsoft.com/azure/search/cognitive-search-skill-text-translation for details of the Text Translation skill.
                TextTranslationSkill translationSkill = new TextTranslationSkill(
                    inputs: new[]
                {
                    new InputFieldMappingEntry("text")
                    {
                        Source = "/document/description"
                    }
                },
                    outputs: new[]
                {
                    new OutputFieldMappingEntry("translatedText")
                    {
                        TargetName = "descriptionFrTranslated"
                    }
                },
                    TextTranslationSkillLanguage.Fr)
                {
                    Name    = "descriptionFrTranslation",
                    Context = "/document",
                    DefaultFromLanguageCode = TextTranslationSkillLanguage.En
                };

                // Use the human-translated French description if available; otherwise, use the translated description.
                // See https://docs.microsoft.com/azure/search/cognitive-search-skill-conditional for details of the Conditional skill.
                ConditionalSkill conditionalSkill = new ConditionalSkill(
                    inputs: new[]
                {
                    new InputFieldMappingEntry("condition")
                    {
                        Source = "= $(/document/descriptionFr) == null"
                    },
                    new InputFieldMappingEntry("whenTrue")
                    {
                        Source = "/document/descriptionFrTranslated"
                    },
                    new InputFieldMappingEntry("whenFalse")
                    {
                        Source = "/document/descriptionFr"
                    }
                },
                    outputs: new[]
                {
                    new OutputFieldMappingEntry("output")
                    {
                        TargetName = "descriptionFrFinal"
                    }
                })
                {
                    Name    = "descriptionFrConditional",
                    Context = "/document",
                };

                // Create a SearchIndexerSkillset that processes those skills in the order given below.
                string skillsetName = "translations";
#if !SNIPPET
                skillsetName = Recording.Random.GetName();
#endif
                SearchIndexerSkillset skillset = new SearchIndexerSkillset(
                    skillsetName,
                    new SearchIndexerSkill[] { translationSkill, conditionalSkill })
                {
                    CognitiveServicesAccount = new CognitiveServicesAccountKey(
                        Environment.GetEnvironmentVariable("COGNITIVE_SERVICES_KEY")),
                    KnowledgeStore = new KnowledgeStore(
                        Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"),
                        new List <KnowledgeStoreProjection>()),
                };

                await indexerClient.CreateSkillsetAsync(skillset);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Skillset

                // Make sure our skillset gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteSkillsetAsync(skillsetName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndexer
                string indexerName = "hotels";
#if !SNIPPET
                indexerName = Recording.Random.GetName();
#endif
                SearchIndexer indexer = new SearchIndexer(
                    indexerName,
                    dataSourceConnectionName,
                    indexName)
                {
                    // We only want to index fields defined in our index, excluding descriptionFr if defined.
                    FieldMappings =
                    {
                        new FieldMapping("hotelId"),
                        new FieldMapping("hotelName"),
                        new FieldMapping("description"),
                        new FieldMapping("tags"),
                        new FieldMapping("address")
                    },
                    OutputFieldMappings =
                    {
                        new FieldMapping("/document/descriptionFrFinal")
                        {
                            TargetFieldName = "descriptionFr"
                        }
                    },
                    Parameters = new IndexingParameters
                    {
                        // Tell the indexer to parse each blob as a separate JSON document.
                        IndexingParametersConfiguration = new IndexingParametersConfiguration
                        {
                            ParsingMode = BlobIndexerParsingMode.Json
                        }
                    },
                    SkillsetName = skillsetName
                };

                // Create the indexer which, upon successful creation, also runs the indexer.
                await indexerClient.CreateIndexerAsync(indexer);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndexer

                // Make sure our indexer gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteIndexerAsync(indexerName));

                // Wait till the indexer is done.
                await WaitForIndexingAsync(indexerClient, indexerName);

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Query
                // Get a SearchClient from the SearchIndexClient to share its pipeline.
                SearchClient searchClient = indexClient.GetSearchClient(indexName);
#if !SNIPPET
                searchClient = InstrumentClient(new SearchClient(endpoint, indexName, credential, GetSearchClientOptions()));
#endif

                // Query for hotels with an ocean view.
                SearchResults <Hotel> results = await searchClient.SearchAsync <Hotel>("ocean view");

#if !SNIPPET
                bool found = false;
#endif
                await foreach (SearchResult <Hotel> result in results.GetResultsAsync())
                {
                    Hotel hotel = result.Document;
#if !SNIPPET
                    if (hotel.HotelId == "6")
                    {
                        Assert.IsNotNull(hotel.DescriptionFr); found = true;
                    }
#endif

                    Console.WriteLine($"{hotel.HotelName} ({hotel.HotelId})");
                    Console.WriteLine($"  Description (English): {hotel.Description}");
                    Console.WriteLine($"  Description (French):  {hotel.DescriptionFr}");
                }
                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Query

                Assert.IsTrue(found, "Expected hotel #6 not found in search results");
            }
            finally
            {
                // We want to await these individual to create a deterministic order for playing back tests.
                foreach (Func <Task> cleanUpTask in cleanUpTasks)
                {
                    await cleanUpTask();
                }
            }
        }
示例#29
0
        public SearchResults <Document> Search(string query, string discoveryType, int pageNumber, int pageSize, bool shouldDocumentsBeClustered, string sort)
        {
            try
            {
                Global.RefreshIndexSearcher();

                if (string.IsNullOrEmpty(discoveryType))
                {
                    discoveryType = "WebPage";
                }
                if (pageNumber == 0)
                {
                    pageNumber = 1;
                }
                if (pageSize == 0)
                {
                    pageSize = 20;
                }
                if (string.IsNullOrEmpty(sort))
                {
                }

                SearchResults <Lucene.Net.Documents.Document> searchResults = SearchManager.GetDocuments(Global.DefaultQueryParser, Global.CustomQueryParser, Global.IndexSearcher, query, (DiscoveryType)Enum.Parse(typeof(DiscoveryType), discoveryType), pageNumber, pageSize, shouldDocumentsBeClustered, sort, WebSettings.MaximumNumberOfDocumentsToReturnPerSearch);

                SearchResults <Document> searchResults2 = new SearchResults <Document>();

                searchResults2.Documents         = new List <Document>(searchResults.Documents.Count);
                searchResults2.TotalNumberOfHits = searchResults.TotalNumberOfHits;

                foreach (Lucene.Net.Documents.Document document in searchResults.Documents)
                {
                    try
                    {
                        Document document2 = new Document();

                        document2.AbsoluteUri   = document.GetField("absoluteuri").StringValue();
                        document2.Created       = DateTools.StringToDate(document.GetField("created").StringValue());
                        document2.DiscoveryID   = long.Parse(document.GetField("discoveryid").StringValue());
                        document2.DiscoveryPath = document.GetField("discoverypath").StringValue();
                        document2.Domain        = document.GetField("domain").StringValue();
                        document2.Extension     = document.GetField("extension").StringValue();
                        document2.Host          = document.GetField("host").StringValue();
                        document2.Scheme        = document.GetField("scheme").StringValue();
                        document2.Score         = float.Parse(document.GetField("relevancyscore").StringValue());
                        document2.Strength      = float.Parse(document.GetField("strength").StringValue());

                        string text = null;

                        if (File.Exists(document2.DiscoveryPath))
                        {
                            text = File.ReadAllText(document2.DiscoveryPath, Encoding.GetEncoding(int.Parse(document.GetField("codepage").StringValue())));
                        }
                        else
                        {
                            ArachnodeDataSet.WebPagesRow webPagesRow = ArachnodeDAO.GetWebPage(document2.DiscoveryID.ToString());

                            if (webPagesRow != null && webPagesRow.Source != null)
                            {
                                text = Encoding.GetEncoding(webPagesRow.CodePage).GetString(webPagesRow.Source);
                            }
                        }

                        if (text != null)
                        {
                            document2.Summary = SearchManager.Summarize(searchResults.Query, searchResults.WildcardSafeQuery, shouldDocumentsBeClustered, text);
                        }
                        else
                        {
                            document2.Summary = "The WebPage source was not found in the database or on disk.";

                            try
                            {
                                throw new Exception("The WebPage source for " + document2.AbsoluteUri + " was not found in the database or on disk.");
                            }
                            catch (Exception exception)
                            {
                                ArachnodeDAO.InsertException(null, null, exception, false);
                            }
                        }

                        document2.Title = document.GetField("title").StringValue();
                        if (document.GetField("updated") != null)
                        {
                            document2.Updated = DateTools.StringToDate(document.GetField("updated").StringValue());
                        }

                        searchResults2.Documents.Add(document2);
                    }
                    catch (Exception exception)
                    {
                        ArachnodeDAO.InsertException(null, null, exception, false);
                    }
                }

                return(searchResults2);
            }
            catch (Exception exception)
            {
                ArachnodeDAO.InsertException(null, null, exception, false);
            }

            return(null);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GenericSearchResponse{T}"/> class.
 /// </summary>
 /// <param name="results">
 /// The results.
 /// </param>
 public GenericSearchResponse(SearchResults <T> results)
 {
     this.TotalResults = results.TotalSearchResults;
     this.Results      = results.GetDocuments();
     this.Facets       = results.Facets;
 }
示例#31
0
        static public IEnumerable <SearchResults> AddToSearchResults(IEnumerable <SearchResults> IEnumerableCol, SearchResults item)
        {
            List <SearchResults> tempList = new List <SearchResults>();

            if (IEnumerableCol == null)
            {
                tempList.Add(item);
            }
            else
            {
                tempList = IEnumerableCol.ToList();
                tempList.Add(item);
            }
            return(tempList);
        }
示例#32
0
 public abstract IEnumerable <IFilterOptionModel> GetFilterOptions(SearchResults <IFacetContent> searchResults, ListingMode mode);
 public SearchResults[] SearchSegments(SearchSettings settings, Segment[] segments)
 {
     SearchResults[] results = new SearchResults[segments.Length];
     for (int p = 0; p < segments.Length; ++p)
     {
         results[p] = SearchSegment(settings, segments[p]);
     }
     return results;
 }
示例#34
0
 protected override EndSearchMessage OnEndSearch(SearchResults results)
 {
     return(new EndSearchMessage(results, true));
 }
 public SearchResults[] SearchTranslationUnits(SearchSettings settings, TranslationUnit[] translationUnits)
 {
     SearchResults[] results = new SearchResults[translationUnits.Length];
     for (int p = 0; p < translationUnits.Length; ++p)
     {
         //need to use the tu confirmation level in searchsegment method
         inputTu = translationUnits[p];
         results[p] = SearchSegment(settings, translationUnits[p].SourceSegment); //changed this to send whole tu
     }
     return results;
 }
示例#36
0
        public JObject GetProducts(ProductSearchData productSearchData)
        {
            // If we do not get any facets as part of query, we use the default facets from the registry
            var facetRegistry = ServiceLocator.Current.GetInstance <FacetRegistry>();

            if (productSearchData.ProductData.Facets == null || productSearchData.ProductData.Facets.Any() == false)
            {
                productSearchData.ProductData.Facets = new List <FacetValues>();
                foreach (FacetDefinition definition in facetRegistry.FacetDefinitions)
                {
                    var valuesForFacet = new FacetValues()
                    {
                        Definition = definition
                    };
                    productSearchData.ProductData.Facets.Add(valuesForFacet);
                }
            }

            // The language is part of the route
            string language = Language;

            // search term, used if part of freetext search
            var searchTerm = productSearchData.ProductData.SearchTerm;
            SearchResults <FindProduct> productsSearchResult = GetProductsForSearchAndFilters(productSearchData, searchTerm, language);

            string selectedFacetName   = productSearchData.ProductData.SelectedFacetName ?? string.Empty;
            var    productFacetsResult = GetFacetResult(productSearchData, language, productSearchData.ProductData.Facets, searchTerm);

            // parse facet results
            IEnumerable <TermCount> productCategoryFacetsResult = productFacetsResult.TermsFacetFor(x => x.ParentCategoryName).Terms;
            List <FacetViewModel>   allProductCategoryFacets    = CreateCategoryFacetViewModels(productCategoryFacetsResult,
                                                                                                productSearchData.ProductData.SelectedProductCategories.Select(x => x.ToString()).ToList());

            // Get all facet values based on facet registry
            var facetsAndValues = GetFacetsAndValues(productFacetsResult, productSearchData.ProductData.Facets);

            // If we're doing a filtering on a specific facet, we handle that one
            // in a special way, in order to show the count for all terms for the facet
            SearchResults <FindProduct> productSelectedFacetsResult = null;

            if (string.IsNullOrEmpty(selectedFacetName) == false)
            {
                List <FacetValues> selectedFacet = new List <FacetValues>();
                if (productSearchData.ProductData.Facets != null)
                {
                    FacetValues selectedValues = productSearchData.ProductData.Facets.Find(f => f.Definition.Name.Equals(selectedFacetName));
                    if (selectedValues != null)
                    {
                        selectedFacet.Add(selectedValues);
                    }
                }

                // Get facet values and counts for the selected facet
                productSelectedFacetsResult = GetFacetResult(
                    productSearchData,
                    language,
                    selectedFacet,
                    searchTerm, applyFacetFilters: false);

                // Treat the selected faced specially, as it might show more data if it is selected
                facetsAndValues = GetFacetsAndValues(productSelectedFacetsResult, facetsAndValues);
            }

            var result = new
            {
                products = productsSearchResult.ToList(),
                productCategoryFacets = allProductCategoryFacets,
                facets      = facetsAndValues,
                totalResult = productsSearchResult.TotalMatching
            };

            var serializer = new JsonSerializer();

            serializer.TypeNameHandling = TypeNameHandling.Auto;

            return(JObject.FromObject(result, serializer));
        }
示例#37
0
        //public static IEnumerable<ElasticHelper> Search(string query, string scrollID, out SearchResults r)
        //{
        //    return Search(query, Collection, scrollID, out r);
        //}
        public static IEnumerable <ElasticHelper> Search(string query, string index, string scrollID, out SearchResults r)
        {
            IEnumerable <ElasticHelper> tmp = new List <ElasticHelper>();

            r = Search(query, index, scrollID);

            if (r.hits != null && r.hits.total > 0)
            {
                tmp = r.hits.hits.Select(h => Newtonsoft.Json.JsonConvert.DeserializeObject <ElasticHelper>(h.ToString()));
            }

            return(tmp);
        }
        public void CreateIndex(string name, IEnumerable<IFieldDefinition> fieldDefinitions)
        {
            //You must add here your accessKey and SecretAccessKey. See here how to get them: http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html
            using (IAmazonCloudSearch cloudSearchClient = AWSClientFactory.CreateAmazonCloudSearchClient(AmazonSearchService.AwsAccessKey, AmazonSearchService.AwsSecretAccessKey, RegionEndpoint.EUWest1))
            {
                try
                {
                    CreateDomainRequest domainRequest = new CreateDomainRequest();
                    domainRequest.DomainName = name;
                    cloudSearchClient.CreateDomain(domainRequest);

                    if (fieldDefinitions == null)
                        throw new ArgumentNullException("fieldDefinitions");

                    foreach (var fieldDefinition in fieldDefinitions)
                    {
                        DefineIndexFieldRequest request = new DefineIndexFieldRequest();
                        request.DomainName = name;
                        request.IndexField = new IndexField();
                        request.IndexField.IndexFieldName = fieldDefinition.Name.ToUpperInvariant();
                        if (fieldDefinition.Type == null || fieldDefinition.Type == typeof(string))
                            request.IndexField.IndexFieldType = IndexFieldType.Text;
                        if (fieldDefinition.Type == typeof(string[]))
                            request.IndexField.IndexFieldType = IndexFieldType.TextArray;
                        if (fieldDefinition.Type == typeof(int))
                            request.IndexField.IndexFieldType = IndexFieldType.Int;
                        if (fieldDefinition.Type == typeof(DateTime))
                            request.IndexField.IndexFieldType = IndexFieldType.Date;
                        cloudSearchClient.DefineIndexField(request);
                    }

                    SearchResults searchResults = new SearchResults();
                    foreach (var field in searchResults.HighlightedFields)
                    {
                        Suggester suggester = new Suggester();
                        DocumentSuggesterOptions suggesterOptions = new DocumentSuggesterOptions();
                        suggesterOptions.FuzzyMatching = SuggesterFuzzyMatching.None;
                        suggesterOptions.SourceField = field.ToUpperInvariant();
                        suggester.DocumentSuggesterOptions = suggesterOptions;
                        suggester.SuggesterName = field.ToUpperInvariant() + "_suggester";
                        DefineSuggesterRequest defineRequest = new DefineSuggesterRequest();
                        defineRequest.DomainName = name;
                        defineRequest.Suggester = suggester;
                        cloudSearchClient.DefineSuggester(defineRequest);
                    }

                    searchResults.Dispose();

                    IndexDocumentsRequest documentRequest = new IndexDocumentsRequest();
                    documentRequest.DomainName = name;
                    cloudSearchClient.IndexDocuments(documentRequest);
                }
                catch (BaseException ex)
                {
                    Log.Write(ex.InnerException.Message);
                }
                catch (LimitExceededException ex)
                {
                    Log.Write(ex.InnerException.Message);
                }
                catch (InternalException ex)
                {
                    Log.Write(ex.InnerException.Message);
                }
            }
        }
示例#39
0
 public void Initialize()
 {
     HomePage      = new HomePage(WebDriver, ExtentReports, ExtentTest);
     SearchResults = new SearchResults(WebDriver, ExtentReports, ExtentTest);
 }
 public void AddPackageResult(PackageViewModel package)
 => SearchResults.Add(package);
示例#41
0
        private List <Criterium> EnrichCriteriaWithSearchParameters(ResourceType resourceType, SearchResults results)
        {
            var result  = new List <Criterium>();
            var notUsed = new List <Criterium>();

            foreach (var crit in results.UsedCriteria)
            {
                if (TryEnrichCriteriumWithSearchParameters(crit, resourceType))
                {
                    result.Add(crit);
                }
                else
                {
                    notUsed.Add(crit);
                    results.AddIssue(String.Format("Parameter with name {0} is not supported for resource type {1}.", crit.ParamName, resourceType), OperationOutcome.IssueSeverity.Warning);
                }
            }

            results.UsedCriteria = results.UsedCriteria.Except(notUsed).ToList();

            return(result);
        }
示例#42
0
        /// <summary>
        /// Performs the actual search by looping through the
        /// delimited segment pairs contained in the text file.
        /// Depening on the search mode, a segment lookup (with exact machting) or a source / target
        /// concordance search is done.
        /// </summary>
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            var translation = new Segment(_languageDirection.TargetCulture);            //this will be the target segment

            var results = new SearchResults();

            results.SourceSegment = segment.Duplicate();

            if (!_options.ResendDrafts && _inputTu.ConfirmationLevel != ConfirmationLevel.Unspecified) //i.e. if it's status is other than untranslated
            {                                                                                          //don't do the lookup, b/c we don't need to pay google to translate text already translated if we edit a segment
                translation.Add(PluginResources.TranslationLookupDraftNotResentMessage);
                //later get these strings from resource file
                results.Add(CreateSearchResult(segment, translation));
                return(results);
            }

            // Look up the currently selected segment in the collection (normal segment lookup).

            var translatedText = "";
            //a new seg avoids modifying the current segment object
            var newseg = segment.Duplicate();

            //do preedit if checked
            var sendTextOnly = _options.SendPlainTextOnly || !newseg.HasTags;

            if (!sendTextOnly)
            {
                //do preedit with tagged segment
                if (_options.UsePreEdit)
                {
                    if (_preLookupSegmentEditor == null)
                    {
                        _preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    }
                    newseg = GetEditedSegment(_preLookupSegmentEditor, newseg);
                }
                //return our tagged target segment
                var tagplacer = new MtTranslationProviderTagPlacer(newseg);
                ////tagplacer is constructed and gives us back a properly marked up source string for google
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGt(tagplacer.PreparedSourceText, _options, "html");
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMst(tagplacer.PreparedSourceText, _options, "text/html");
                }
                //now we send the output back to tagplacer for our properly tagged segment
                translation = tagplacer.GetTaggedSegment(translatedText).Duplicate();

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (_postLookupSegmentEditor == null)
                    {
                        _postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    }
                    translation = GetEditedSegment(_postLookupSegmentEditor, translation);
                }
            }
            else             //only send plain text
            {
                var sourcetext = newseg.ToPlain();
                //do preedit with string
                if (_options.UsePreEdit)
                {
                    if (_preLookupSegmentEditor == null)
                    {
                        _preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    }
                    sourcetext = GetEditedString(_preLookupSegmentEditor, sourcetext);
                    //change our source segment so it gets sent back with modified text to show in translation results window that it was changed before sending
                    newseg.Clear();
                    newseg.Add(sourcetext);
                }

                switch (_options.SelectedProvider)
                {
                //now do lookup
                case MtTranslationOptions.ProviderType.GoogleTranslate:
                    translatedText = LookupGt(sourcetext, _options, "html");                             //plain??
                    break;

                case MtTranslationOptions.ProviderType.MicrosoftTranslator:
                    translatedText = LookupMst(sourcetext, _options, "text/plain");
                    break;
                }
                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (_postLookupSegmentEditor == null)
                    {
                        _postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    }
                    translatedText = GetEditedString(_postLookupSegmentEditor, translatedText);
                }
                translation.Add(translatedText);
            }

            results.Add(CreateSearchResult(newseg, translation));

            return(results);
        }
 public void ClearPackages()
 => SearchResults.Clear();
示例#44
0
        public async Task UpdateTestResultsForSpecification_GivenResultsReturnedButIndexeingCausesErrors_LogsErrors()
        {
            //Arrange
            const string specificationId = "spec-id";

            SpecificationVersionComparisonModel specificationVersionComparison = new SpecificationVersionComparisonModel()
            {
                Id      = specificationId,
                Current = new SpecificationVersion {
                    Name = "new name"
                },
                Previous = new SpecificationVersion {
                    Name = "any name"
                }
            };

            string json = JsonConvert.SerializeObject(specificationVersionComparison);

            Message message = new Message(Encoding.UTF8.GetBytes(json));

            ILogger logger = CreateLogger();

            SearchResults <TestScenarioResultIndex> searchResult = new SearchResults <TestScenarioResultIndex>
            {
                Results = new List <CalculateFunding.Repositories.Common.Search.SearchResult <TestScenarioResultIndex> >
                {
                    new CalculateFunding.Repositories.Common.Search.SearchResult <TestScenarioResultIndex>
                    {
                        Result = new TestScenarioResultIndex()
                    },
                    new CalculateFunding.Repositories.Common.Search.SearchResult <TestScenarioResultIndex>
                    {
                        Result = new TestScenarioResultIndex()
                    },
                    new CalculateFunding.Repositories.Common.Search.SearchResult <TestScenarioResultIndex>
                    {
                        Result = new TestScenarioResultIndex()
                    }
                }
            };

            IEnumerable <IndexError> indexErrors = new[]
            {
                new IndexError {
                    ErrorMessage = "an error"
                }
            };

            ISearchRepository <TestScenarioResultIndex> searchRepository = CreateSearchRespository();

            searchRepository
            .Search(Arg.Is(""), Arg.Any <SearchParameters>())
            .Returns(searchResult);

            searchRepository
            .Index(Arg.Any <IEnumerable <TestScenarioResultIndex> >())
            .Returns(indexErrors);

            TestResultsService service = CreateTestResultsService(logger: logger, searchRepository: searchRepository);

            //Act
            await service.Process(message);

            //Assert
            await
            searchRepository
            .Received(1)
            .Search(Arg.Is(""), Arg.Is <SearchParameters>(
                        m => m.Skip == 0 &&
                        m.Top == 1000 &&
                        m.SearchMode == SearchMode.Any &&
                        m.Filter == $"specificationId eq '{specificationVersionComparison.Id}' and specificationName ne '{specificationVersionComparison.Current.Name}'"
                        ));

            await
            searchRepository
            .Received(1)
            .Index(Arg.Is <IEnumerable <TestScenarioResultIndex> >(m => m.Count() == 3));

            logger
            .Received(1)
            .Error($"The following errors occcurred while updating test results for specification id: {specificationId}, an error");
        }
示例#45
0
        /// <summary>
        /// Performs the actual search
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="segment"></param>
        /// <returns></returns>
        #region "SearchSegment"
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            // Loop through segment elements to 'filter out' e.g. tags in order to
            // make certain that only plain text information is retrieved for
            // this simplified implementation.

            // TODO: Make it work with tags. Probably alignment information
            // is needed from the server for this
            #region "SegmentElements"
            _visitor.Reset();
            foreach (var element in segment.Elements)
            {
                element.AcceptSegmentElementVisitor(_visitor);
            }
            #endregion

            #region "SearchResultsObject"
            SearchResults results = new SearchResults();
            results.SourceSegment = segment.Duplicate();

            #endregion
            string sourceText = _visitor.PlainText;

            // If replacements need to be done to the source segment, here is the place
            // sourceText = sourceText.Replace("foo", "bar");

            //Get the translation from the server
            string translatedSentence = searchInServer(sourceText);

            if (String.IsNullOrEmpty(translatedSentence))
            {
                return(results);
            }

            // Here restore any replacements made above. The replacements may be needed
            // for invalid, corrupted, or other characters that could break the OpenNMT engine
            // translatedSentence = translatedSentence.Replace("bar", "foo");

            // Look up the currently selected segment in the collection (normal segment lookup).
            if (settings.Mode == SearchMode.FullSearch)
            {
                Segment translation = new Segment(_languageDirection.TargetCulture);
                translation.Add(translatedSentence);

                results.Add(CreateSearchResult(segment, translation, _visitor.PlainText, segment.HasTags));
            }
            #region "SegmentLookup"
            if (settings.Mode == SearchMode.NormalSearch)
            {
                Segment translation = new Segment(_languageDirection.TargetCulture);
                translation.Add(translatedSentence);

                results.Add(CreateSearchResult(segment, translation, _visitor.PlainText, segment.HasTags));
            }
            #endregion

            #region "Close"
            return(results);

            #endregion
        }
示例#46
0
        private async Task <SearchResults> SearchCore(SearchFilter filter, bool raw)
        {
            // Query!
            var sw = new Stopwatch();

            sw.Start();
            var result = await _client.Search(
                filter.SearchTerm,
                projectTypeFilter : null,
                includePrerelease : filter.IncludePrerelease,
                curatedFeed : filter.CuratedFeed?.Name,
                sortBy : filter.SortOrder,
                skip : filter.Skip,
                take : filter.Take,
                isLuceneQuery : raw,
                countOnly : filter.CountOnly,
                explain : false,
                getAllVersions : filter.IncludeAllVersions,
                supportedFramework : filter.SupportedFramework);

            sw.Stop();

            SearchResults results = null;

            if (result.IsSuccessStatusCode)
            {
                var content = await result.ReadContent();

                if (filter.CountOnly || content.TotalHits == 0)
                {
                    results = new SearchResults(content.TotalHits, content.IndexTimestamp);
                }
                else
                {
                    results = new SearchResults(
                        content.TotalHits,
                        content.IndexTimestamp,
                        content.Data.Select(ReadPackage).AsQueryable());
                }
            }
            else
            {
                if (result.HttpResponse.Content != null)
                {
                    result.HttpResponse.Content.Dispose();
                }

                results = new SearchResults(0, null, Enumerable.Empty <Package>().AsQueryable());
            }

            Trace.PerfEvent(
                SearchRoundtripTimePerfCounter,
                sw.Elapsed,
                new Dictionary <string, object>()
            {
                { "Term", filter.SearchTerm },
                { "Context", filter.Context },
                { "Raw", raw },
                { "Hits", results == null ? -1 : results.Hits },
                { "StatusCode", (int)result.StatusCode },
                { "SortOrder", filter.SortOrder.ToString() },
                { "CuratedFeed", filter.CuratedFeed?.Name },
                { "Url", TryGetUrl() }
            });

            return(results);
        }
示例#47
0
        /**
         * Entry point
         */
        private static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                return;
            }

            RuntimeInfo.Setup();

            CliParse.ReadArguments(args);

            var img = RuntimeInfo.Config.Image;

            bool run = img != null;

            if (run)
            {
                var sr      = new SearchResults();
                var ok      = Search.RunSearch(img, ref sr);
                var results = sr.Results;

                // Console.WriteLine("Elapsed: {0:F} sec", result.Duration.TotalSeconds);

                ConsoleKeyInfo cki;

                do
                {
                    Console.Clear();

                    for (int i = 0; i < sr.Results.Length; i++)
                    {
                        var r = sr.Results[i];

                        var tag = (i + 1).ToString();
                        if (r != null)
                        {
                            string str = r.Format(tag);

                            Console.Write(str);
                        }
                        else
                        {
                            Console.WriteLine("{0} - ...", tag);
                        }
                    }

                    Console.WriteLine();

                    // Exit
                    if (RuntimeInfo.Config.AutoExit)
                    {
                        SearchConfig.Cleanup();
                        return;
                    }

                    CliOutput.WriteSuccess("Enter the result number to open or escape to quit.");


                    while (!Console.KeyAvailable)
                    {
                        // Block until input is entered.
                    }


                    // Key was read

                    cki = Console.ReadKey(true);
                    char keyChar = cki.KeyChar;

                    if (Char.IsNumber(keyChar))
                    {
                        int idx = (int)Char.GetNumericValue(cki.KeyChar) - 1;

                        if (idx < results.Length && idx >= 0)
                        {
                            var res = results[idx];
                            WebAgent.OpenUrl(res.Url);
                        }
                    }
                } while (cki.Key != ConsoleKey.Escape);

                // Exit
                SearchConfig.Cleanup();
            }
            else
            {
                //CliOutput.WriteInfo("Exited");
            }
        }
示例#48
0
        //TODO: The last param, Cache isn't used.  Remove it and update dependant projects.  (Version 1.3)
        public static SearchResults <Document> GetDocuments(QueryParser defaultQueryParser, QueryParser customQueryParser, IndexSearcher indexSearcher, string query, int pageNumber, int pageSize, bool shouldDocumentsBeClustered, string sort, int maximumNumberOfDocumentsToScore, Cache cache)
        {
            Query query2 = customQueryParser.Parse(query);

            Hits hits = null;

            if (!string.IsNullOrEmpty(sort))
            {
                string[] sorts = sort.ToLower().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                List <SortField> sortFields = new List <SortField>(sorts.Length / 2);

                for (int i = 0; i < sorts.Length; i++)
                {
                    if (sorts[i].Split(' ')[1] == "asc")
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], false));
                    }
                    else
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], true));
                    }
                }

                hits = indexSearcher.Search(query2, new Sort(sortFields.ToArray()));
            }
            else
            {
                hits = indexSearcher.Search(query2);
            }

            SearchResults <Document> searchResults = new SearchResults <Document>();

            searchResults.Documents = new List <Document>();
            searchResults.Query     = query2;

            if (hits.Length() != 0)
            {
                Dictionary <string, string> domains = new Dictionary <string, string>();

                PriorityQueue <Document> priorityQueue = new PriorityQueue <Document>();

                //Get the Hits!!!
                //TODO: Optimize this!!! (Version 1.3)
                for (int j = 0; j < hits.Length() && searchResults.Documents.Count < maximumNumberOfDocumentsToScore && priorityQueue.Count < maximumNumberOfDocumentsToScore; j++)
                {
                    Document document = hits.Doc(j);

                    float score = hits.Score(j);

                    document.Add(new Field("documentid", j.ToString(), Field.Store.YES, Field.Index.NO));
                    document.Add(new Field("relevancyscore", score.ToString(), Field.Store.YES, Field.Index.NO));

                    if (!string.IsNullOrEmpty(sort))
                    {
                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                    else
                    {
                        priorityQueue.Enqueue(document, score * double.Parse(document.GetField("strength").StringValue()));
                    }
                }

                if (string.IsNullOrEmpty(sort))
                {
                    for (int i = 0; i < hits.Length() && priorityQueue.Count != 0; i++)
                    {
                        Document document = priorityQueue.Dequeue();

                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                                else
                                {
                                    i--;
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                }

                if (shouldDocumentsBeClustered)
                {
                    searchResults.TotalNumberOfHits = domains.Count;
                }
                else
                {
                    searchResults.TotalNumberOfHits = hits.Length();
                }
            }

            return(searchResults);
        }
示例#49
0
        //TODO: Delete, F.Query is obsolete.
        /*
        public SearchResults Search(F.Query query)
        {
            SearchResults results = new SearchResults();

            var criteria = parseCriteria(query, results);

            if (!results.HasErrors)
            {
                results.UsedCriteria = criteria;
                //TODO: ResourceType.ToString() sufficient, or need to use EnumMapping?
                var normalizedCriteria = NormalizeNonChainedReferenceCriteria(criteria, query.ResourceType.ToString());
                List<BsonValue> keys = CollectKeys(query.ResourceType.ToString(), normalizedCriteria, results);

                int numMatches = keys.Count();

                results.AddRange(KeysToSearchResults(keys));
                results.MatchCount = numMatches;
            }

            return results;
        }
        */
        private List<Criterium> parseCriteria(SearchParams searchCommand, SearchResults results)
        {
            var result = new List<Criterium>();
            foreach (var c in searchCommand.Parameters)
            {
                try
                {
                    result.Add(Criterium.Parse(c.Item1, c.Item2));
                }
                catch (Exception ex)
                {
                    results.AddIssue(String.Format("Could not parse parameter [{0}] for reason [{1}].", c.ToString(), ex.Message));
                }
            }
            return result;
        }
示例#50
0
        private void AddSchemaUrl(SearchResults result, NamedId <DomainId> appId, NamedId <DomainId> schemaId, string name)
        {
            var schemaUrl = urlGenerator.SchemaUI(appId, schemaId);

            result.Add(T.Get("search.schemaResult", new { name }), SearchResultType.Schema, schemaUrl);
        }
        public SearchResults SearchSegment(SearchSettings settings, Segment segment)
        {
            //FUTURE: consider making GT and MT lookup classes static utility classes

            Segment translation = new Segment(_languageDirection.TargetCulture);//this will be the target segment

            #region "SearchResultsObject"
            SearchResults results = new SearchResults();
            results.SourceSegment = segment.Duplicate();

            #endregion

            #region "Confirmation Level"
            if (!_options.ResendDrafts && inputTu.ConfirmationLevel != ConfirmationLevel.Unspecified) //i.e. if it's status is other than untranslated
            { //don't do the lookup, b/c we don't need to pay google to translate text already translated if we edit a segment
                translation.Add(PluginResources.TranslationLookupDraftNotResentMessage);
                //later get these strings from resource file
                results.Add(CreateSearchResult(segment, translation, segment.ToString()));
                return results;
            }
            #endregion

            // Look up the currently selected segment in the collection (normal segment lookup).
            #region "SegmentLookup"
            string sourceLang = SourceLanguage.ToString();
            string targetLang = TargetLanguage.ToString();
            string translatedText = "";
            //a new seg avoids modifying the current segment object
            Segment newseg = segment.Duplicate();

            //do preedit if checked
            bool sendTextOnly = _options.SendPlainTextOnly || !newseg.HasTags;
            if (!sendTextOnly)
            {
                //do preedit with tagged segment
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null) preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    newseg = getEditedSegment(preLookupSegmentEditor, newseg);
                }
                //return our tagged target segment
                MtTranslationProviderTagPlacer tagplacer = new MtTranslationProviderTagPlacer(newseg);
                ////tagplacer is constructed and gives us back a properly marked up source string for google
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(tagplacer.PreparedSourceText, _options, "html");
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(tagplacer.PreparedSourceText, _options, "text/html");
                }
                //now we send the output back to tagplacer for our properly tagged segment
                translation = tagplacer.GetTaggedSegment(translatedText).Duplicate();

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null) postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    translation = getEditedSegment(postLookupSegmentEditor, translation);
                }
            }
            else //only send plain text
            {
                string sourcetext = newseg.ToPlain();
                //do preedit with string
                if (_options.UsePreEdit)
                {
                    if (preLookupSegmentEditor == null) preLookupSegmentEditor = new SegmentEditor(_options.PreLookupFilename);
                    sourcetext = getEditedString(preLookupSegmentEditor, sourcetext);
                    //change our source segment so it gets sent back with modified text to show in translation results window that it was changed before sending
                    newseg.Clear();
                    newseg.Add(sourcetext);
                }

                //now do lookup
                if (_options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    translatedText = LookupGT(sourcetext, _options, "html"); //plain??
                }
                else if (_options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    translatedText = LookupMST(sourcetext, _options, "text/plain");
                }

                //now do post-edit if that option is checked
                if (_options.UsePostEdit)
                {
                    if (postLookupSegmentEditor == null) postLookupSegmentEditor = new SegmentEditor(_options.PostLookupFilename);
                    translatedText = getEditedString(postLookupSegmentEditor, translatedText);
                }
                translation.Add(translatedText);
            }

            results.Add(CreateSearchResult(newseg, translation, newseg.ToPlain()));

            #endregion

            #region "Close"
            return results;
            #endregion
        }
 void ISearchForAllDocumentsAndCreateAHierarchicalFacet()
 {
     result = client.Search<Document>()
                 .HierarchicalFacetFor(x => x.Hierarchy)
                 .GetResult();
 }
        public SearchResults[] SearchSegmentsMasked(SearchSettings settings, Segment[] segments, bool[] mask)
        {
            if (segments == null)
            {
                throw new ArgumentNullException("segments in SearchSegmentsMasked");
            }
            if (mask == null || mask.Length != segments.Length)
            {
                throw new ArgumentException("mask in SearchSegmentsMasked");
            }

            SearchResults[] results = new SearchResults[segments.Length];
            for (int p = 0; p < segments.Length; ++p)
            {
                if (mask[p])
                {
                    results[p] = SearchSegment(settings, segments[p]);
                }
                else
                {
                    results[p] = null;
                }
            }

            return results;
        }
示例#54
0
        public ObservableCollection <SearchResults> GetSearchResults(string connectionString)
        {
            string GetLevelsQuery = "SELECT DISTINCT * FROM Schedule JOIN labs ON labs.LabName = Schedule.LabName JOIN lecturer ON lecturer.LecturerID = Schedule.LecturerID JOIN modules ON modules.ModuleCode = Schedule.ModuleCode WHERE (Schedule.LecturerID=(SELECT LecturerID FROM lecturer WHERE LecName LIKE'%" + searchBox.Text + "%') Or Schedule.LabName LIKE '%" + searchBox.Text + "%' Or Schedule.ModuleCode LIKE '%" + searchBox.Text + "%' Or Schedule.ModuleCode=(SELECT ModuleCode FROM modules WHERE ModuleName LIKE '%" + searchBox.Text + "%')) AND Schedule.UseDate = CONVERT(date, GETDATE())";

            var results = new ObservableCollection <SearchResults>();

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = GetLevelsQuery;

                            using (SqlDataReader dr = cmd.ExecuteReader())
                            {
                                while (dr.Read())
                                {
                                    var result = new SearchResults();
                                    result.EndTime      = dr.GetTimeSpan(7);
                                    result.IntakeCode   = dr.GetString(4);
                                    result.LabLocation  = dr.GetString(9);
                                    result.LabName      = dr.GetString(1);
                                    result.UseDate      = dr.GetDateTime(5);
                                    result.LecturerName = dr.GetString(13);
                                    result.ModuleCode   = dr.GetString(2);
                                    result.ModuleName   = dr.GetString(15);
                                    result.StartTime    = dr.GetTimeSpan(6);
                                    results.Add(result);
                                }
                            }
                        }
                    }
                }
                return(results);
            }
            catch (SqlException exSql)
            {
                if (Debugger.IsAttached)
                {
                    Helpers.ShowMsgComplete(exSql.Message + exSql.StackTrace, "SqlException");
                }
                else
                {
                    Helpers.ShowMsgComplete("The search query is too short or there is something wrong when connecting to the database. Please try again with another search query. If the problem persists, please contact TA.", "Unable to search");
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Helpers.ShowMsgComplete(ex.Message + ex.StackTrace, ex.ToString());
                }
                else
                {
                    Helpers.ShowMsgComplete("Please try again with another search query. If the problem persists, please contact TA.", "Unable to search");
                }
            }
            return(null);
        }
        /// <summary>
        ///     Searches the datasource using the specified criteria. Criteria is parsed by the query builder specified by
        ///     <typeparamref />
        ///     .
        /// </summary>
        /// <param name="scope">Name of the application.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        /// <exception cref="VirtoCommerce.SearchModule.Data.Providers.Lucene.LuceneSearchException"></exception>
        public virtual ISearchResults Search(string scope, ISearchCriteria criteria)
        {
            ISearchResults result;

            var directoryInfo = new DirectoryInfo(GetDirectoryPath(GetFolderName(scope, criteria.DocumentType)));

            if (directoryInfo.Exists)
            {
                var dir = FSDirectory.Open(directoryInfo);
                var searcher = new IndexSearcher(dir);

                var q = (QueryBuilder)QueryBuilder.BuildQuery(criteria);

                // filter out empty value
                var filter = q.Filter.ToString().Equals("BooleanFilter()") ? null : q.Filter;

                Debug.WriteLine("Search Lucene Query:{0}", q.ToString());

                TopDocs docs;

                try
                {
                    var numDocs = criteria.StartingRecord + criteria.RecordsToRetrieve;

                    if (criteria.Sort != null)
                    {
                        var fields = criteria.Sort.GetSort();

                        docs = searcher.Search(
                            q.Query,
                            filter,
                            numDocs,
                            new Sort(
                                fields.Select(field => new SortField(field.FieldName, field.DataType, field.IsDescending))
                                    .ToArray()));
                    }
                    else
                    {
                        docs = searcher.Search(q.Query, filter, numDocs);
                    }
                }
                catch (Exception ex)
                {
                    throw new LuceneSearchException("Search exception", ex);
                }

                var results = new LuceneSearchResults(searcher, searcher.IndexReader, docs, criteria, q.Query);

                // Cleanup here
                searcher.IndexReader.Dispose();
                searcher.Dispose();
                result = results.Results;
            }
            else
            {
                result = new SearchResults(criteria, null);
            }

            return result;
        }
示例#56
0
        public override IDataItems GetAll(DataSourceContext context, Select selectQuery)
        {
            ReIndexIfNeeded(context.ModuleId, context.TabId, context.PortalId);
            if (context.Index && selectQuery != null)
            {
                SearchResults docs = LuceneUtils.Search(INDEX_SCOPE, selectQuery);
                if (LogContext.IsLogActive)
                {
                    var logKey = "Lucene query";
                    LogContext.Log(context.ActiveModuleId, logKey, "Filter", docs.ResultDefinition.Filter);
                    LogContext.Log(context.ActiveModuleId, logKey, "Query", docs.ResultDefinition.Query);
                    LogContext.Log(context.ActiveModuleId, logKey, "Sort", docs.ResultDefinition.Sort);
                    LogContext.Log(context.ActiveModuleId, logKey, "PageIndex", docs.ResultDefinition.PageIndex);
                    LogContext.Log(context.ActiveModuleId, logKey, "PageSize", docs.ResultDefinition.PageSize);
                }
                int total    = docs.TotalResults;
                var dataList = new List <IDataItem>();
                foreach (string item in docs.ids)
                {
                    var user = UserController.GetUserById(context.PortalId, int.Parse(item));
                    if (user != null)
                    {
                        dataList.Add(ToData(user));
                    }
                    else
                    {
                        App.Services.Logger.Debug($"DnnUsersDataSource.GetAll() ContentItem not found [{item}]");
                    }
                }
                return(new DefaultDataItems()
                {
                    Items = dataList,
                    Total = total,
                    DebugInfo = docs.ResultDefinition.Filter + " - " + docs.ResultDefinition.Query + " - " + docs.ResultDefinition.Sort
                });
            }
            else
            {
                int pageIndex = 0;
                int pageSize  = 100000;
                int total     = 0;
                IEnumerable <UserInfo> users;
                if (selectQuery != null)
                {
                    var ruleDisplayName = selectQuery.Query.FilterRules.FirstOrDefault(f => f.Field == "DisplayName");
                    var ruleRoles       = selectQuery.Query.FilterRules.FirstOrDefault(f => f.Field == "Roles");
                    var ruleApproved    = selectQuery.Query.FilterRules.FirstOrDefault(f => f.Field == "Approved");

                    if (ruleDisplayName != null)
                    {
                        string displayName = ruleDisplayName.Value.AsString + "%";
                        users = UserController.GetUsersByDisplayName(context.PortalId, displayName, pageIndex, pageSize, ref total, true, false).Cast <UserInfo>();
                    }
                    else
                    {
                        users = UserController.GetUsers(context.PortalId, pageIndex, pageSize, ref total, true, false).Cast <UserInfo>();
                    }
                    var userCount = users.Count();
                    if (ruleRoles != null)
                    {
                        var roleNames = ruleRoles.MultiValue.Select(r => r.AsString).ToList();
                        users = users.Where(u => u.Roles.Intersect(roleNames).Any());
                    }
                    if (ruleApproved != null)
                    {
                        var val = bool.Parse(ruleApproved.Value.AsString);
                        users = users.Where(u => u.Membership.Approved == val);
                    }
                    total     = users.Count();
                    pageIndex = selectQuery.PageIndex;
                    pageSize  = selectQuery.PageSize;
                    users     = users.Skip(pageIndex * pageSize).Take(pageSize);
                }
                else
                {
                    users = UserController.GetUsers(context.PortalId, pageIndex, pageSize, ref total, true, false).Cast <UserInfo>();
                }
                int excluded = users.Count(u => u.IsInRole("Administrators"));
                users = users.Where(u => !u.IsInRole("Administrators"));

                var dataList = new List <IDataItem>();
                foreach (var user in users)
                {
                    dataList.Add(ToData(user));
                }
                return(new DefaultDataItems()
                {
                    Items = dataList,
                    Total = total - excluded,
                    //DebugInfo =
                });
            }
        }
示例#57
0
 public void Restart()
 {
     StopSearch();
     SearchResults.Clear();
     StartSearch();
 }
示例#58
0
            public override void Process()
            {
                string query = context.Request.QueryString["q"];

                if (query == null)
                {
                    return;
                }

                // Look for special searches
                if (SpecialSearches.ContainsKey(query))
                {
                    string path = SpecialSearches[query];

                    if (context.Request.QueryString["jsonp"] != null)
                    {
                        // TODO: Does this include the JSONP headers?
                        SendFile(JsonConstants.MediaType, path);
                        return;
                    }

                    if (Accepts(context, JsonConstants.MediaType))
                    {
                        SendFile(JsonConstants.MediaType, path);
                        return;
                    }
                    return;
                }

                //
                // Do the search
                //
                ResourceManager resourceManager = new ResourceManager(context.Server);

                SectorMap.Milieu map = SectorMap.ForMilieu(resourceManager, GetStringOption("milieu"));

                query = query.Replace('*', '%'); // Support * and % as wildcards
                query = query.Replace('?', '_'); // Support ? and _ as wildcards

                if (UWP_REGEXP.IsMatch(query))
                {
                    query = "uwp:" + query;
                }

                const int NUM_RESULTS = 160;

                var searchResults = SearchEngine.PerformSearch(query, SearchEngine.SearchResultsType.Default, NUM_RESULTS);

                SearchResults resultsList = new SearchResults();

                if (searchResults != null)
                {
                    resultsList.AddRange(searchResults
                                         .Select(loc => SearchResults.LocationToSearchResult(map, resourceManager, loc))
                                         .OfType <SearchResults.Item>()
                                         .OrderByDescending(item => item.Importance)
                                         .Take(NUM_RESULTS));
                }

                SendResult(context, resultsList);
            }
        private async Task<SearchResults> SearchCore(SearchFilter filter, bool raw)
        {
            // Query!
            var sw = new Stopwatch();
            sw.Start();
            var result = await _client.Search(
                filter.SearchTerm,
                projectTypeFilter: null,
                includePrerelease: filter.IncludePrerelease,
                curatedFeed: filter.CuratedFeed == null ? null : filter.CuratedFeed.Name,
                sortBy: filter.SortOrder,
                skip: filter.Skip,
                take: filter.Take,
                isLuceneQuery: raw,
                countOnly: filter.CountOnly,
                explain: false,
                getAllVersions: filter.IncludeAllVersions,
                supportedFramework: filter.SupportedFramework);
            sw.Stop();

            SearchResults results = null;
            if (result.IsSuccessStatusCode)
            {
                var content = await result.ReadContent();
                if (filter.CountOnly || content.TotalHits == 0)
                {
                    results = new SearchResults(content.TotalHits, content.IndexTimestamp);
                }
                else
                {
                    results = new SearchResults(
                        content.TotalHits,
                        content.IndexTimestamp,
                        content.Data.Select(ReadPackage).AsQueryable());
                }
            }

            Trace.PerfEvent(
                SearchRoundtripTimePerfCounter,
                sw.Elapsed,
                new Dictionary<string, object>() {
                    {"Term", filter.SearchTerm},
                    {"Context", filter.Context},
                    {"Raw", raw},
                    {"Hits", results == null ? -1 : results.Hits},
                    {"StatusCode", (int)result.StatusCode},
                    {"SortOrder", filter.SortOrder.ToString()},
                    {"CuratedFeed", filter.CuratedFeed == null ? null : filter.CuratedFeed.Name},
                    {"Url", TryGetUrl()}
                });

            result.HttpResponse.EnsureSuccessStatusCode();
            return results;
        }
示例#60
0
 public void Clear()
 {
     SearchText = string.Empty;
     StopSearch();
     SearchResults.Clear();
 }