public void Update(SearchResult?other) { if (other is null) { return; } if (TotalResults != other.TotalResults) { TotalResults = other.TotalResults; OnPropertyChanged(nameof(TotalResults)); } if (HasMore != other.HasMore) { HasMore = other.HasMore; OnPropertyChanged(nameof(HasMore)); } if (!Query.DeepEquals(other.Query)) { Query.Update(other.Query); OnPropertyChanged(nameof(Query)); } if (ReplacementContinuationToken != other.ReplacementContinuationToken) { ReplacementContinuationToken = other.ReplacementContinuationToken; OnPropertyChanged(nameof(ReplacementContinuationToken)); } if (UseTotalResults != other.UseTotalResults) { UseTotalResults = other.UseTotalResults; OnPropertyChanged(nameof(UseTotalResults)); } }
public static int Compare(SearchResult?r1, SearchResult?r2) { if (r1 == null && r2 == null) { return(0); } if (r1 == null) { return(-1); } if (r2 == null) { return(1); } if (r1.File != null && r2.File != null) { var sfCmp = SearchFile.Compare(r1.File, r2.File); if (sfCmp != 0) { return(sfCmp); } } if (r1.LineNum == r2.LineNum) { return(r1.MatchStartIndex - r2.MatchStartIndex); } return(r1.LineNum - r2.LineNum); }
public override int Compare(SearchResult?x, SearchResult?y) { if (object.ReferenceEquals(x, y)) { return(0); } if (x == null) { return(-1); } if (y == null) { return(1); } int diff = x.GetSize().CompareTo(y.GetSize()); if (diff != 0) { return(diff); } return(Name.Compare(x, y)); }
public async Task ChannelInfoCommand([Remainder] string searchTerm) { Channel?channelListResult; using (var youtubeService = new YouTubeService(new BaseClientService.Initializer { ApiKey = _botCredentials.GoogleApiKey, ApplicationName = GetType().ToString() })) { SearchResource.ListRequest searchListRequest = youtubeService.Search.List("snippet"); searchListRequest.Q = searchTerm; searchListRequest.MaxResults = 1; SearchResult?searchListResult = (await searchListRequest.ExecuteAsync()).Items.FirstOrDefault(); if (searchListResult == null) { await SendErrorAsync("Could not find the requested channel!"); return; } ChannelsResource.ListRequest channelListRequest = youtubeService.Channels.List("snippet"); channelListRequest.Id = searchListResult.Snippet.ChannelId; channelListRequest.MaxResults = 10; channelListResult = (await channelListRequest.ExecuteAsync()).Items.FirstOrDefault(); if (channelListResult == null) { await SendErrorAsync("Could not find the requested channel!"); return; } } var builder = new EmbedBuilder() .WithTitle(channelListResult.Snippet.Title) .WithColor(GetColor(Context)) .WithFooter(channelListResult.Id) .WithThumbnailUrl(channelListResult.Snippet.Thumbnails.Medium.Url); if (!string.IsNullOrEmpty(channelListResult.Snippet.Description)) { builder.AddField("Description", channelListResult.Snippet.Description); } if (channelListResult.Snippet.Country != null) { builder.AddField("Country", channelListResult.Snippet.Country, true); } if (channelListResult.Snippet.PublishedAt != null) { // date is in format YYYY-MM-DDThh:mm:ssZ - remove the T and Z builder.AddField("Created", channelListResult.Snippet.PublishedAt.Replace('T', ' ').Remove(19), true); } await ReplyAsync(embed : builder.Build()); }
public static ReplicationConnection FindByName(DirectoryContext context, string name) { ValidateArgument(context, name); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the servername property DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName) !; string connectionContainer = "CN=NTDS Settings," + serverDN; de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer); // doing the search to find the connection object based on its name ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=" + Utils.GetEscapedFilterValue(name) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* no paged search */ false /* don't cache results */); SearchResult?srchResult = null; try { srchResult = adSearcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } if (srchResult == null) { // no such connection object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name); throw e; } else { DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); return(new ReplicationConnection(context, connectionEntry, name)); } } finally { de.Dispose(); } }
public bool DeepEquals(SearchResult?other) { return(other is not null && TotalResults == other.TotalResults && HasMore == other.HasMore && (Query is not null ? Query.DeepEquals(other.Query) : other.Query is null) && ReplacementContinuationToken == other.ReplacementContinuationToken && UseTotalResults == other.UseTotalResults); }
public static DiscordEmbedBuilder AsEmbed(this SearchResult?searchResult) { var result = new DiscordEmbedBuilder { //Title = "IRD Library Search Result", Color = Config.Colors.DownloadLinks, }; if (searchResult?.Data is null or { Count : 0 })
public override int Compare(SearchResult?x, SearchResult?y) { if (object.ReferenceEquals(x, y)) { return(0); } if (x == null) { return(-1); } if (y == null) { return(1); } return(x.FileSystemInfo.LastWriteTime.CompareTo(y.FileSystemInfo.LastWriteTime)); }
private RenameLocations( ISymbol symbol, Solution solution, RenameOptionSet options, SearchResult?originalSymbolResult, SearchResult mergedResult, ImmutableArray <SearchResult> overloadsResult, ImmutableArray <RenameLocation> stringsResult, ImmutableArray <RenameLocation> commentsResult) { Solution = solution; Symbol = symbol; Options = options; _originalSymbolResult = originalSymbolResult; _mergedResult = mergedResult; _overloadsResult = overloadsResult; _stringsResult = stringsResult; _commentsResult = commentsResult; }
public async Task <List <BloodRequestSearchRecordDto> > GetSearchResultsAsync(string searchString) { var requests = new List <BloodRequestSearchRecordDto>(); SearchResult?searchResult = null; try { searchResult = await _redisSearchClient.SearchAsync(new Query(searchString) { WithPayloads = true }); _logger.LogInformation("search result: {info}", searchResult); } catch (Exception ex) { _logger.LogError(ex, "Redis Search for Blood Requests"); } if (searchResult == null) { return(requests); } requests.AddRange(from doc in searchResult.Documents let record = doc.GetProperties().ToList() let status = int.Parse(record.FirstOrDefault(p => p.Key == "status").Value.ToString() ?? string.Empty, CultureInfo.InvariantCulture) where status <= 2 select new BloodRequestSearchRecordDto { SearchId = doc.Id, SearchScore = doc.Score, RequestId = Guid.Parse(doc.Id), PatientName = record.FirstOrDefault(p => p.Key == "patientName").Value.ToString(), Reason = record.FirstOrDefault(p => p.Key == "reason").Value.ToString(), QuantityInUnits = double.Parse(record.FirstOrDefault(p => p.Key == "units").Value.ToString(), CultureInfo.InvariantCulture), DonationType = Enumeration.FromValue <BloodDonationType>(record.FirstOrDefault(p => p.Key == "donationType").Value.ToString()).Name, BloodGroup = Enumeration.FromValue <BloodGroup>(record.FirstOrDefault(p => p.Key == "bloodGroup").Value.ToString()).Name, Priority = Enumeration.FromValue <BloodRequestPriority>(record.FirstOrDefault(p => p.Key == "priority").Value.ToString()).Name, Status = Enumeration.FromValue <DetailedStatus>(status).Name }); return(requests); }
public async Task <List <BloodRequestSearchRecordDto> > GetSearchResultsFromDbAsync(string searchString) { var requests = new List <BloodRequestSearchRecordDto>(); SearchResult?searchResult = null; try { searchResult = await _redisSearchClient.SearchAsync(new Query(searchString) { WithPayloads = true }); _logger.LogInformation("search result: {info}", searchResult); } catch (Exception ex) { _logger.LogError(ex, "Redis Search for Blood Requests"); } if (searchResult == null) { return(requests); } var db = _connectionMultiplexer.GetDatabase(); var result = await db.JsonMultiGetAsync <BloodRequest>(searchResult.Documents.Select(q => new RedisKey(RedisConstants.GetBloodRequestPersistenceKey(q.Id))).ToArray()); var filteredResult = result.Where(q => q.Status is DetailedStatusList.Open or DetailedStatusList.Assigned) .Select(q => new BloodRequestSearchRecordDto() { Status = q.Status.GetDescription(), RequestId = q.Id, PatientName = q.PatientName, Reason = q.Reason, BloodGroup = q.BloodGroup.GetDescription(), DonationType = q.DonationType.GetDescription(), Priority = q.Priority.GetDescription(), QuantityInUnits = q.QuantityInUnits }); requests.AddRange(filteredResult); return(requests); }
public override int Compare(SearchResult?x, SearchResult?y) { if (object.ReferenceEquals(x, y)) { return(0); } if (x == null) { return(-1); } if (y == null) { return(1); } return(string.Compare( x.FileMatch.NameMatch !.Value, y.FileMatch.NameMatch !.Value, StringComparison)); }
/// <summary> /// This search source does not track selection state. /// </summary> public virtual void NotifyDeselected(SearchResult?result) { // This space intentionally left blank. }
public int Compare(SearchResult?r1, SearchResult?r2) { return(SearchResult.Compare(r1, r2)); }
public static ActiveDirectorySiteLinkBridge FindByName(DirectoryContext context, string bridgeName, ActiveDirectoryTransportType transport) { ValidateArgument(context, bridgeName, transport); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext) !; string containerDN = "CN=Inter-Site Transports,CN=Sites," + config; if (transport == ActiveDirectoryTransportType.Rpc) { containerDN = "CN=IP," + containerDN; } else { containerDN = "CN=SMTP," + containerDN; } de = DirectoryEntryManager.GetDirectoryEntry(context, containerDN); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLinkBridge)(objectCategory=SiteLinkBridge)(name=" + Utils.GetEscapedFilterValue(bridgeName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult?srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such site link bridge object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); throw e; } else { DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // it is an existing site link bridge object ActiveDirectorySiteLinkBridge bridge = new ActiveDirectorySiteLinkBridge(context, bridgeName, transport, true); bridge.cachedEntry = connectionEntry; return(bridge); } } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // if it is ADAM and transport type is SMTP, throw NotSupportedException. DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp) { throw new NotSupportedException(SR.NotSupportTransportSMTP); } else { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySiteLinkBridge), bridgeName); } } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { de.Dispose(); } }
public static ActiveDirectorySubnet FindByName(DirectoryContext context, string subnetName) { ValidateArgument(context, subnetName); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext) !; string subnetdn = "CN=Subnets,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, subnetdn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=subnet)(objectCategory=subnet)(name=" + Utils.GetEscapedFilterValue(subnetName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult?srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such subnet object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); throw e; } else { string? siteName = null; DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // try to get the site that this subnet lives in if (connectionEntry.Properties.Contains("siteObject")) { NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname) new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; string tmp = (string)connectionEntry.Properties["siteObject"][0] !; // escaping manipulation pathCracker.Set(tmp, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); siteName = rdn.Substring(3); } // it is an existing subnet object ActiveDirectorySubnet?subnet = null; if (siteName == null) { subnet = new ActiveDirectorySubnet(context, subnetName, null, true); } else { subnet = new ActiveDirectorySubnet(context, subnetName, siteName, true); } subnet.cachedEntry = connectionEntry; return(subnet); } } catch (COMException e) { if (e.ErrorCode == unchecked ((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (de != null) { de.Dispose(); } } }
public override abstract int Compare(SearchResult?x, SearchResult?y);
public override int Compare(SearchResult?x, SearchResult?y) { if (object.ReferenceEquals(x, y)) { return(0); } if (x == null) { return(-1); } if (y == null) { return(1); } string path1 = x.Path; string path2 = y.Path; int i1 = -1; int i2 = -1; while (true) { int l1 = FileSystemHelpers.IndexOfDirectorySeparator(path1, ++i1) - i1; int l2 = FileSystemHelpers.IndexOfDirectorySeparator(path2, ++i2) - i2; bool isLast1 = i1 + l1 == path1.Length; bool isLast2 = i2 + l2 == path2.Length; if (isLast1) { if (isLast2) { if (x.IsDirectory) { if (!y.IsDirectory) { return(-1); } } else if (y.IsDirectory) { return(1); } } else if (!x.IsDirectory) { return(1); } } else if (isLast2 && !y.IsDirectory) { return(-1); } int diff = string.Compare(path1, i1, path2, i2, Math.Min(l1, l2), StringComparison); if (diff != 0) { return(diff); } if (l1 != l2) { diff = l1 - l2; if (diff != 0) { return(diff); } } i1 += l1; i2 += l2; if (isLast1) { return((isLast2) ? 0 : -1); } if (isLast2) { return(1); } } }
/// <devdoc> /// Advances the enumerator to the next element of the collection /// and returns a Boolean value indicating whether a valid element is available. /// </devdoc> public bool MoveNext() { DirectorySynchronization?tempsync = null; DirectoryVirtualListView?tempvlv = null; int errorCode = 0; if (_eof) { return(false); } _currentResult = null; if (!_initialized) { int hr = _results.SearchObject.GetFirstRow(_results.Handle); if (hr != UnsafeNativeMethods.S_ADS_NOMORE_ROWS) { //throw a clearer exception if the filter was invalid if (hr == UnsafeNativeMethods.INVALID_FILTER) { throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter, _results.Filter)); } if (hr != 0) { throw COMExceptionHelper.CreateFormattedComException(hr); } _eof = false; _initialized = true; return(true); } _initialized = true; } while (true) { // clear the last error first CleanLastError(); errorCode = 0; int hr = _results.SearchObject.GetNextRow(_results.Handle); // SIZE_LIMIT_EXCEEDED occurs when we supply too generic filter or small SizeLimit value. if (hr == UnsafeNativeMethods.S_ADS_NOMORE_ROWS || hr == UnsafeNativeMethods.SIZE_LIMIT_EXCEEDED) { // need to make sure this is not the case that server actually still has record not returned yet if (hr == UnsafeNativeMethods.S_ADS_NOMORE_ROWS) { hr = GetLastError(ref errorCode); // get last error call failed, we need to bail out if (hr != 0) { throw COMExceptionHelper.CreateFormattedComException(hr); } } // not the case that server still has result, we are done here if (errorCode != SafeNativeMethods.ERROR_MORE_DATA) { // get the dirsync cookie as we finished all the rows if (_results.srch.directorySynchronizationSpecified) { tempsync = _results.srch.DirectorySynchronization; } // get the vlv response as we finished all the rows if (_results.srch.directoryVirtualListViewSpecified) { tempvlv = _results.srch.VirtualListView; } _results.srch.searchResult = null; _eof = true; _initialized = false; return(false); } else { uint temp = (uint)errorCode; temp = (temp & 0x0000FFFF) | (7 << 16) | 0x80000000; throw COMExceptionHelper.CreateFormattedComException((int)temp); } } //throw a clearer exception if the filter was invalid if (hr == UnsafeNativeMethods.INVALID_FILTER) { throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter, _results.Filter)); } if (hr != 0) { throw COMExceptionHelper.CreateFormattedComException(hr); } _eof = false; return(true); } }
public int Compare(SearchResult?x, SearchResult?y) { //elements with higher Fitness come first return(Comparer <float> .Default.Compare(y?.Fitness ?? 0, x?.Fitness ?? 0)); }
public int Compare(SearchResult?x, SearchResult?y) { return(StringComparer.Ordinal.Compare(x?.Name ?? "", y?.Name ?? "")); }
private async Task UpdateSearchQueryAsync(Guid id, ICollection <Auction> auctions) { using var context = this.factory.GetContext(); var entity = await context.SearchQueries.AsTracking() .SingleAsync(x => x.Id == id); var externalIds = auctions.Select(x => x.Provider.Value).ToList(); var existingAuctions = await context.Auctions .IgnoreQueryFilters() .Where(x => externalIds.Contains(x.Provider.Value)) .Select(x => new { Id = x.Id, ExternalId = x.Provider.Value, Result = x.Results.SingleOrDefault(y => y.QueryId == id) }) .ToListAsync(); var nameCandidates = auctions.Select(x => x.Info.Name).ToList(); var sellerCandidates = auctions.Select(x => x.Seller.Provider.Value).ToList(); var deletedDuplicateCandidates = await context.SearchResults .IgnoreQueryFilters() .Where(x => x.QueryId == id && x.Lifetime.IsDeleted && nameCandidates.Contains(x.Auction.Info.Name) && sellerCandidates.Contains(x.Auction.Seller.Provider.Value)) .Select(x => new { Name = x.Auction.Info.Name, ExternalSellerId = x.Auction.Seller.Provider.Value }) .ToListAsync(); var externalCategoryIds = auctions.Select(x => x.Category.Provider.Value).Distinct().ToList(); var existingCategories = await context.Categories .Where(x => externalCategoryIds.Contains(x.Provider.Value)) .Select(x => new { Id = x.Id, ExternalId = x.Provider.Value }) .ToListAsync(); var newCategories = externalCategoryIds .Where(x => !existingCategories.Any(y => y.ExternalId == x)) .Select(x => auctions.Select(y => y.Category).First(y => y.Provider.Value == x)) .ToList(); var externalSellerIds = auctions.Select(x => x.Seller.Provider.Value).Distinct().ToList(); var existingSellers = await context.Sellers .Where(x => externalSellerIds.Contains(x.Provider.Value)) .Select(x => new { Id = x.Id, ExternalId = x.Provider.Value }) .ToListAsync(); var newSellers = externalSellerIds .Where(x => !existingSellers.Any(y => y.ExternalId == x)) .Select(x => auctions.Select(y => y.Seller).First(y => y.Provider.Value == x)) .ToList(); var newResults = new List <SearchResult>(); foreach (var auction in auctions) { var existingAuction = existingAuctions.SingleOrDefault(x => x.ExternalId == auction.Provider.Value); var hasDeletedDuplicate = deletedDuplicateCandidates.Any(x => x.Name == auction.Info.Name && x.ExternalSellerId == auction.Seller.Provider.Value); SearchResult?newResult = null; if (existingAuction == null) { var existingCategory = existingCategories.SingleOrDefault(x => x.ExternalId == auction.Category.Provider.Value); var newCategory = newCategories.SingleOrDefault(x => x.Provider.Value == auction.Category.Provider.Value); var existingSeller = existingSellers.SingleOrDefault(x => x.ExternalId == auction.Seller.Provider.Value); var newSeller = newSellers.SingleOrDefault(x => x.Provider.Value == auction.Seller.Provider.Value); newResult = new SearchResult { Auction = auction with { Category = newCategory ?? null !, CategoryId = existingCategory?.Id ?? Guid.Empty, Seller = newSeller ?? null !, SellerId = existingSeller?.Id ?? Guid.Empty, } }; } else if (existingAuction.Result == null) { newResult = new SearchResult { AuctionId = existingAuction.Id }; } if (newResult != null) { if (entity.Settings.AutoFilterDeletedDuplicates && hasDeletedDuplicate) { newResult.Delete(); } else { newResults.Add(newResult); } entity.Results.Add(newResult); } } entity.Release(true); await context.SaveChangesAsync(); if (newResults.Any()) { await this.notifier.NotifyAboutNewResultsAsync(id, newResults.Select(x => x.Id)); } }