Microsoft.PackageManagement.NuGetProvider.NuGetRequest.SearchForPackages C# (CSharp) Method

SearchForPackages() private method

Search the entire repository for the packages
private SearchForPackages ( PackageSource source, string name ) : IEnumerable
source PackageSource Package Source
name string Package name
return IEnumerable
        private IEnumerable<PackageItem> SearchForPackages(PackageSource source, string name)
        {
            try
            {
                Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "SearchForPackages", name);

                // no repository found then returns nothing
                if (source.Repository == null)
                {
                    return Enumerable.Empty<PackageItem>();
                }

                var isNameContainsWildCard = false;
                var searchTerm = Contains.Value ?? string.Empty;

                // Deal with two cases here:
                // 1. The package name contains wildcards like "Find-Package -name JQ*". We search based on the name.
                // 2. A user does not provide the Name parameter,

                // A user provides name with wildcards. We will use name as the SearchTerm while Contains and Tag will be used
                // for filtering on the results.
                if (!String.IsNullOrWhiteSpace(name) && WildcardPattern.ContainsWildcardCharacters(name))
                {
                    isNameContainsWildCard = true;

                    // NuGet does not support PowerShell/POSIX style wildcards and supports only '*' in searchTerm
                    // Replace the range from '[' - to ']' with * and ? with * then wildcard pattern is applied on the results
                    var tempName = name;
                    var squareBracketPattern = Regex.Escape("[") + "(.*?)]";
                    foreach (Match match in Regex.Matches(tempName, squareBracketPattern)) {
                        tempName = tempName.Replace(match.Value, "*");
                    }

                    //As the nuget does not support wildcard, we remove '?', '*' wildcards from the search string, and then
                    //looking for the longest string in the given string as a keyword for the searching in the repository.
                    //A sample case will be something like find-package sql*Compact*.

                    //When the AllVersions property exists, the query like the following containing the wildcards does not work. We need to remove the wild cards and
                    //replace it with the longest string searhc.
                    //http://www.powershellgallery.com/api/v2/Search()?$orderby=DownloadCount%20desc,Id&searchTerm='tsdprovi*'&targetFramework=''&includePrerelease=false

                    if ((!String.IsNullOrWhiteSpace(name) && source.Location.IndexOf("powershellgallery.com", StringComparison.OrdinalIgnoreCase) == -1)
                        || (AllVersions.Value))
                    {
                        //get rid of wildcard and search the longest string in the given name for nuget.org
                        tempName = tempName.Split('?', '*').OrderBy(namePart => namePart.Length).Last();
                    }

                    //Deal with a case when a user type Find-Package *
                    if (String.Equals(tempName, "*", StringComparison.OrdinalIgnoreCase)) {
                        //We use '' instead of "*" because searchterm='*' does not return the entire repository.
                        tempName = string.Empty;
                    }

                    searchTerm = tempName;
                }

                // Add the Tags for the search.
                if (FilterOnTag != null)
                {
                    // E.g. searchTerm = "tag:dscresource_xFirefox tag:command_Start-Process"
                    searchTerm = FilterOnTag.Value.Where(tag => !string.IsNullOrWhiteSpace(tag)).Aggregate(searchTerm, (current, tag) => current + " tag:" + tag);
                }

                Verbose(Resources.Messages.SearchingRepository, source.Repository.Source, searchTerm);

                // Handling case where a user does not provide Name parameter
                var pkgs = source.Repository.Search(searchTerm, this);

                if (!String.IsNullOrWhiteSpace(name))
                {
                    //Filter on the results. This is needed because we replace [...] regex in the searchterm at the begining of this method.
                    pkgs = FilterOnName(pkgs, name, isNameContainsWildCard);
                }

                pkgs = FilterOnContains(pkgs);

                var pkgsItem = pkgs.Select(pkg => new PackageItem
                   {
                       Package = pkg,
                       PackageSource = source,
                       FastPath = MakeFastPath(source, pkg.Id, pkg.Version.ToString())
                   });

                return pkgsItem;
            }
            catch (Exception e)
            {
                e.Dump(this);
                Warning(e.Message);
                return Enumerable.Empty<PackageItem>();
            }
        }

