public IProcessText GetInstance(SearchOptions options) { IProcessText result = null; switch (options) { case (SearchOptions.QuickSearch): result = new QuickSearchProcess(); break; case (SearchOptions.Horspool): result = new HorspoolProcess(); break; case (SearchOptions.Sunday): result = new SundayProcess(); break; case (SearchOptions.Raita): result = new RaitaProcess(); break; case (SearchOptions.TunedBM): result = new TunedBMProcess(); break; case (SearchOptions.BNDM): case (SearchOptions.Wildcard): result = new BNDMProcess(); break; default: return null; } return result; }
private FindOptions CreateFindOptions(string pattern, SearchKind kind, SearchOptions options) { var searchData = new SearchData(pattern, SearchOffsetData.None, kind, options); var serviceSearchData = _searchRaw.GetServiceSearchData(searchData, _wordNavigator); var findData = SearchService.ConvertToFindDataCore(serviceSearchData, _textBuffer.CurrentSnapshot); Assert.True(findData.IsResult); return findData.AsResult().FindOptions; }
private void InitializeRunner(string pattern, SearchOptions options) { if (options == SearchOptions.Unknown) options = SelectTheBestOption(pattern); IPreProcess preProcess = new PreProcessFactory().GetInstance(options); IProcessText processText = new ProcessTextFactory().GetInstance(options); _searchRunner = new SearchDispatch(processText, preProcess, pattern); }
/// <summary> /// Searches Twitter with the the specified query. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="query">The query.</param> /// <param name="options">The options.</param> /// <returns> /// A <see cref="TwitterSearchResultCollection"/> instance. /// </returns> public static TwitterResponse<TwitterSearchResultCollection> Search(OAuthTokens tokens, string query, SearchOptions options) { if (options == null) options = new SearchOptions(); Commands.SearchCommand command = new Twitterizer.Commands.SearchCommand(tokens, query, options); TwitterResponse<TwitterSearchResultCollection> results = Core.CommandPerformer.PerformAction(command); return results; }
/// <summary> /// Initializes a new instance of the <see cref="T:SearchParameters" /> class. /// </summary> /// <param name="query">The search query.</param> /// <param name="documentTypeTags">The document type tags to include in the search, or <c>null</c>.</param> /// <param name="options">The search options.</param> /// <exception cref="ArgumentNullException">If <paramref name="query"/> or one of the elements of <paramref name="documentTypeTags"/> (when the array is not <c>null</c>) are <c>null</c>.</exception> /// <exception cref="ArgumentException">If <paramref name="query"/> or one of the elements of <paramref name="documentTypeTags"/> (when the array is not <c>null</c>) are empty.</exception> public SearchParameters(string query, string[] documentTypeTags, SearchOptions options) { if(query == null) throw new ArgumentNullException("query"); if(query.Length == 0) throw new ArgumentException("Query cannot be empty", "query"); if(documentTypeTags != null) { if(documentTypeTags.Length == 0) throw new ArgumentException("DocumentTypeTags cannot be empty", "documentTypeTags"); foreach(string dtt in documentTypeTags) { if(dtt == null) throw new ArgumentNullException("documentTypeTags"); if(dtt.Length == 0) throw new ArgumentException("DocumentTypeTag cannot be empty", "documentTypeTag"); } } this.query = PrepareQuery(query); this.documentTypeTags = documentTypeTags; this.options = options; }
public static SearchValidationResults Validate(SearchOptions options) { bool valid = true; List<SearchValidationErrors> errors = new List<SearchValidationErrors>(); foreach (KeyValuePair<SearchFields, List<Condition>> pair in options.Conditions) { foreach (Condition cond in pair.Value) { ValidationErrors error = TestFieldValue(pair.Key, cond); if (error != ValidationErrors.NoErrors) { errors.Add(new SearchValidationErrors(cond, error)); valid = false; } } } return new SearchValidationResults(valid, errors); }
public ISearchResult FindNext(SearchOptions options) { // insanity check Debug.Assert(searchStrategy != null); Debug.Assert(documentIterator != null); Debug.Assert(textIteratorBuilder != null); Debug.Assert(options != null); if (info != null && textIterator != null && documentIterator.CurrentFileName != null) { if (info.FileName != documentIterator.CurrentFileName) { // create new iterator, if document changed info = documentIterator.Current; textIterator = textIteratorBuilder.BuildTextIterator(info); } else { // old document -> initialize iterator position to caret pos textIterator.Position = info.CurrentOffset; } ISearchResult result = CreateNamedSearchResult(searchStrategy.FindNext(textIterator, options)); if (result != null) { info.CurrentOffset = textIterator.Position; return result; } } // not found or first start -> move forward to the next document if (documentIterator.MoveForward()) { info = documentIterator.Current; // document is valid for searching -> set iterator & fileName if (info != null && info.TextBuffer != null && info.EndOffset >= 0 && info.EndOffset < info.TextBuffer.Length) { textIterator = textIteratorBuilder.BuildTextIterator(info); } else { textIterator = null; } return FindNext(options); } return null; }
/// <summary> /// Build an 'EndsWith' expression for a collection of properties against a particular string property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, Expression <Func <T, string> >[] propertiesToSearchFor, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var propertyToSearchFor in propertiesToSearchFor) { var endsWithExpression = Build(stringProperty, propertyToSearchFor, searchOptions); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, endsWithExpression); } return(completeExpression); }
private FindOptions CreateFindOptions(string pattern, SearchKind kind, SearchOptions options) { var searchData = new SearchData(pattern, kind, options); var findData = _searchRaw.ConvertToFindData(searchData, _textBuffer.CurrentSnapshot, _wordNavigator); Assert.True(findData.IsSome()); return findData.Value.FindOptions; }
private SearchResult CreateResult(SearchResult primaryResult, SearchResult secondaryResult, SearchOptions options) { if (primaryResult == null) { throw new ArgumentNullException(nameof(primaryResult)); } if (secondaryResult == null) { throw new ArgumentNullException(nameof(secondaryResult)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var result = new SearchResult() { ResultType = TrieNodeSearchResultType.Unkown }; var items = new List <string>(options.MaxItemCount * 2); if (primaryResult.ResultType == secondaryResult.ResultType) { if (primaryResult.Items != null) { items.AddRange(primaryResult.Items); } if (secondaryResult.Items != null) { items.AddRange(secondaryResult.Items); } items.Sort(); result.ResultType = primaryResult.ResultType; } else if (primaryResult.ResultType == TrieNodeSearchResultType.FoundEquals) { if (primaryResult.Items != null) { items.AddRange(primaryResult.Items); } result.ResultType = TrieNodeSearchResultType.FoundEquals; } else if (secondaryResult.ResultType == TrieNodeSearchResultType.FoundEquals) { if (secondaryResult.Items != null) { items.AddRange(secondaryResult.Items); } result.ResultType = TrieNodeSearchResultType.FoundEquals; } else if (primaryResult.ResultType == TrieNodeSearchResultType.FoundStartsWith) { if (primaryResult.Items != null) { items.AddRange(primaryResult.Items); } result.ResultType = TrieNodeSearchResultType.FoundStartsWith; } else if (secondaryResult.ResultType == TrieNodeSearchResultType.FoundStartsWith) { if (secondaryResult.Items != null) { items.AddRange(secondaryResult.Items); } result.ResultType = TrieNodeSearchResultType.FoundStartsWith; } if (items.Count > 0) { result.Items = items.Take(options.MaxItemCount).ToArray(); } return(result); }
/// <summary> /// Searches files and folders in current folder using search phrase and options. /// </summary> /// <param name="searchString">A phrase to search.</param> /// <param name="options">Search options.</param> /// <param name="propNames"> /// List of properties to retrieve with each item returned by this method. They will be requested by the /// Engine in <see cref="IHierarchyItemAsync.GetPropertiesAsync(IList{PropertyName}, bool)"/> call. /// </param> /// <returns>List of <see cref="IHierarchyItemAsync"/> satisfying search request.</returns> public async Task <IEnumerable <IHierarchyItemAsync> > SearchAsync(string searchString, SearchOptions options, List <PropertyName> propNames) { // Not implemented currently. .NET Core on Mac OS X does not provide a OLEDB driver at this time. // To generate a Windows-specific search code use the 'ASP.NET WebDAV Server Application' wizard for Visual Studio. return(new List <IHierarchyItemAsync>()); }
/// <summary> Finds a player by name, using autocompletion. /// Returns ALL matching players, including hidden ones. </summary> /// <param name="namePart"> Full or partial player name. </param> /// <param name="options"> Search options (recognizes SuppressEvent). </param> /// <returns> An array of matches. List length of 0 means "no matches"; /// 1 is an exact match; over 1 for multiple matches. </returns> /// <exception cref="ArgumentNullException"></exception> public static Player[] FindPlayers( [NotNull] string namePart, SearchOptions options) { if( namePart == null ) throw new ArgumentNullException( "namePart" ); bool suppressEvent = (options & SearchOptions.SuppressEvent) != 0; Player[] tempList = Players; List<Player> results = new List<Player>(); for( int i = 0; i < tempList.Length; i++ ) { if( tempList[i] == null ) continue; if( tempList[i].Name.Equals( namePart, StringComparison.OrdinalIgnoreCase ) ) { results.Clear(); results.Add( tempList[i] ); break; } else if( tempList[i].Name.StartsWith( namePart, StringComparison.OrdinalIgnoreCase ) ) { results.Add( tempList[i] ); } } if( !suppressEvent ) { var h = SearchingForPlayer; if( h != null ) { var e = new SearchingForPlayerEventArgs( null, namePart, results, options ); h( null, e ); } } return results.ToArray(); }
internal bool Match(SearchOptions search) { if (search == null) return false; Debug.Assert(!string.IsNullOrEmpty(Path), "This Metadata object does not have a path"); Debug.Assert(search.SearchType == SearchType.Metadata, "The search parameters are not appropriate for metadata"); if (string.IsNullOrEmpty(search.XmlElement)) { //to search the whole document, we don't need to parse it as XML string content = LoadAsText(); return content != null && Match(content, search.SearchWords, search.FindAll, search.ComparisonMethod); } XDocument xDoc = LoadAsXDoc(); if (xDoc == null) return false; return xDoc.Descendants(search.XmlElement) .Select(element => element.Value) .Where(value => !string.IsNullOrEmpty(value)) .Any(value => Match(value, search.SearchWords, search.FindAll, search.ComparisonMethod)); }
/// <summary> /// Build an 'equals' expression for one string property against another string property /// </summary> private static Expression Build <TSource, TType>(Expression <Func <TSource, TType> > propertyToSearch, IEnumerable <Expression <Func <TSource, TType> > > propertiesToSearchFor, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var propertyToSearchFor in propertiesToSearchFor) { var isEqualExpression = Expression.Call(propertyToSearch.Body, ExpressionMethods.EqualsMethod, propertyToSearchFor.Body, searchOptions.ComparisonTypeExpression); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, isEqualExpression); } return(completeExpression); }
/// <summary> /// Asynchronously searches the subset of UIDs in the folder for messages matching the specified query, /// returning them in the preferred sort order. /// </summary> /// <remarks> /// Asynchronously searches the folder for messages matching the specified query and ordering, /// returning only the requested search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="uids">The subset of UIDs</param> /// <param name="query">The search query.</param> /// <param name="orderBy">The sort order.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uids"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="query"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the <paramref name="uids"/> is invalid.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is empty.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The server does not support the ESORT extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The folder is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public virtual Task<SearchResults> SearchAsync (SearchOptions options, IList<UniqueId> uids, SearchQuery query, IList<OrderBy> orderBy, CancellationToken cancellationToken = default (CancellationToken)) { if (uids == null) throw new ArgumentNullException ("uids"); if (query == null) throw new ArgumentNullException ("query"); if (orderBy == null) throw new ArgumentNullException ("orderBy"); if (orderBy.Count == 0) throw new ArgumentException ("No sort order provided.", "orderBy"); return Task.Factory.StartNew (() => { lock (SyncRoot) { return Search (options, uids, query, orderBy, cancellationToken); } }, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); }
/// <summary> /// Build an 'equals' expression for a search term against a particular string property /// </summary> private static Expression Build <TSource, TType>(Expression <Func <TSource, TType> > property, IEnumerable <string> terms, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var term in terms) { var searchTermExpression = Expression.Constant(term); var equalsExpression = Expression.Call(property.Body, ExpressionMethods.EqualsMethod, searchTermExpression, searchOptions.ComparisonTypeExpression); completeExpression = completeExpression == null ? equalsExpression : ExpressionHelper.JoinOrExpression(completeExpression, equalsExpression); } return(completeExpression); }
/// <summary> /// Build an 'equals' expression for one string property against another string property /// </summary> public static Expression Build <TSource, TType>(Expression <Func <TSource, TType> >[] propertiesToSearch, Expression <Func <TSource, TType> >[] propertiesToSearchFor, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var propertyToSearch in propertiesToSearch) { var isEqualExpression = Build(propertyToSearch, propertiesToSearchFor, searchOptions); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, isEqualExpression); } return(completeExpression); }
private void SimulateSearch(string pattern, SearchKind searchKind = null, SearchOptions searchOptions = SearchOptions.None) { searchKind = searchKind ?? SearchKind.Forward; var data = new SearchData(pattern, SearchOffsetData.None, searchKind, searchOptions); _search.SetupGet(x => x.HasActiveSession).Returns(true).Verifiable(); _search.SetupGet(x => x.CurrentSearchData).Returns(data).Verifiable(); _search.SetupGet(x => x.CurrentSearchText).Returns(pattern).Verifiable(); }
/// <summary> /// Build an 'EndsWith([searchTerm])' expression comparing multiple string properties against string terms /// </summary> public static Expression Build <T>(Expression <Func <T, string> >[] stringProperties, string[] searchTerms, SearchOptions searchOptions) { Expression finalExpression = null; foreach (var stringProperty in stringProperties) { var endsWithExpression = Build(stringProperty, searchTerms, searchOptions); finalExpression = ExpressionHelper.JoinOrExpression(finalExpression, endsWithExpression); } return(finalExpression); }
/// <summary> /// Build an 'EndsWith' expression for a string property against a property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, Expression <Func <T, string> > propertyToSearchFor, SearchOptions searchOptions) { var endsWithExpresion = Expression.Call(stringProperty.Body, ExpressionMethods.EndsWithMethodWithComparison, propertyToSearchFor.Body, searchOptions.ComparisonTypeExpression); Expression finalExpression = null; if (searchOptions.NullCheck) { var notNullProperty = ExpressionHelper.BuildNotNullExpression(stringProperty); var notNullSearchFor = ExpressionHelper.BuildNotNullExpression(propertyToSearchFor); finalExpression = ExpressionHelper.JoinAndAlsoExpression(notNullProperty, notNullSearchFor); } finalExpression = ExpressionHelper.JoinAndAlsoExpression(finalExpression, endsWithExpresion); return(Expression.IsTrue(finalExpression)); }
public QueryUserVotesGiven(SearchOptions options) : this(options, new CachePolicy(TimeSpan.FromHours(12))) { }
public _ VerifyContentBlockIsLoaded() { Assert.That(ContentBlock.GetScope(SearchOptions.UnsafelyAtOnce()).Text, Is.EqualTo("Loaded")); return(this); }
/// <summary> /// Asynchronously search the folder for messages matching the specified query. /// </summary> /// <remarks> /// Asynchronously searches the folder for messages matching the specified query, /// returning only the specified search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="query">The search query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="query"/> is <c>null</c>. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The IMAP server does not support the ESEARCH extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The <see cref="MailFolder"/> is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public virtual Task<SearchResults> SearchAsync (SearchOptions options, SearchQuery query, CancellationToken cancellationToken = default (CancellationToken)) { if (query == null) throw new ArgumentNullException ("query"); return Task.Factory.StartNew (() => { lock (SyncRoot) { return Search (options, query, cancellationToken); } }, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); }
public QuerySubmissionsByDomain(string domain, SearchOptions options) : this(domain, options, new CachePolicy(TimeSpan.FromMinutes(60))) { this._options = options; this._domain = domain; }
/// <summary> /// Performs a search. /// </summary> /// <param name="query">The search query.</param> /// <param name="mode">The search mode.</param> /// <param name="selectedCategories">The selected categories.</param> /// <param name="searchUncategorized">A value indicating whether to search uncategorized pages.</param> /// <param name="searchInAllNamespacesAndCategories">A value indicating whether to search in all namespaces and categories.</param> /// <param name="searchFilesAndAttachments">A value indicating whether to search files and attachments.</param> private void PerformSearch(string query, SearchOptions mode, List <string> selectedCategories, bool searchUncategorized, bool searchInAllNamespacesAndCategories, bool searchFilesAndAttachments) { List <SearchResult> results = null; DateTime begin = DateTime.Now; try { List <SearchField> searchFields = new List <SearchField>(2) { SearchField.Title, SearchField.Content }; if (searchFilesAndAttachments) { searchFields.AddRange(new SearchField[] { SearchField.FileName, SearchField.FileContent }); } results = SearchClass.Search(searchFields.ToArray(), query, mode); } catch (ArgumentException ex) { Log.LogEntry("Search threw an exception\n" + ex.ToString(), EntryType.Warning, SessionFacade.CurrentUsername); results = new List <SearchResult>(); } DateTime end = DateTime.Now; // Build a list of SearchResultRow for display in the repeater List <SearchResultRow> rows = new List <SearchResultRow>(Math.Min(results.Count, MaxResults)); string currentUser = SessionFacade.GetCurrentUsername(); string[] currentGroups = SessionFacade.GetCurrentGroupNames(); CategoryInfo[] pageCategories; int count = 0; foreach (SearchResult res in results) { // Filter by category PageInfo currentPage = null; pageCategories = new CategoryInfo[0]; if (res.DocumentType == DocumentType.Page) { PageDocument doc = res.Document as PageDocument; currentPage = Pages.FindPage(doc.PageFullName); pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canReadPage = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadPage, currentUser, currentGroups); if (!canReadPage) { continue; // Skip } } else if (res.DocumentType == DocumentType.Message) { MessageDocument doc = res.Document as MessageDocument; currentPage = Pages.FindPage(doc.PageFullName); pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canReadDiscussion = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.ReadDiscussion, currentUser, currentGroups); if (!canReadDiscussion) { continue; // Skip } } else if (res.DocumentType == DocumentType.Attachment) { PageAttachmentDocument doc = res.Document as PageAttachmentDocument; currentPage = Pages.FindPage(doc.PageFullName); pageCategories = Pages.GetCategoriesForPage(currentPage); // Verify permissions bool canDownloadAttn = AuthChecker.CheckActionForPage(currentPage, Actions.ForPages.DownloadAttachments, currentUser, currentGroups); if (!canDownloadAttn) { continue; // Skip } } else if (res.DocumentType == DocumentType.File) { FileDocument doc = res.Document as FileDocument; string[] fields = doc.FileName.Split('|'); IFilesStorageProviderV30 provider = Collectors.FilesProviderCollector.GetProvider(fields[0]); string directory = Tools.GetDirectoryName(fields[1]); // Verify permissions bool canDownloadFiles = AuthChecker.CheckActionForDirectory(provider, directory, Actions.ForDirectories.DownloadFiles, currentUser, currentGroups); if (!canDownloadFiles) { continue; // Skip } } string currentNamespace = DetectNamespace(); if (string.IsNullOrEmpty(currentNamespace)) { currentNamespace = null; } if (currentPage != null) { // Check categories match, if page is set if (searchInAllNamespacesAndCategories || Array.Find(pageCategories, delegate(CategoryInfo c) { return(selectedCategories.Contains(c.FullName)); }) != null || pageCategories.Length == 0 && searchUncategorized) { // ... then namespace if (searchInAllNamespacesAndCategories || NameTools.GetNamespace(currentPage.FullName) == currentNamespace) { rows.Add(SearchResultRow.CreateInstance(res)); count++; } } } else { // No associated page (-> file), add result rows.Add(SearchResultRow.CreateInstance(res)); count++; } if (count >= MaxResults) { break; } } rptResults.DataSource = rows; rptResults.DataBind(); }
public QueryUserVotesGiven(SearchOptions options, CachePolicy policy) : base(policy) { this._options = options; }
/// <summary> Finds player by name without autocompletion. /// Returns null if no player with the given name is online. </summary> /// <param name="player"> Player from whose perspective search is performed. Used to determine whether others are hidden. </param> /// <param name="name"> Full player name. Case-insensitive. </param> /// <param name="options"> Search options (IncludeHidden and IncludeSelf are applicable, other flags are ignored). </param> /// <returns> Player object if player was found online; otherwise null. </returns> public static Player FindPlayerExact( [NotNull] Player player, [NotNull] string name, SearchOptions options ) { Player target = Players.FirstOrDefault( p => p.Name.Equals( name, StringComparison.OrdinalIgnoreCase ) ); bool includeHidden = (options & SearchOptions.IncludeHidden) != 0; bool includeSelf = (options & SearchOptions.IncludeSelf) != 0; if( target != null && !includeHidden && !player.CanSee( target ) || // hide players whom player cant see target == player && !includeSelf ) { // hide self, if applicable target = null; } return target; }
private bool MatchDescription(SearchOptions search) { return MatchText(search, Description); }
/// <summary> /// Searches the subset of UIDs in the folder for messages matching the specified query, /// returning them in the preferred sort order. /// </summary> /// <remarks> /// Searches the folder for messages matching the specified query and ordering, /// returning only the requested search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="uids">The subset of UIDs</param> /// <param name="query">The search query.</param> /// <param name="orderBy">The sort order.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uids"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="query"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the <paramref name="uids"/> is invalid.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is empty.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The IMAP server does not support the ESORT extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="ImapClient"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="ImapClient"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="ImapClient"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The <see cref="ImapFolder"/> is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ImapProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="ImapCommandException"> /// The server replied with a NO or BAD response. /// </exception> public override SearchResults Search (SearchOptions options, IList<UniqueId> uids, SearchQuery query, IList<OrderBy> orderBy, CancellationToken cancellationToken = default (CancellationToken)) { var set = ImapUtils.FormatUidSet (uids); var args = new List<string> (); string charset; if (query == null) throw new ArgumentNullException ("query"); if (orderBy == null) throw new ArgumentNullException ("orderBy"); if (orderBy.Count == 0) throw new ArgumentException ("No sort order provided.", "orderBy"); CheckState (true, false); if ((Engine.Capabilities & ImapCapabilities.ESort) == 0) throw new NotSupportedException ("The IMAP server does not support the ESORT extension."); if ((Engine.Capabilities & ImapCapabilities.SortDisplay) == 0) { for (int i = 0; i < orderBy.Count; i++) { if (orderBy[i].Type == OrderByType.DisplayFrom || orderBy[i].Type == OrderByType.DisplayTo) throw new NotSupportedException ("The IMAP server does not support the SORT=DISPLAY extension."); } } if (uids.Count == 0) return new SearchResults (); var optimized = query.Optimize (new ImapSearchQueryOptimizer ()); var expr = BuildQueryExpression (optimized, args, out charset); var order = BuildSortOrder (orderBy); var command = "UID SORT RETURN ("; if ((options & SearchOptions.Count) != 0) command += "COUNT "; if ((options & SearchOptions.Min) != 0) command += "MIN "; if ((options & SearchOptions.Max) != 0) command += "MAX "; command = command.TrimEnd (); command += ") "; command += order + " " + charset + " UID " + set + " " + expr + "\r\n"; var ic = new ImapCommand (Engine, cancellationToken, this, command, args.ToArray ()); ic.RegisterUntaggedHandler ("ESEARCH", ESearchMatches); ic.UserData = new SearchResults (); Engine.QueueCommand (ic); Engine.Wait (ic); ProcessResponseCodes (ic, null); if (ic.Response != ImapCommandResponse.Ok) throw ImapCommandException.Create ("SORT", ic); return (SearchResults) ic.UserData; }
private bool MatchTags(SearchOptions search) { return MatchText(search, Tags); }
/// <summary> /// Initializes the command. /// </summary> public override void Init() { #if !SILVERLIGHT CultureInfo unitedStatesEnglishCulture = CultureInfo.GetCultureInfo("en-us"); #else CultureInfo unitedStatesEnglishCulture = CultureInfo.InvariantCulture; #endif this.RequestParameters.Add("q", this.Query); SearchOptions options = this.OptionalProperties as SearchOptions; if (options == null) { return; } if (!string.IsNullOrEmpty(options.Language)) { this.RequestParameters.Add("lang", options.Language); } if (!string.IsNullOrEmpty(options.Locale)) { this.RequestParameters.Add("locale", options.Locale); } if (options.MaxId > 0) { this.RequestParameters.Add("max_id", options.MaxId.ToString(unitedStatesEnglishCulture)); } if (options.NumberPerPage > 0) { this.RequestParameters.Add("rpp", options.NumberPerPage.ToString(unitedStatesEnglishCulture)); } if (options.PageNumber > 0) { this.RequestParameters.Add("page", options.PageNumber.ToString(unitedStatesEnglishCulture)); } if (options.SinceDate > new DateTime()) { this.RequestParameters.Add("since", options.SinceDate.ToString("yyyy-MM-dd", unitedStatesEnglishCulture)); } if (options.SinceId > 0) { this.RequestParameters.Add("since_id", options.SinceId.ToString(unitedStatesEnglishCulture)); } if (!string.IsNullOrEmpty(options.GeoCode)) { this.RequestParameters.Add("geocode", options.GeoCode); } if (options.PrefixUsername) { this.RequestParameters.Add("show_user", "true"); } if (options.UntilDate > new DateTime()) { this.RequestParameters.Add("until", options.UntilDate.ToString("{0:yyyy-MM-dd}", unitedStatesEnglishCulture)); } switch (options.ResultType) { case SearchOptionsResultType.Mixed: this.RequestParameters.Add("result_type", "mixed"); break; case SearchOptionsResultType.Recent: this.RequestParameters.Add("result_type", "recent"); break; case SearchOptionsResultType.Popular: this.RequestParameters.Add("result_type", "popular"); break; } if (options.WithTwitterUserID) { this.RequestParameters.Add("with_twitter_user_id", "true"); } if (options.IncludeEntities) { this.RequestParameters.Add("include_entities", "true"); } }
private bool MatchDate(SearchOptions search) { int ageInDays = Age; if (search.HasMinDays && search.HasMaxDays) if (search.MinDaysSinceEdit < search.MaxDaysSinceEdit) return ((search.MinDaysSinceEdit <= ageInDays) && (ageInDays <= search.MaxDaysSinceEdit)); else return ((search.MinDaysSinceEdit <= ageInDays) || (ageInDays <= search.MaxDaysSinceEdit)); if (search.HasMinDays && search.MinDaysSinceEdit <= ageInDays) return true; if (search.HasMaxDays && ageInDays <= search.MaxDaysSinceEdit) return true; return false; }
public QuerySubmissionsByDomain(string domain, SearchOptions options, CachePolicy policy) : base(policy) { this._options = options; this._domain = domain; }
/// <summary> /// Build an 'EndsWith' expression for a search term against a particular string property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, string searchTerm, SearchOptions searchOptions) { var alteredTerm = searchOptions.SearchType == SearchType.WholeWords ? " " + searchTerm : searchTerm; var searchTermExpression = Expression.Constant(alteredTerm); var endsWithExpresion = Expression.Call(stringProperty.Body, ExpressionMethods.EndsWithMethodWithComparison, searchTermExpression, searchOptions.ComparisonTypeExpression); return(Expression.IsTrue(endsWithExpresion)); }
private bool MatchName(SearchOptions search) { return MatchText(search, Name); }
private void FindNext(bool replace, bool replaceAll) { bool found = false; if (FDesigner.ActiveReportTab.ActivePage == null) { // search in the code tab SyntaxEdit Edit = (FDesigner.ActiveReportTab.ActivePageDesigner as CodePageDesigner).Edit; if (FFirstSearch) { Edit.FirstSearch = true; } SearchOptions options = SearchOptions.None; if (cbMatchCase.Checked) { options |= SearchOptions.CaseSensitive; } if (cbMatchWholeWord.Checked) { options |= SearchOptions.WholeWordsOnly; } if (Edit.Selection.SelectedText == cbxFind.Text && replace && !replaceAll) { Edit.Selection.SelectedText = cbxReplace.Text; found = true; } else { while (true) { if (Edit.Find(cbxFind.Text, options)) { found = true; if (replace) { Edit.Selection.SelectedText = cbxReplace.Text; } if (!replaceAll) { break; } } else { break; } } } } else { ObjectCollection allObjects = FDesigner.ActiveReportTab.ActivePage.AllObjects; for (; FIndex < allObjects.Count; FIndex++) { Base c = allObjects[FIndex]; string text = ""; if (c is TextObject) { text = (c as TextObject).Text; } else if (c is RichObject) { text = (c as RichObject).Text; } List <CharacterRange> ranges = FindText(text, 0); if (ranges.Count > 0) { found = true; if (!replaceAll) { FDesigner.SelectedObjects.Clear(); FDesigner.SelectedObjects.Add(c); FDesigner.SelectionChanged(null); } if (replace) { int correction = 0; foreach (CharacterRange range in ranges) { text = text.Remove(range.First + correction, range.Length); text = text.Insert(range.First + correction, cbxReplace.Text); correction += cbxReplace.Text.Length - range.Length; } if (c is TextObject) { (c as TextObject).Text = text; } else if (c is RichObject) { (c as RichObject).Text = text; } } if (!replaceAll) { FIndex++; break; } } } } if (found && replace) { FDesigner.SetModified(null, "Change"); } if (FFirstSearch) { if (!found) { FRMessageBox.Information(Res.Get("Forms,SearchReplace,NotFound")); } FFirstSearch = false; } else { if (!found) { FRMessageBox.Information(Res.Get("Forms,SearchReplace,NoMoreFound")); } } }
private bool MatchSummary(SearchOptions search) { return MatchText(search, Summary); }
public async Task EverythingOperationGETReturn200OnSuccess() { // Create VonkContext for $everything (GET / Instance level) var testContext = new VonkTestContext(VonkInteraction.instance_custom); // Setup Patient resource var patient = CreateTestPatientNoReferences(); string patientStr = FhirAsJsonString(patient); var account = CreateTestAccountForPatient(); var searchOptions = SearchOptions.Latest(testContext.ServerBase, testContext.Request.Interaction, testContext.InformationModel); var patSearchResult = new SearchResult(new List <IResource>() { patient }, 1, 1); var searchArgs = new ArgumentCollection( new Argument(ArgumentSource.Internal, ArgumentNames.resourceType, patient.GetResourceTypeIndicator()) { MustHandle = true }, new Argument(ArgumentSource.Internal, ArgumentNames.resourceId, $"{patient.Id}") { MustHandle = true } ); _searchMock.Setup(repo => repo.Search(searchArgs, searchOptions)).ReturnsAsync(patSearchResult); var acctsearchResult = new SearchResult(new List <IResource>() { account }, 1, 1); searchArgs = new ArgumentCollection( new Argument(ArgumentSource.Internal, ArgumentNames.resourceType, account.GetResourceTypeIndicator()) { MustHandle = true }, new Argument(ArgumentSource.Internal, "subject", $"Patient/{patient.Id}") { MustHandle = true } ); _searchMock.Setup(repo => repo.Search(searchArgs, searchOptions)).ReturnsAsync(acctsearchResult); testContext.Arguments.AddArguments(new[] { new Argument(ArgumentSource.Path, ArgumentNames.resourceType, "Patient"), new Argument(ArgumentSource.Path, ArgumentNames.resourceId, "test") }); testContext.TestRequest.CustomOperation = "everything"; testContext.TestRequest.Method = "GET"; // Execute $everything await _everythingService.PatientInstanceGET(testContext); // Check response status testContext.Response.HttpResult.Should().Be(StatusCodes.Status200OK, "$everything should succeed with HTTP 200 - OK on test patient"); testContext.Response.Payload.Should().NotBeNull(); var bundleType = testContext.Response.Payload.SelectText("type"); bundleType.Should().Be("searchset", "Bundle.type should be set to 'searchset'"); var bundle = testContext.Response.Payload.ToPoco <Bundle>(); bundle.Entry.Count.Should().Be(1); bundle.Entry[0].Resource.ResourceType.Should().Be(ResourceType.Patient); string bundleStr = FhirAsJsonString(testContext.Response.Payload); }
private static bool MatchText(SearchOptions search, string text) { bool found; if (search.FindAll) { found = true; if (search.SearchWords.Any(searchString => !text.Contains(searchString, search.ComparisonMethod))) return false; } else //FindAny { found = false; if (search.SearchWords.Any(searchString => text.Contains(searchString, search.ComparisonMethod))) return true; } return found; }
protected override Task <SearchResult> SearchHistoryInternalAsync( SearchOptions searchOptions, CancellationToken cancellationToken) { return(Task.FromResult(SearchImplementation(searchOptions))); }
private bool MatchMeta(SearchOptions search) { if (!HasMetadata) return false; return Metadata.Match(search); }
protected override Task <SearchResult> SearchForReindexInternalAsync(SearchOptions searchOptions, string searchParameterHash, CancellationToken cancellationToken) { return(Task.FromResult(SearchImplementation(searchOptions))); }
internal SearchingForPlayerEventArgs([CanBeNull] Player player, [NotNull] string searchTerm, List<Player> matches, SearchOptions options) { if (searchTerm == null) throw new ArgumentNullException("searchTerm"); Player = player; SearchTerm = searchTerm; Matches = matches; Options = options; }
static void Main(string[] args) { try { //Debug.Assert(false, "Attach VS here!"); Console.OutputEncoding = new UTF8Encoding(); PrintHeader(); BaseAPI.SetMessageAction(message => Console.WriteLine(message)); if (args.Length == 0) { PrintTwits(Timeline.GetTimeline().Result); return; } if (args[0].StartsWith("/")) { string flag = args[0].ToLower().Trim(); switch (flag) { case CLEAR: AuthenticatedUser.ClearCredentials(); Console.WriteLine("User credentials cleared!"); return; case HELP: ShowUsage(); return; case TIME_LINE: PrintTwits(Timeline.GetTimeline().Result); return; case MENTIONS: PrintTwits(Mentions.GetMentions().Result); return; case SEARCH: SearchOptions options = new SearchOptions { Query = string.Join(" ", args).Substring(2), User = AuthenticatedUser.LoadCredentials() }; PrintTwits(Search.SearchTweets(options).Result); return; case LIKES: PrintTwits(Likes.GetUserLikes(new LikesOptions()).Result); return; case USER: if (args.Length != 2) { throw new ArgumentNullException("screenname", "The user' screen name must be provided"); } UserTimelineOptions usrOptions = new UserTimelineOptions { ScreenName = args[1] }; PrintTwits(UserTimeline.GetUserTimeline(usrOptions).Result); return; case STREAMING: if (args.Length != 2) { throw new ArgumentNullException("streaming", "The track must be provided"); } StreammingFilterOptions streamingOptions = new StreammingFilterOptions { Track = args[1] }; Console.WriteLine("Starting live streaming, press ctrl+c to quit"); foreach (Status s in StreamingFilter.GetStreamingTimeline(streamingOptions)) { PrintTwit(s); } return; default: Console.WriteLine($"Invalid flag: {flag}"); ShowUsage(); return; } } if (args[0].StartsWith("\\") || args[0].Length == 1) { Console.WriteLine("Really? do you really wanna twit that?. [T]wit, or [N]o sorry, I messed up..."); ConsoleKeyInfo input = Console.ReadKey(); while (input.Key != ConsoleKey.T && input.Key != ConsoleKey.N) { Console.WriteLine(); Console.WriteLine("[T]wit, or [N]o sorry, I messed up..."); input = Console.ReadKey(); } Console.WriteLine(); if (input.Key == ConsoleKey.N) { Console.WriteLine("That's what I thought! ;)"); return; } } string response = Update.UpdateStatus(string.Join(" ", args)).Result; if (response != "OK") { Console.WriteLine($"Response was not OK: {response}"); } } catch (WebException wex) { Console.WriteLine(wex.Message); HttpWebResponse res = (HttpWebResponse)wex.Response; if (res != null) { UpdateError errors = ShelltwitLib.Helpers.Util.Deserialize <UpdateError>(res.GetResponseStream()); errors.errors.ForEach(e => Console.WriteLine(e.ToString())); } } catch (Exception ex) { PrintException(ex); } finally { #if DEBUG if (Debugger.IsAttached) { Console.WriteLine("Press <enter> to exit..."); Console.ReadLine(); } #endif } Environment.Exit(0); }
/// <summary> /// Search the folder for messages matching the specified query. /// </summary> /// <remarks> /// Searches the folder for messages matching the specified query, /// returning only the specified search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="query">The search query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="query"/> is <c>null</c>. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The IMAP server does not support the ESEARCH extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The <see cref="MailFolder"/> is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public abstract SearchResults Search (SearchOptions options, SearchQuery query, CancellationToken cancellationToken = default (CancellationToken));
/// <summary> /// Build a 'indexof() == 0' expression for a search term against a particular string property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, IEnumerable <string> searchTerms, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var searchTerm in searchTerms) { var startsWithExpression = Build(stringProperty, searchTerm, searchOptions); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, startsWithExpression); } return(completeExpression); }
/// <summary> /// Searches the subset of UIDs in the folder for messages matching the specified query, /// returning them in the preferred sort order. /// </summary> /// <remarks> /// Searches the folder for messages matching the specified query and ordering, /// returning only the requested search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="uids">The subset of UIDs</param> /// <param name="query">The search query.</param> /// <param name="orderBy">The sort order.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uids"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="query"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para>One or more of the <paramref name="uids"/> is invalid.</para> /// <para>-or-</para> /// <para><paramref name="orderBy"/> is empty.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The server does not support the ESORT extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="IMailStore"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="IMailStore"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="IMailStore"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The folder is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="CommandException"> /// The command failed. /// </exception> public abstract SearchResults Search (SearchOptions options, IList<UniqueId> uids, SearchQuery query, IList<OrderBy> orderBy, CancellationToken cancellationToken = default (CancellationToken));
/// <summary> /// Build an 'indexof() == 0' expression for a search term against a particular string property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, string searchTerm, SearchOptions searchOptions) { var alteredSearchTerm = searchOptions.SearchType == SearchType.WholeWords ? searchTerm + " " : searchTerm; var searchTermExpression = Expression.Constant(alteredSearchTerm); if (searchOptions.NullCheck) { var coalesceExpression = Expression.Coalesce(stringProperty.Body, ExpressionMethods.EmptyStringExpression); return(Expression.Call(coalesceExpression, ExpressionMethods.StartsWithMethodWithComparison, searchTermExpression, searchOptions.ComparisonTypeExpression)); } return(Expression.Call(stringProperty.Body, ExpressionMethods.StartsWithMethodWithComparison, searchTermExpression, searchOptions.ComparisonTypeExpression)); }
/// <summary> /// Performs a search. /// </summary> /// <param name="query">The search query.</param> /// <param name="fullText">A value indicating whether to perform a full-text search.</param> /// <param name="filesAndAttachments">A value indicating whether to search the names of files and attachments.</param> /// <param name="options">The search options.</param> /// <returns>The search results.</returns> /// <exception cref="ArgumentNullException">If <b>query</b> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If <b>query</b> is empty.</exception> public SearchResultCollection PerformSearch(string query, bool fullText, bool filesAndAttachments, SearchOptions options) { if(query == null) throw new ArgumentNullException("query"); if(query.Length == 0) throw new ArgumentException("Query cannot be empty", "query"); return SearchTools.Search(query, fullText, filesAndAttachments, options); }
/// <summary> /// Build a 'indexof() == 0' expression for a search term against a particular string property /// </summary> private static Expression Build <T>(Expression <Func <T, string> > stringProperty, IEnumerable <Expression <Func <T, string> > > propertiesToSearchFor, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var propertyToSearchFor in propertiesToSearchFor) { var startsWithExpression = Build(stringProperty, propertyToSearchFor, searchOptions.ComparisonTypeExpression); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, startsWithExpression); } return(completeExpression); }
public void Push(SearchOptions options) { try { if (options == null) return; _Stack.Push(options); SaveStack(); Debug.WriteLine(STACK_FILE_NAME + ": Push: " + options.ToString()); } catch (Exception ex) { Debug.WriteLine("\nStackMgr.Push " + ex.ToString()); } finally { /*Debug.WriteLine("Stack.Push finally block");*/ } }
/// <summary> /// Build an 'indexof() == 0' expression for a search term against a particular string property /// </summary> public static Expression Build <T>(Expression <Func <T, string> >[] stringProperties, Expression <Func <T, string> >[] propertiesToSearchFor, SearchOptions searchOptions) { Expression completeExpression = null; foreach (var stringProperty in stringProperties) { var startsWithExpression = Build(stringProperty, propertiesToSearchFor, searchOptions); completeExpression = ExpressionHelper.JoinOrExpression(completeExpression, startsWithExpression); } return(completeExpression); }
public static Player[] FindPlayers( [NotNull] Player player, [NotNull] string name, SearchOptions options ) { if( player == null ) throw new ArgumentNullException( "player" ); if( name == null ) throw new ArgumentNullException( "name" ); bool includeHidden = (options & SearchOptions.IncludeHidden) != 0; bool includeSelf = (options & SearchOptions.IncludeSelf) != 0; bool suppressEvent = (options & SearchOptions.SuppressEvent) != 0; bool returnSelf = (options & SearchOptions.ReturnSelfIfOnlyMatch) != 0; // Repeat last-used player name if( name == "-" ) { if( player.LastUsedPlayerName != null ) { name = player.LastUsedPlayerName; } else { return new Player[0]; } } // in case someone tries to use the "!" prefix in an online-only search if( name.Length > 0 && name[0] == '!' ) { name = name.Substring( 1 ); } bool foundSelf = false; List<Player> results = new List<Player>(); Player[] tempList = Players; foreach( Player otherPlayer in tempList ) { if( otherPlayer == null || !includeHidden && !player.CanSee( otherPlayer ) ) { continue; } if( otherPlayer.Name.Equals( name, StringComparison.OrdinalIgnoreCase ) ) { if( !includeSelf && otherPlayer == player ) { foundSelf = true; } else { results.Clear(); results.Add( otherPlayer ); break; } } else if( otherPlayer.Name.StartsWith( name, StringComparison.OrdinalIgnoreCase ) ) { if( !includeSelf && otherPlayer == player ) { foundSelf = true; } else { results.Add( otherPlayer ); } } } // set LastUsedPlayerName if we found one result if( results.Count == 1 ) { player.LastUsedPlayerName = results[0].Name; } // raise the SearchingForPlayer event if( !suppressEvent ) { var h = SearchingForPlayer; if( h != null ) { var e = new SearchingForPlayerEventArgs( player, name, results, options ); h( null, e ); } } // special behavior for ReturnSelfIfOnlyMatch flag if( results.Count == 0 && !includeSelf && foundSelf && returnSelf ) { results.Add( player ); } return results.ToArray(); }
protected override async Task <SearchResult> SearchHistoryInternalAsync(SearchOptions searchOptions, CancellationToken cancellationToken) { SqlSearchOptions sqlSearchOptions = new SqlSearchOptions(searchOptions); return(await SearchImpl(sqlSearchOptions, SqlSearchType.History, null, cancellationToken)); }
public static Player FindPlayerOrPrintMatches( [NotNull] Player player, [NotNull] string namePart, SearchOptions options ) { if( player == null ) throw new ArgumentNullException( "player" ); if( namePart == null ) throw new ArgumentNullException( "namePart" ); // Repeat last-used player name if( namePart == "-" ) { if( player.LastUsedPlayerName != null ) { namePart = player.LastUsedPlayerName; } else { player.Message( "Cannot repeat player name: you haven't used any names yet." ); return null; } } // in case someone tries to use the "!" prefix in an online-only search if( namePart.Length > 0 && namePart[0] == '!' ) { namePart = namePart.Substring( 1 ); } // Make sure player name is valid if( !Player.ContainsValidCharacters( namePart ) ) { player.MessageInvalidPlayerName( namePart ); return null; } Player[] matches = FindPlayers( player, namePart, options ); if( matches.Length == 0 ) { player.MessageNoPlayer( namePart ); return null; } else if( matches.Length > 1 ) { player.MessageManyMatches( "player", matches ); return null; } else { player.LastUsedPlayerName = matches[0].Name; return matches[0]; } }
public override async Task <SearchResult> SearchAsync(SearchOptions searchOptions, CancellationToken cancellationToken) { SqlSearchOptions sqlSearchOptions = new SqlSearchOptions(searchOptions); SearchResult searchResult = await SearchImpl(sqlSearchOptions, SqlSearchType.Default, null, cancellationToken); int resultCount = searchResult.Results.Count(); if (!sqlSearchOptions.IsSortWithFilter && searchResult.ContinuationToken == null && resultCount <= sqlSearchOptions.MaxItemCount && sqlSearchOptions.Sort != null && sqlSearchOptions.Sort.Count > 0 && sqlSearchOptions.Sort[0].searchParameterInfo.Code != KnownQueryParameterNames.LastUpdated) { // We seem to have run a sort which has returned less results than what max we can return. // Let's determine whether we need to execute another query or not. if ((sqlSearchOptions.Sort[0].sortOrder == SortOrder.Ascending && sqlSearchOptions.DidWeSearchForSortValue.HasValue && !sqlSearchOptions.DidWeSearchForSortValue.Value) || (sqlSearchOptions.Sort[0].sortOrder == SortOrder.Descending && sqlSearchOptions.DidWeSearchForSortValue.HasValue && sqlSearchOptions.DidWeSearchForSortValue.Value)) { if (sqlSearchOptions.MaxItemCount - resultCount == 0) { // Since we are already returning MaxItemCount number of resources we don't want // to execute another search right now just to drop all the resources. We will return // a "special" ct so that we the subsequent request will be handled correctly. var ct = new ContinuationToken(new object[] { SqlSearchConstants.SortSentinelValueForCt, 0, }); searchResult = new SearchResult(searchResult.Results, ct.ToJson(), searchResult.SortOrder, searchResult.UnsupportedSearchParameters); } else { var finalResultsInOrder = new List <SearchResultEntry>(); finalResultsInOrder.AddRange(searchResult.Results); sqlSearchOptions.SortQuerySecondPhase = true; sqlSearchOptions.MaxItemCount -= resultCount; searchResult = await SearchImpl(sqlSearchOptions, SqlSearchType.Default, null, cancellationToken); finalResultsInOrder.AddRange(searchResult.Results); searchResult = new SearchResult( finalResultsInOrder, searchResult.ContinuationToken, searchResult.SortOrder, searchResult.UnsupportedSearchParameters); } } } // If we should include the total count of matching search results if (sqlSearchOptions.IncludeTotal == TotalType.Accurate && !sqlSearchOptions.CountOnly) { // If this is the first page and there aren't any more pages if (sqlSearchOptions.ContinuationToken == null && searchResult.ContinuationToken == null) { // Count the match results on the page. searchResult.TotalCount = searchResult.Results.Count(r => r.SearchEntryMode == SearchEntryMode.Match); } else { try { // Otherwise, indicate that we'd like to get the count sqlSearchOptions.CountOnly = true; // And perform a second read. var countOnlySearchResult = await SearchImpl(sqlSearchOptions, SqlSearchType.Default, null, cancellationToken); searchResult.TotalCount = countOnlySearchResult.TotalCount; } finally { // Ensure search options is set to its original state. sqlSearchOptions.CountOnly = false; } } } return(searchResult); }
/// <summary> /// Searches the subset of UIDs in the folder for messages matching the specified query. /// </summary> /// <remarks> /// Searches the fsubset of UIDs in the folder for messages matching the specified query, /// returning only the specified search results. /// </remarks> /// <returns>The search results.</returns> /// <param name="options">The search options.</param> /// <param name="uids">The subset of UIDs</param> /// <param name="query">The search query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uids"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="query"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// One or more of the <paramref name="uids"/> is invalid. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>One or more search terms in the <paramref name="query"/> are not supported by the IMAP server.</para> /// <para>-or-</para> /// <para>The IMAP server does not support the ESEARCH extension.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="ImapClient"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="ImapClient"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// The <see cref="ImapClient"/> is not authenticated. /// </exception> /// <exception cref="FolderNotOpenException"> /// The <see cref="ImapFolder"/> is not currently open. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="ImapProtocolException"> /// The server's response contained unexpected tokens. /// </exception> /// <exception cref="ImapCommandException"> /// The server replied with a NO or BAD response. /// </exception> public override SearchResults Search (SearchOptions options, IList<UniqueId> uids, SearchQuery query, CancellationToken cancellationToken = default (CancellationToken)) { var set = ImapUtils.FormatUidSet (uids); var args = new List<string> (); string charset; if (query == null) throw new ArgumentNullException ("query"); CheckState (true, false); if ((Engine.Capabilities & ImapCapabilities.ESearch) == 0) throw new NotSupportedException ("The IMAP server does not support the ESEARCH extension."); if (uids.Count == 0) return new SearchResults (); var optimized = query.Optimize (new ImapSearchQueryOptimizer ()); var expr = BuildQueryExpression (optimized, args, out charset); var command = "UID SEARCH RETURN ("; if ((options & SearchOptions.Count) != 0) command += "COUNT "; if ((options & SearchOptions.Min) != 0) command += "MIN "; if ((options & SearchOptions.Max) != 0) command += "MAX "; command = command.TrimEnd (); command += ") "; if (args.Count > 0 && !Engine.UTF8Enabled) command += "CHARSET " + charset + " "; command += "UID " + set + " " + expr + "\r\n"; var ic = new ImapCommand (Engine, cancellationToken, this, command, args.ToArray ()); ic.RegisterUntaggedHandler ("ESEARCH", ESearchMatches); ic.UserData = new SearchResults (); Engine.QueueCommand (ic); Engine.Wait (ic); ProcessResponseCodes (ic, null); if (ic.Response != ImapCommandResponse.Ok) throw ImapCommandException.Create ("SEARCH", ic); return (SearchResults) ic.UserData; }
public static Task <EntityInfo[]> Search(string text, SearchOptions options, EntityType?type = null) { return(Search(text, options, CancellationToken.None, type)); }
private void SimulateSearch(string pattern, SearchKind searchKind = null, SearchOptions searchOptions = SearchOptions.None) { searchKind = searchKind ?? SearchKind.Forward; var data = new SearchData(pattern, searchKind, searchOptions); _search.SetupGet(x => x.InSearch).Returns(true).Verifiable(); _search.SetupGet(x => x.CurrentSearchData).Returns(FSharpOption.Create(data)).Verifiable(); }
public void SearchOptions_Default() { SearchOptions options = SearchOptions.Default; Assert.AreEqual("", options.ToString()); }