Esempio n. 1
0
        public async Task DownloadPackage(PackageWrapper packageWrapper)
        {
            //this will prevent install to look in all repos
            _sourceRepos = new List <SourceRepository>();
            _sourceRepos.Add(packageWrapper.sourceRepository);

            PackageIdentity packageIdentity = packageWrapper.rootPackageIdentity;
            List <Lazy <INuGetResourceProvider> > providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(Repository.Provider.GetCoreV3());  // Add v3 API s

            var rootPath = NugetHelper.Instance.GetNugetSettings().NugetFolder;
            var settings = Settings.LoadDefaultSettings(rootPath, null, new MachineWideSettings());
            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);
            var project        = new NuGet.ProjectManagement.FolderNuGetProject(rootPath);
            var packageManager = new NuGet.PackageManagement.NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
            {
                PackagesFolderNuGetProject = project
            };

            var allowPrereleaseVersions = true;
            var allowUnlisted           = false;

            NuGet.ProjectManagement.INuGetProjectContext projectContext = new ProjectContext();

            NuGet.PackageManagement.ResolutionContext resolutionContext =
                new NuGet.PackageManagement.ResolutionContext(
                    NuGet.Resolver.DependencyBehavior.Lowest,
                    allowPrereleaseVersions,
                    allowUnlisted,
                    NuGet.PackageManagement.VersionConstraints.None);


            if (NugetHelper.Instance.GetNugetSettings().DisableCache)
            {
                resolutionContext.SourceCacheContext.NoCache        = true;
                resolutionContext.SourceCacheContext.DirectDownload = true;
            }

            var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext,
                                                             rootPath, resolutionContext.SourceCacheContext.DirectDownload);

            bool packageAlreadyExists = packageManager.PackageExistsInPackagesFolder(packageIdentity,
                                                                                     NuGet.Packaging.PackageSaveMode.None);

            if (!packageAlreadyExists)
            {
                await packageManager.InstallPackageAsync(
                    project,
                    packageIdentity,
                    resolutionContext,
                    projectContext,
                    downloadContext,
                    _sourceRepos,
                    new List <SourceRepository>(),
                    CancellationToken.None);

                var packageDeps = packageManager.GetInstalledPackagesDependencyInfo(project, CancellationToken.None, true);
                _logger.LogInformation($"Package {packageIdentity.Id} is got Installed at  | {project.GetInstalledPath(packageIdentity)} ");
            }
            else
            {
                _logger.LogInformation($"Package {packageIdentity.Id} is Already Installed at  | {project.GetInstalledPath(packageIdentity)} " +
                                       $" | skipping instalation !!");
            }



            #region GetDll paths


            var dllstoAdd = NugetHelper.Instance.GetInstallPackagesDllPath(packageWrapper, ref project);
            if (dllstoAdd.Count > 0)
            {
                downloadedDllPaths.AddRange(dllstoAdd);
            }


            ////now iterate for child identities , but as we have alreayd written login for recursive install , check if this
            //is now really required or not ?

            //if (packageWrapper.childPackageIdentities != null && packageWrapper.childPackageIdentities.Count > 0)
            //{
            //    foreach (var childPackageIdentity in packageWrapper.childPackageIdentities)
            //    {

            //        var _dllstoAdd = NugetHelper.Instance.GetInstallPackagesDllPath(packageWrapper., ref project);
            //        if (_dllstoAdd.Count > 0)
            //        {
            //            downloadedDllPaths.AddRange(_dllstoAdd);
            //        }

            //    }
            //}



            #endregion


            _logger.LogInformation($"done for package {packageIdentity.Id} , with total Dlls {downloadedDllPaths.Count}");
        }
        public PackageWrapper GetPackageByExactSearch(string packageName, string version)
        {
            bool           packageFound   = false;
            PackageWrapper packageWrapper = null;

            #region processing
            foreach (var sourceRepository in _sourceRepos)
            {
                if (!packageFound)
                {
                    // _logger.LogInformation("###################################################################");
                    //_logger.LogInformation($"Looking in Repo {sourceRepository.PackageSource.Source} for package : {packageName}");

                    //extact search
                    PackageMetadataResource packageMetadataResource = sourceRepository
                                                                      .GetResourceAsync <PackageMetadataResource>().Result;

                    SourceCacheContext sourceCacheContext = new SourceCacheContext();

                    ////below will slow down search as it is disabling search
                    if (NugetHelper.Instance.GetNugetSettings().DisableCache)
                    {
                        sourceCacheContext.NoCache        = true;
                        sourceCacheContext.DirectDownload = true;
                    }

                    IPackageSearchMetadata rootPackage = null;

                    //if user has mentioned version , then search specifcially for that version only , else get latest version
                    if (!string.IsNullOrWhiteSpace(version))
                    {
                        rootPackage = GetPackageFromRepoWithVersion(packageName, version,
                                                                    packageMetadataResource, sourceCacheContext, sourceRepository);
                    }
                    else
                    {
                        rootPackage = GetPackageFromRepoWithoutVersion(packageName,
                                                                       packageMetadataResource, sourceCacheContext, sourceRepository);
                    }

                    if (rootPackage == null)
                    {
                        _logger.LogInformation($" No Package found in Repo " +
                                               $"{sourceRepository.PackageSource.Source} for package : {packageName} | {version}");

                        //as we have not found package , there is no need to process further ,look for next repo by continue
                        continue;
                    }
                    else
                    {
                        packageWrapper = new PackageWrapper();
                        packageWrapper.rootPackageIdentity = rootPackage.Identity;
                        packageWrapper.packageName         = packageWrapper.rootPackageIdentity.Id;

                        packageWrapper.version = packageWrapper.rootPackageIdentity.Version;
                        //save the repo infor as well so that during install it doesnt need to search on all repos
                        packageWrapper.sourceRepository = sourceRepository;

                        //load child package identities
                        packageWrapper.childPackageIdentities = NugetHelper.Instance.GetChildPackageIdentities(rootPackage);

                        _logger.LogInformation($"Latest Package form Exact Search : {packageWrapper.packageName }" +
                                               $"| {packageWrapper.version } in Repo {sourceRepository.PackageSource.Source}");
                    }

                    packageFound = true;
                    //as package is found , we can break loop here for this package, but keeping above bool as well for testing

                    _logger.LogInformation("---------------------------------------------------------------------");
                    break;
                }
            }

            #endregion

            return(packageWrapper);
        }
        /// <summary>
        /// Obsolute : Find app matching package with that keyword , but implemented C# code  is not same as GetPackageByExact
        /// If you want to use it  , then change internal implementation as well
        /// </summary>
        /// <returns></returns>
        ///
        public PackageWrapper GetPackageByFullSearch(string packageName, string version)
        {
            bool           packageFound   = false;
            PackageWrapper packageWrapper = null;

            #region processing
            _logger.LogInformation($"Target frameworkName : {_targetFramwork}");


            //create search criteria
            SearchFilter filter = new SearchFilter(true, SearchFilterType.IsLatestVersion);
            filter.SupportedFrameworks = new List <string>()
            {
                _targetFramwork
            };


            foreach (var sourceRepository in _sourceRepos)
            {
                if (!packageFound)
                {
                    // _logger.LogInformation("###################################################################");
                    //_logger.LogInformation($"Looking in Repo {sourceRepository.PackageSource.Source} for package : {packageName}");

                    //create package source resource - Full Search  - all matching keywords
                    PackageSearchResource searchResource = sourceRepository.
                                                           GetResourceAsync <PackageSearchResource>().Result;
                    IEnumerable <IPackageSearchMetadata> FullsearchResults = searchResource
                                                                             .SearchAsync(packageName, filter, 0, 20, _logger, CancellationToken.None).Result;

                    if (FullsearchResults.Count() == 0 ||
                        !(FullsearchResults.Any(x => x.Identity.Id.ToLower() == packageName.ToLower())))
                    {
                        _logger.LogInformation($"Full Search - No Package found in Repo {sourceRepository.PackageSource.Source} for package : {packageName}");
                    }
                    else
                    {
                        //only list relavant package
                        FullsearchResults = FullsearchResults.Where(x => x.Identity.Id.ToLower() == packageName.ToLower());

                        packageFound = true;
                        //got list of matching package , iterate throug it
                        //foreach (var pgkdata in FullsearchResults)
                        //{
                        //    _logger.LogInformation($"Full search Package Located: {pgkdata.Title} | { pgkdata.Identity.Version}");
                        //    //identity = pgkdata.Identity;
                        //}

                        //initilize wrapper
                        packageWrapper = new PackageWrapper();
                        IPackageSearchMetadata rootPackage;
                        //if version number is present , select that specific package , else select latest
                        if (!string.IsNullOrWhiteSpace(version))
                        {
                            //not checking against Identity.Version & Identity.Version.Version is diffrent
                            //Identity.Version.Version is more accurate but may result in diffrent packages
                            rootPackage = FullsearchResults.Where(x => x.Identity.HasVersion &&
                                                                  x.Identity.Version.Version.ToString() == version).LastOrDefault();

                            //it is possible that no matching version found , then fallback to latest
                            if (rootPackage == null)
                            {
                                rootPackage = FullsearchResults.OrderByDescending(x => x.Identity.Version)
                                              .FirstOrDefault();
                            }
                        }
                        else //select latest version
                        {
                            rootPackage = FullsearchResults.OrderByDescending(x => x.Identity.Version)
                                          .FirstOrDefault();
                        }
                        packageWrapper.rootPackageIdentity = rootPackage.Identity;

                        packageWrapper.packageName = packageWrapper.rootPackageIdentity.Id;

                        packageWrapper.version = packageWrapper.rootPackageIdentity.Version;
                        //save the repo infor as well so that during install it doesnt need to search on all repos
                        packageWrapper.sourceRepository = sourceRepository;

                        //load child package identities
                        packageWrapper.childPackageIdentities = NugetHelper.Instance.GetChildPackageIdentities(rootPackage);

                        _logger.LogInformation($"Exact Package form Full Search : " +
                                               $"{packageWrapper.packageName }| {packageWrapper.version }");
                    }
                }
            }

            #endregion

            return(packageWrapper);
        }