Same methods

NuGetRequest::SearchForPackages ( string name ) : IEnumerable

Usage Example

Example #1
0
        /// <summary>
        /// Searches package sources given name and version information
        ///
        /// Package information must be returned using <c>request.YieldPackage(...)</c> function.
        /// </summary>
        /// <param name="name">a name or partial name of the package(s) requested</param>
        /// <param name="requiredVersion">A specific version of the package. Null or empty if the user did not specify</param>
        /// <param name="minimumVersion">A minimum version of the package. Null or empty if the user did not specify</param>
        /// <param name="maximumVersion">A maximum version of the package. Null or empty if the user did not specify</param>
        /// <param name="id">if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>, the core is calling this multiple times to do a batch search request. The operation can be delayed until <c>CompleteFind(...)</c> is called</param>
        /// <param name="request">An object passed in from the PackageManagement that contains functions that can be used to interact with its Provider</param> 
        public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, NuGetRequest request)
        {
            if (request == null){
                throw new ArgumentNullException("request");
            }

            // true if we want to include the max and min version
            bool minInclusive = true;
            bool maxInclusive = true;

            // If finding by canonical id, then the version follows dependency version requirement
            if (request.GetOptionValue("FindByCanonicalId").IsTrue())
            {
                // Use the dependency version if no min and max is supplied
                if (String.IsNullOrWhiteSpace(maximumVersion) && String.IsNullOrWhiteSpace(minimumVersion))
                {
                    DependencyVersion depVers = DependencyVersion.ParseDependencyVersion(requiredVersion);
                    maximumVersion = depVers.MaxVersion.ToStringSafe();
                    minimumVersion = depVers.MinVersion.ToStringSafe();
                    minInclusive = depVers.IsMinInclusive;
                    maxInclusive = depVers.IsMaxInclusive;

                    // set required version if we have both min max as the same value.
                    if (depVers.MaxVersion != null && depVers.MinVersion != null
                        && depVers.MaxVersion == depVers.MinVersion && minInclusive && maxInclusive)
                    {
                        requiredVersion = maximumVersion;
                    }
                    else
                    {
                        requiredVersion = null;
                    }
                }                
            }

            request.Debug(Resources.Messages.DebugInfoCallMethod, PackageProviderName, string.Format(CultureInfo.InvariantCulture, "FindPackage' - name='{0}', requiredVersion='{1}',minimumVersion='{2}', maximumVersion='{3}'", name, requiredVersion, minimumVersion, maximumVersion));

            NormalizeVersion(request, ref requiredVersion, ref minimumVersion, ref maximumVersion);

            try {

            
            // If there are any packages, yield and return
            if (request.YieldPackages(request.GetPackageById(name, request, requiredVersion, minimumVersion, maximumVersion, minInclusive, maxInclusive), name))
            {
                return;
            }

            // Check if the name contains wildcards. If not, return. This matches the behavior as "Get-module xje" 
            if (!String.IsNullOrWhiteSpace(name) && !WildcardPattern.ContainsWildcardCharacters(name))
            {              
                return;
            }

            // In the case of the package name is null or contains wildcards, error out if a user puts version info
            if (!String.IsNullOrWhiteSpace(requiredVersion) || !String.IsNullOrWhiteSpace(minimumVersion) || !String.IsNullOrWhiteSpace(maximumVersion))
            {
                request.Warning( Constants.Messages.MissingRequiredParameter, "name");
                return;
            }
            
            
       
            // Have we been cancelled?
            if (request.IsCanceled) {
                request.Debug(Resources.Messages.RequestCanceled, PackageProviderName, "FindPackage");

                return;
            }

            // A user does not provide the package full Name at all Or used wildcard in the name. Let's try searching the entire repository for matches.
            request.YieldPackages(request.SearchForPackages(name), name);
            }
            catch (Exception ex)
            {
                ex.Dump(request);
            }
        }
All Usage Examples Of Microsoft.PackageManagement.NuGetProvider.NuGetRequest::SearchForPackages