Esempio n. 4
0
        public List <DllInfo> GetInstallPackagesDllPath(PackageWrapper packageWrapper, ref FolderNuGetProject project)
        {
            List <DllInfo> dllinfo = new List <DllInfo>();

            var packageIdentity = packageWrapper.rootPackageIdentity;
            var packageFilePath = project.GetInstalledPackageFilePath(packageIdentity);

            if (!string.IsNullOrWhiteSpace(packageFilePath))
            {
                _logger.LogInformation(packageFilePath);


                var archiveReader  = new NuGet.Packaging.PackageArchiveReader(packageFilePath, null, null);
                var nugetFramwork  = NuGetFramework.ParseFrameworkName(NugetHelper.Instance.GetTargetFramwork(), new DefaultFrameworkNameProvider());
                var referenceGroup = NugetHelper.Instance.GetMostCompatibleGroup(nugetFramwork, archiveReader.GetReferenceItems());
                if (referenceGroup != null)
                {
                    foreach (var group in referenceGroup.Items)
                    {
                        var    installedPackagedFolder = project.GetInstalledPath(packageIdentity);
                        string installedDllPath        = string.Empty;
                        if (NugetHelper.Instance.GetNugetSettings().RunningOnwindows)
                        {
                            installedDllPath = Path.Combine(installedPackagedFolder, group.Replace("/", "\\"));
                        }
                        else
                        {
                            installedDllPath = Path.Combine(installedPackagedFolder, group);
                        }


                        var installedDllFolder = Path.GetDirectoryName(installedDllPath);
                        var dllName            = Path.GetFileName(installedDllPath);
                        var extension          = Path.GetExtension(installedDllPath).ToLower();
                        var processor          = group.GetProcessor();

                        _logger.LogInformation($"dll Path: {installedDllPath}");

                        //check if file path exist , then only add
                        if (File.Exists(installedDllPath) && extension == ".dll")
                        {
                            dllinfo.Add(
                                new DllInfo()
                            {
                                name        = dllName,
                                path        = installedDllPath,
                                framework   = referenceGroup.TargetFramework.DotNetFrameworkName,
                                processor   = processor,
                                rootPackage = packageIdentity.Id
                            }
                                );
                        }

                        //also , try to cross refer this with expected folder name to avoid version mismatch
                    }
                }
            }


            return(dllinfo);
        }