Esempio n. 1
0
        /// <summary>
        /// Adds refresh files to the specified project for all assemblies references belonging to the packages
        /// specified by packageNames.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="repositoryPath">The file system pointing to 'packages' folder under the solution.</param>
        /// <param name="packageNames">The package names.</param>
        private void AddRefreshFilesForReferences(EnvDTE.Project project, string repositoryPath, IEnumerable <PackageIdentity> packageNames)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (repositoryPath == null)
            {
                throw new ArgumentNullException("repositoryPath");
            }

            if (!packageNames.Any())
            {
                return;
            }

            VSAPIProjectContext context = new VSAPIProjectContext(skipAssemblyReferences: true, bindingRedirectsDisabled: true);
            var signedPackageVerifier   = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());

            context.PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                new LoggerAdapter(context),
                signedPackageVerifier,
                SignedPackageVerifierSettings.GetDefault());

            WebSiteProjectSystem projectSystem = new WebSiteProjectSystem(_vsProjectAdapterProvider.CreateAdapterForFullyLoadedProject(project), context);

            foreach (var packageName in packageNames)
            {
                string packagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", packageName.Id, packageName.Version);

                DirectoryInfo packageFolder = new DirectoryInfo(Path.Combine(repositoryPath, packagePath));

                PackageFolderReader reader = new PackageFolderReader(packageFolder);

                var frameworkGroups = reader.GetReferenceItems();

                var groups = reader.GetReferenceItems();

                var fwComparer           = new NuGetFrameworkFullComparer();
                FrameworkReducer reducer = new FrameworkReducer();
                NuGetFramework   targetGroupFramework = reducer.GetNearest(projectSystem.TargetFramework, groups.Select(e => e.TargetFramework));

                if (targetGroupFramework != null)
                {
                    var refGroup = groups.Where(e => fwComparer.Equals(targetGroupFramework, e.TargetFramework)).FirstOrDefault();

                    foreach (string refItem in refGroup.Items)
                    {
                        string sourcePath = Path.Combine(packageFolder.FullName, refItem.Replace('/', Path.DirectorySeparatorChar));

                        // create one refresh file for each assembly reference, as per required by Website projects
                        // projectSystem.CreateRefreshFile(assemblyPath);
                        RefreshFileUtility.CreateRefreshFile(projectSystem, sourcePath);
                    }
                }
            }
        }
Esempio n. 2
0
        public IEnumerable <string> GetCompatibleAssemblyPaths()
        {
            List <string>              assemblyPaths     = new List <string>();
            FrameworkReducer           reducer           = new FrameworkReducer();
            NuGetFramework             targetFramework   = new NuGetFramework(".NETFramework", Version.Parse("4.5")); // If alternate versions of Wyam are developed (I.e., for DNX), this will need to be switched
            NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer();
            IPackageRepository         packageRepository = PackageRepositoryFactory.Default.CreateRepository(Path);
            PackageManager             packageManager    = new PackageManager(packageRepository, Path);

            foreach (IPackage package in packageManager.LocalRepository.GetPackages())
            {
                List <KeyValuePair <IPackageFile, NuGetFramework> > filesAndFrameworks = package.GetLibFiles()
                                                                                         .Select(x => new KeyValuePair <IPackageFile, NuGetFramework>(x,
                                                                                                                                                      new NuGetFramework(x.TargetFramework.Identifier, x.TargetFramework.Version, x.TargetFramework.Profile)))
                                                                                         .ToList();
                NuGetFramework targetPackageFramework = reducer.GetNearest(targetFramework, filesAndFrameworks.Select(x => x.Value));
                if (targetPackageFramework != null)
                {
                    assemblyPaths.AddRange(filesAndFrameworks
                                           .Where(x => frameworkComparer.Equals(targetPackageFramework, x.Value))
                                           .Select(x => System.IO.Path.Combine(Path, String.Format(CultureInfo.InvariantCulture, "{0}.{1}", package.Id, package.Version), x.Key.Path))
                                           .Where(x => System.IO.Path.GetExtension(x) == ".dll"));
                }
            }
            return(assemblyPaths);
        }
Esempio n. 3
0
        public async Task <IEnumerable <PackageDependency> > GetDependencies(string package, List <Uri> sources, NuGetVersion referencedVersion, NuGetFramework targetFramework)
        {
            var allDependencies = new List <PackageDependency>();

            foreach (var source in sources)
            {
                var findPackageById = await FindResourceForSource(source);

                var dependencyInfo = await findPackageById.GetDependencyInfoAsync(package, referencedVersion, _context, _logger, CancellationToken.None);

                var reducer  = new FrameworkReducer();
                var comparer = new NuGetFrameworkFullComparer();

                if (dependencyInfo != null)
                {
                    var nearestFramework = reducer.GetNearest(targetFramework, dependencyInfo.DependencyGroups.Select(x => x.TargetFramework));

                    foreach (var dependencyGroup in dependencyInfo.DependencyGroups.Where(d => comparer.Equals(nearestFramework, d.TargetFramework)))
                    {
                        foreach (var groupPackage in dependencyGroup.Packages)
                        {
                            allDependencies.Add(groupPackage);
                        }
                    }
                }
            }

            return(allDependencies);
        }
Esempio n. 4
0
 /// <summary>
 /// Creates a FrameworkReducer using custom framework mappings.
 /// </summary>
 public FrameworkReducer(IFrameworkNameProvider mappings, IFrameworkCompatibilityProvider compat)
 {
     _mappings = mappings;
     _compat = compat;
     _fullComparer = new NuGetFrameworkFullComparer();
     _fwNameComparer = new NuGetFrameworkNameComparer();
 }
Esempio n. 5
0
 public IEnumerable<string> GetCompatibleAssemblyPaths()
 {
     List<string> assemblyPaths = new List<string>();
     FrameworkReducer reducer = new FrameworkReducer();
     NuGetFramework targetFramework = new NuGetFramework(".NETFramework", Version.Parse("4.5"));  // If alternate versions of Wyam are developed (I.e., for DNX), this will need to be switched
     NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer();
     IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(Path);
     PackageManager packageManager = new PackageManager(packageRepository, Path);
     foreach (IPackage package in packageManager.LocalRepository.GetPackages())
     {
         List<KeyValuePair<IPackageFile, NuGetFramework>> filesAndFrameworks = package.GetLibFiles()
             .Select(x => new KeyValuePair<IPackageFile, NuGetFramework>(x,
                 new NuGetFramework(x.TargetFramework.Identifier, x.TargetFramework.Version, x.TargetFramework.Profile)))
             .ToList();
         NuGetFramework targetPackageFramework = reducer.GetNearest(targetFramework, filesAndFrameworks.Select(x => x.Value));
         if (targetPackageFramework != null)
         {
             assemblyPaths.AddRange(filesAndFrameworks
                 .Where(x => frameworkComparer.Equals(targetPackageFramework, x.Value))
                 .Select(x => System.IO.Path.Combine(Path, String.Format(CultureInfo.InvariantCulture, "{0}.{1}", package.Id, package.Version), x.Key.Path))
                 .Where(x => System.IO.Path.GetExtension(x) == ".dll"));
         }
     }
     return assemblyPaths;
 }
        public void NuGetFrameworkFullComparer_WithAssetTargetFallback_Succeeds(string shortFrameworkName)
        {
            var nugetFramework      = NuGetFramework.Parse(shortFrameworkName);
            var assetTargetFallback = new AssetTargetFallbackFramework(nugetFramework, fallbackFrameworks: SampleFrameworkList);
            var comparer            = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(nugetFramework, assetTargetFallback));
        }
        public void NuGetFrameworkEquals_WithDualCompatibilityFramework_Succeeds(string shortFrameworkName, string rootFrameworkName, bool equals)
        {
            var nugetFramework    = NuGetFramework.Parse(shortFrameworkName);
            var extendedFramework = new DualCompatibilityFramework(NuGetFramework.Parse(rootFrameworkName), secondaryFramework: NuGetFramework.Parse(rootFrameworkName));
            var comparer          = new NuGetFrameworkFullComparer();

            comparer.Equals(nugetFramework, extendedFramework).Should().Be(equals);
            nugetFramework.Equals(extendedFramework).Should().Be(equals);
        }
Esempio n. 8
0
        private IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path, PackageReference package)
        {
            if (!_fileSystem.Exist(path))
            {
                return(new List <IFile>());
            }

            // Get current framework.
            var provider = DefaultFrameworkNameProvider.Instance;
            var current  = NuGetFramework.Parse(_environment.Runtime.BuiltFramework.FullName, provider);

            // Get all ref assemblies.
            var refAssemblies = _globber.GetFiles(path.FullPath + "/ref/**/*.dll");

            // Get all candidate files.
            var pathComparer = PathComparer.Default;
            var assemblies   = GetFiles(path, package, new[] { path.FullPath + "/**/*.dll" })
                               .Where(file => !"Cake.Core.dll".Equals(file.Path.GetFilename().FullPath, StringComparison.OrdinalIgnoreCase) &&
                                      IsCLRAssembly(file) &&
                                      !refAssemblies.Contains(file.Path, pathComparer))
                               .ToList();

            // Iterate all found files.
            var comparer = new NuGetFrameworkFullComparer();
            var mapping  = new Dictionary <NuGetFramework, List <FilePath> >(comparer);

            foreach (var assembly in assemblies)
            {
                // Get relative path.
                var relative  = path.GetRelativePath(assembly.Path);
                var framework = ParseFromDirectoryPath(current, relative.GetDirectory());
                if (!mapping.ContainsKey(framework))
                {
                    mapping.Add(framework, new List <FilePath>());
                }
                mapping[framework].Add(assembly.Path);
            }

            // Reduce found frameworks to the closest one.
            var reducer = new FrameworkReducer();
            var nearest = reducer.GetNearest(current, mapping.Keys);

            if (nearest == null || !mapping.ContainsKey(nearest))
            {
                return(new List <IFile>());
            }

            if (nearest == NuGetFramework.AnyFramework)
            {
                var framework = _environment.Runtime.BuiltFramework;
                _log.Warning("Could not find any assemblies compatible with {0} in NuGet package {1}. " +
                             "Falling back to using root folder of NuGet package.", framework.FullName, package.Package);
            }

            // Return the result.
            return(mapping[nearest].Select(p => _fileSystem.GetFile(p)).ToList());
        }
Esempio n. 9
0
        /// <summary>
        /// Retrieve a registration blob
        /// </summary>
        /// <returns>Returns Null if the package does not exist</returns>
        public static async Task <RegistrationInfo> GetRegistrationInfo(
            HttpSource httpClient,
            Uri registrationUri,
            string packageId,
            VersionRange range,
            SourceCacheContext cacheContext,
            NuGetFramework projectTargetFramework,
            ILogger log,
            CancellationToken token)
        {
            var frameworkComparer = new NuGetFrameworkFullComparer();
            var frameworkReducer  = new FrameworkReducer();
            var dependencies      = await GetDependencies(httpClient, registrationUri, packageId, range, cacheContext, log, token);

            var result           = new HashSet <RegistrationInfo>();
            var registrationInfo = new RegistrationInfo();

            registrationInfo.IncludePrerelease = true;
            foreach (var item in dependencies)
            {
                var packageInfo = new PackageInfo
                {
                    Listed         = item.Listed,
                    Version        = item.Identity.Version,
                    PackageContent = new Uri(item.ContentUri)
                };

                // only one target framework group will be used at install time, which means
                // we can filter down to that group now by using the project target framework
                var depFrameworks   = item.DependencyGroups.Select(e => e.TargetFramework);
                var targetFramework = frameworkReducer.GetNearest(projectTargetFramework, depFrameworks);

                // If no frameworks are compatible we just ignore them - Should this be an exception?
                if (targetFramework != null)
                {
                    var dependencyGroup = item.DependencyGroups.FirstOrDefault(d => frameworkComparer.Equals(targetFramework, d.TargetFramework));
                    if (dependencyGroup != null)
                    {
                        foreach (var dependency in dependencyGroup.Packages)
                        {
                            var dependencyInfo = new DependencyInfo
                            {
                                Id    = dependency.Id,
                                Range = dependency.VersionRange
                            };

                            packageInfo.Dependencies.Add(dependencyInfo);
                        }
                    }
                }

                registrationInfo.Add(packageInfo);
                registrationInfo.Id = item.Identity.Id;
            }

            return(registrationInfo);
        }
        public void FrameworkComparer_PCLNormalize()
        {
            var fw1 = NuGetFramework.Parse("portable-net45+win8+wp8+wpa81+monotouch+monoandroid");
            var fw2 = NuGetFramework.Parse("portable-net45+win8+wp8+wpa81");
            var fw3 = NuGetFramework.Parse(".NETPortable, Version=v0.0, Profile=Profile259");

            var comparer = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(fw1, fw2), "2");
            Assert.True(comparer.Equals(fw1, fw3), "3");
        }
Esempio n. 11
0
        /// <summary>
        /// Adds refresh files to the specified project for all assemblies references belonging to the packages specified by packageNames.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="packagesFileSystem">The file system pointing to 'packages' folder under the solution.</param>
        /// <param name="packageNames">The package names.</param>
        private void AddRefreshFilesForReferences(Project project, string repositoryPath, IEnumerable <PackageIdentity> packageNames)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (repositoryPath == null)
            {
                throw new ArgumentNullException("repositoryPath");
            }

            if (!packageNames.Any())
            {
                return;
            }

            VSAPIProjectContext  context       = new VSAPIProjectContext();
            WebSiteProjectSystem projectSystem = new WebSiteProjectSystem(project, context);

            var root = EnvDTEProjectUtility.GetFullPath(project);

            foreach (var packageName in packageNames)
            {
                string packagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", packageName.Id, packageName.Version);

                DirectoryInfo packageFolder = new DirectoryInfo(Path.Combine(repositoryPath, packagePath));

                PackageFolderReader reader = new PackageFolderReader(packageFolder);

                var frameworkGroups = reader.GetReferenceItems();

                var groups = reader.GetReferenceItems();

                var fwComparer           = new NuGetFrameworkFullComparer();
                FrameworkReducer reducer = new FrameworkReducer();
                NuGetFramework   targetGroupFramework = reducer.GetNearest(projectSystem.TargetFramework, groups.Select(e => e.TargetFramework));

                if (targetGroupFramework != null)
                {
                    var refGroup = groups.Where(e => fwComparer.Equals(targetGroupFramework, e.TargetFramework)).FirstOrDefault();

                    foreach (string refItem in refGroup.Items)
                    {
                        string sourcePath = Path.Combine(packageFolder.FullName, refItem.Replace('/', Path.DirectorySeparatorChar));

                        // create one refresh file for each assembly reference, as per required by Website projects
                        // projectSystem.CreateRefreshFile(assemblyPath);
                        RefreshFileUtility.CreateRefreshFile(projectSystem, sourcePath, context);
                    }
                }
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Get the nearest framework available in the project.
        /// </summary>
        public static TargetFrameworkInformation GetTargetFramework(this PackageSpec project, NuGetFramework targetFramework)
        {
            var frameworkInfo = project.TargetFrameworks.FirstOrDefault(f => NuGetFrameworkFullComparer.Equals(targetFramework, f));

            if (frameworkInfo == null)
            {
                frameworkInfo = NuGetFrameworkUtility.GetNearest(project.TargetFrameworks,
                                                                 targetFramework,
                                                                 item => item.FrameworkName);
            }

            return(frameworkInfo ?? new TargetFrameworkInformation());
        }
        public void FrameworkComparer_VersionNormalize()
        {
            var fw1 = NuGetFramework.Parse("net45");
            var fw2 = NuGetFramework.Parse("net4.5");
            var fw3 = NuGetFramework.Parse("net4.5.0");
            var fw4 = NuGetFramework.Parse("net450");
            var fw5 = NuGetFramework.Parse(".NETFramework45");

            var comparer = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(fw1, fw2));
            Assert.True(comparer.Equals(fw1, fw3));
            Assert.True(comparer.Equals(fw1, fw4));
            Assert.True(comparer.Equals(fw1, fw5));
        }
Esempio n. 14
0
        protected override IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path, PackageReference package)
        {
            if (!_fileSystem.Exist(path))
            {
                return(new List <IFile>());
            }

            // Get current framework.
            var provider = DefaultFrameworkNameProvider.Instance;
            var current  = NuGetFramework.Parse(_environment.Runtime.TargetFramework.FullName, provider);

            // Get all candidate files.
            var assemblies = GetFiles(path, package, new[] { path.FullPath + "/**/*.dll" })
                             .Where(file => !"Cake.Core.dll".Equals(file.Path.GetFilename().FullPath, StringComparison.OrdinalIgnoreCase) &&
                                    IsCLRAssembly(file))
                             .ToList();

            // Iterate all found files.
            var comparer = new NuGetFrameworkFullComparer();
            var mapping  = new Dictionary <NuGetFramework, List <FilePath> >(comparer);

            foreach (var assembly in assemblies)
            {
                // Get relative path.
                var relative  = path.GetRelativePath(assembly.Path);
                var framework = ParseFromDirectoryPath(current, relative.GetDirectory());
                if (!mapping.ContainsKey(framework))
                {
                    mapping.Add(framework, new List <FilePath>());
                }
                mapping[framework].Add(assembly.Path);
            }

            // Reduce found frameworks to the closest one.
            var reducer = new FrameworkReducer();
            var nearest = reducer.GetNearest(current, mapping.Keys);

            if (nearest == null || !mapping.ContainsKey(nearest))
            {
                return(new List <IFile>());
            }

            // Return the result.
            return(mapping[nearest].Select(p => _fileSystem.GetFile(p)).ToList());
        }
        public void AsFallbackFramework_WhenCalledMultipleTimes_CachesFallbackObjectReference()
        {
            var nugetFramework             = CommonFrameworks.Net50;
            var dualCompatibilityFramework = new DualCompatibilityFramework(nugetFramework, secondaryFramework: NuGetFramework.AnyFramework);

            FallbackFramework fallbackFramework = dualCompatibilityFramework.AsFallbackFramework();

            var comparer = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(fallbackFramework, nugetFramework));

            fallbackFramework.Fallback.Should().HaveCount(1);
            fallbackFramework.Fallback.Single().Should().Be(NuGetFramework.AnyFramework);

            FallbackFramework fallbackFramework2 = dualCompatibilityFramework.AsFallbackFramework();

            fallbackFramework.Should().BeSameAs(fallbackFramework2);
        }
Esempio n. 16
0
        protected override IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path)
        {
            if (!_fileSystem.Exist(path))
            {
                return(new List <IFile>());
            }

            // Get current framework.
            var provider = DefaultFrameworkNameProvider.Instance;
            var current  = NuGetFramework.Parse(_environment.Runtime.TargetFramework.FullName, provider);

            // Get all candidate files.
            var assemblies = _fileSystem.GetDirectory(path).GetFiles("*.dll", SearchScope.Recursive);

            // Iterate all found files.
            var comparer = new NuGetFrameworkFullComparer();
            var mapping  = new Dictionary <NuGetFramework, List <FilePath> >(comparer);

            foreach (var assembly in assemblies)
            {
                // Get relative path.
                var relative  = path.GetRelativePath(assembly.Path);
                var framework = ParseFromDirectoryPath(current, relative.GetDirectory());
                if (!mapping.ContainsKey(framework))
                {
                    mapping.Add(framework, new List <FilePath>());
                }
                mapping[framework].Add(assembly.Path);
            }

            // Reduce found frameworks to the closest one.
            var reducer = new FrameworkReducer();
            var nearest = reducer.GetNearest(current, mapping.Keys);

            if (nearest == null || !mapping.ContainsKey(nearest))
            {
                return(new List <IFile>());
            }

            // Return the result.
            return(mapping[nearest].Select(p => _fileSystem.GetFile(p)).ToList());
        }
Esempio n. 17
0
        public IEnumerable <FilePath> GetCompatibleAssemblyPaths()
        {
            List <FilePath>            assemblyPaths     = new List <FilePath>();
            FrameworkReducer           reducer           = new FrameworkReducer();
            NuGetFramework             targetFramework   = new NuGetFramework(".NETFramework", Version.Parse("4.6")); // TODO: If alternate versions of Wyam are developed (I.e., for DNX), this will need to be switched
            NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer();
            IPackageRepository         packageRepository = PackageRepositoryFactory.Default.CreateRepository(AbsolutePackagesPath.FullPath);
            PackageManager             packageManager    = new PackageManager(packageRepository, AbsolutePackagesPath.FullPath);

            foreach (IPackage package in packageManager.LocalRepository.GetPackages())
            {
                List <KeyValuePair <IPackageFile, NuGetFramework> > filesAndFrameworks = package.GetLibFiles()
                                                                                         .Where(x => x.TargetFramework != null)
                                                                                         .Select(x => new KeyValuePair <IPackageFile, NuGetFramework>(x,
                                                                                                                                                      new NuGetFramework(x.TargetFramework.Identifier, x.TargetFramework.Version, x.TargetFramework.Profile)))
                                                                                         .ToList();
                NuGetFramework targetPackageFramework = reducer.GetNearest(targetFramework, filesAndFrameworks.Select(x => x.Value));
                if (targetPackageFramework != null)
                {
                    List <FilePath> packageAssemblyPaths = filesAndFrameworks
                                                           .Where(x => frameworkComparer.Equals(targetPackageFramework, x.Value))
                                                           .Select(x => AbsolutePackagesPath.Combine(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", package.Id, package.Version)).CombineFile(x.Key.Path))
                                                           .Where(x => x.Extension == ".dll")
                                                           .ToList();
                    foreach (FilePath packageAssemblyPath in packageAssemblyPaths)
                    {
                        Trace.Verbose("Added assembly file {0} from package {1}.{2}", packageAssemblyPath.ToString(), package.Id, package.Version);
                    }
                    assemblyPaths.AddRange(packageAssemblyPaths);
                }
                else
                {
                    Trace.Verbose("Could not find compatible framework for package {0}.{1} (this is normal for content-only packages)", package.Id, package.Version);
                }
            }
            return(assemblyPaths);
        }
        public static async Task <RegistrationInfo> GetRegistrationInfo(HttpClient httpClient, Uri registrationUri, VersionRange range, NuGetFramework projectTargetFramework, ConcurrentDictionary <Uri, JObject> sessionCache = null)
        {
            NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer();
            FrameworkReducer           frameworkReducer  = new FrameworkReducer();
            JObject index = await LoadResource(httpClient, registrationUri, sessionCache);

            if (index == null)
            {
                throw new ArgumentException(registrationUri.AbsoluteUri);
            }

            VersionRange preFilterRange = Utils.SetIncludePrerelease(range, true);

            IList <Task <JObject> > rangeTasks = new List <Task <JObject> >();

            foreach (JObject item in index["items"])
            {
                NuGetVersion lower = NuGetVersion.Parse(item["lower"].ToString());
                NuGetVersion upper = NuGetVersion.Parse(item["upper"].ToString());

                if (ResolverMetadataClientUtility.IsItemRangeRequired(preFilterRange, lower, upper))
                {
                    JToken items;
                    if (!item.TryGetValue("items", out items))
                    {
                        Uri rangeUri = item["@id"].ToObject <Uri>();

                        rangeTasks.Add(LoadResource(httpClient, rangeUri, sessionCache));
                    }
                    else
                    {
                        rangeTasks.Add(Task.FromResult(item));
                    }
                }
            }

            await Task.WhenAll(rangeTasks.ToArray());

            RegistrationInfo registrationInfo = new RegistrationInfo();

            registrationInfo.IncludePrerelease = range.IncludePrerelease;

            string id = string.Empty;

            foreach (JObject rangeObj in rangeTasks.Select((t) => t.Result))
            {
                if (rangeObj == null)
                {
                    throw new InvalidDataException(registrationUri.AbsoluteUri);
                }

                foreach (JObject packageObj in rangeObj["items"])
                {
                    JObject catalogEntry = (JObject)packageObj["catalogEntry"];

                    NuGetVersion packageVersion = NuGetVersion.Parse(catalogEntry["version"].ToString());

                    id = catalogEntry["id"].ToString();

                    int    publishedDate = 0;
                    JToken publishedValue;

                    if (catalogEntry.TryGetValue("published", out publishedValue))
                    {
                        publishedDate = int.Parse(publishedValue.ToObject <DateTime>().ToString("yyyyMMdd"));
                    }

                    //publishedDate = 0 means the property doesn't exist in index.json
                    //publishedDate = 19000101 means the property exists but the package is unlisted
                    if (range.Satisfies(packageVersion) && (publishedDate != 19000101))
                    {
                        PackageInfo packageInfo = new PackageInfo();
                        packageInfo.Version        = packageVersion;
                        packageInfo.PackageContent = new Uri(packageObj["packageContent"].ToString());

                        JArray dependencyGroupsArray = (JArray)catalogEntry["dependencyGroups"];

                        if (dependencyGroupsArray != null)
                        {
                            // only one target framework group will be used at install time, which means
                            // we can filter down to that group now by using the project target framework
                            var depFrameworks = dependencyGroupsArray.Select(e => GetFramework(e as JObject));

                            var targetFramework = frameworkReducer.GetNearest(projectTargetFramework, depFrameworks);

                            // If no frameworks are compatible we just ignore them - Should this be an exception?
                            if (targetFramework != null)
                            {
                                foreach (JObject dependencyGroupObj in dependencyGroupsArray)
                                {
                                    NuGetFramework currentFramework = GetFramework(dependencyGroupObj);

                                    if (frameworkComparer.Equals(currentFramework, targetFramework))
                                    {
                                        foreach (JObject dependencyObj in dependencyGroupObj["dependencies"])
                                        {
                                            DependencyInfo dependencyInfo = new DependencyInfo();
                                            dependencyInfo.Id              = dependencyObj["id"].ToString();
                                            dependencyInfo.Range           = Utils.CreateVersionRange((string)dependencyObj["range"], range.IncludePrerelease);
                                            dependencyInfo.RegistrationUri = dependencyObj["registration"].ToObject <Uri>();

                                            packageInfo.Dependencies.Add(dependencyInfo);
                                        }
                                    }
                                }
                            }
                        }

                        registrationInfo.Add(packageInfo);
                    }
                }

                registrationInfo.Id = id;
            }

            return(registrationInfo);
        }
Esempio n. 19
0
        public void FrameworkComparer_VersionNormalize()
        {
            var fw1 = NuGetFramework.Parse("net45");
            var fw2 = NuGetFramework.Parse("net4.5");
            var fw3 = NuGetFramework.Parse("net4.5.0");
            var fw4 = NuGetFramework.Parse("net450");
            var fw5 = NuGetFramework.Parse(".NETFramework45");

            var comparer = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(fw1, fw2));
            Assert.True(comparer.Equals(fw1, fw3));
            Assert.True(comparer.Equals(fw1, fw4));
            Assert.True(comparer.Equals(fw1, fw5));
        }
Esempio n. 20
0
        public void FrameworkComparer_PCLNormalize()
        {
            var fw1 = NuGetFramework.Parse("portable-net45+win8+wp8+wpa81+monotouch+monoandroid");
            var fw2 = NuGetFramework.Parse("portable-net45+win8+wp8+wpa81");
            var fw3 = NuGetFramework.Parse(".NETPortable, Version=v0.0, Profile=Profile259");

            var comparer = new NuGetFrameworkFullComparer();

            Assert.True(comparer.Equals(fw1, fw2), "2");
            Assert.True(comparer.Equals(fw1, fw3), "3");
        }
        public static async Task<RegistrationInfo> GetRegistrationInfo(HttpClient httpClient, Uri registrationUri, VersionRange range, NuGetFramework projectTargetFramework, ConcurrentDictionary<Uri, JObject> sessionCache = null)
        {
            NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer();
            FrameworkReducer frameworkReducer = new FrameworkReducer();
            JObject index = await LoadResource(httpClient, registrationUri, sessionCache);

            if (index == null)
            {
                throw new ArgumentException(registrationUri.AbsoluteUri);
            }

            VersionRange preFilterRange = Utils.SetIncludePrerelease(range, true);

            IList<Task<JObject>> rangeTasks = new List<Task<JObject>>();

            foreach (JObject item in index["items"])
            {
                NuGetVersion lower = NuGetVersion.Parse(item["lower"].ToString());
                NuGetVersion upper = NuGetVersion.Parse(item["upper"].ToString());

                if (ResolverMetadataClientUtility.IsItemRangeRequired(preFilterRange, lower, upper))
                {
                    JToken items;
                    if (!item.TryGetValue("items", out items))
                    {
                        Uri rangeUri = item["@id"].ToObject<Uri>();

                        rangeTasks.Add(LoadResource(httpClient, rangeUri, sessionCache));
                    }
                    else
                    {
                        rangeTasks.Add(Task.FromResult(item));
                    }
                }
            }

            await Task.WhenAll(rangeTasks.ToArray());

            RegistrationInfo registrationInfo = new RegistrationInfo();

            registrationInfo.IncludePrerelease = range.IncludePrerelease;

            string id = string.Empty;

            foreach (JObject rangeObj in rangeTasks.Select((t) => t.Result))
            {
                if (rangeObj == null)
                {
                    throw new InvalidDataException(registrationUri.AbsoluteUri);
                }

                foreach (JObject packageObj in rangeObj["items"])
                {
                    JObject catalogEntry = (JObject)packageObj["catalogEntry"];

                    NuGetVersion packageVersion = NuGetVersion.Parse(catalogEntry["version"].ToString());

                    id = catalogEntry["id"].ToString();

                    int publishedDate = 0;
                    JToken publishedValue;

                    if (catalogEntry.TryGetValue("published", out publishedValue))
                    {
                        publishedDate = int.Parse(publishedValue.ToObject<DateTime>().ToString("yyyyMMdd"));
                    }

                    //publishedDate = 0 means the property doesn't exist in index.json
                    //publishedDate = 19000101 means the property exists but the package is unlisted
                    if (range.Satisfies(packageVersion) && (publishedDate!= 19000101))
                    {
                        PackageInfo packageInfo = new PackageInfo();
                        packageInfo.Version = packageVersion;
                        packageInfo.PackageContent = new Uri(packageObj["packageContent"].ToString());

                        JArray dependencyGroupsArray = (JArray)catalogEntry["dependencyGroups"];

                        if (dependencyGroupsArray != null)
                        {
                            // only one target framework group will be used at install time, which means 
                            // we can filter down to that group now by using the project target framework
                            var depFrameworks = dependencyGroupsArray.Select(e => GetFramework(e as JObject));

                            var targetFramework = frameworkReducer.GetNearest(projectTargetFramework, depFrameworks);

                            // If no frameworks are compatible we just ignore them - Should this be an exception?
                            if (targetFramework != null)
                            {
                                foreach (JObject dependencyGroupObj in dependencyGroupsArray)
                                {
                                    NuGetFramework currentFramework = GetFramework(dependencyGroupObj);

                                    if (frameworkComparer.Equals(currentFramework, targetFramework))
                                    {
                                        foreach (JObject dependencyObj in dependencyGroupObj["dependencies"])
                                        {
                                            DependencyInfo dependencyInfo = new DependencyInfo();
                                            dependencyInfo.Id = dependencyObj["id"].ToString();
                                            dependencyInfo.Range = Utils.CreateVersionRange((string)dependencyObj["range"], range.IncludePrerelease);
                                            dependencyInfo.RegistrationUri = dependencyObj["registration"].ToObject<Uri>();

                                            packageInfo.Dependencies.Add(dependencyInfo);
                                        }
                                    }
                                }
                            }
                        }

                        registrationInfo.Add(packageInfo);
                    }
                }

                registrationInfo.Id = id;
            }

            return registrationInfo;
        }
Esempio n. 22
0
        public PackageBuilder GetPackageBuilder(IPackTaskRequest <IMSBuildItem> request)
        {
            // Load the assets JSON file produced by restore.
            var assetsFilePath = Path.Combine(request.RestoreOutputPath, LockFileFormat.AssetsFileName);

            if (!File.Exists(assetsFilePath))
            {
                throw new PackagingException(NuGetLogCode.NU5023, string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.AssetsFileNotFound,
                                                 assetsFilePath));
            }

            var builder = new PackageBuilder(request.Deterministic)
            {
                Id                       = request.PackageId,
                Description              = request.Description,
                Title                    = request.Title,
                Copyright                = request.Copyright,
                ReleaseNotes             = request.ReleaseNotes,
                RequireLicenseAcceptance = request.RequireLicenseAcceptance,
                PackageTypes             = ParsePackageTypes(request)
            };

            if (request.DevelopmentDependency)
            {
                builder.DevelopmentDependency = true;
            }

            if (request.PackageVersion != null)
            {
                NuGetVersion version;
                if (!NuGetVersion.TryParse(request.PackageVersion, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5024, string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.InvalidPackageVersion,
                                                     request.PackageVersion));
                }
                builder.Version = version;
            }
            else
            {
                builder.Version = new NuGetVersion("1.0.0");
            }

            if (request.Authors != null)
            {
                builder.Authors.AddRange(request.Authors);
            }

            if (request.Tags != null)
            {
                builder.Tags.AddRange(request.Tags);
            }

            Uri tempUri;

            if (Uri.TryCreate(request.LicenseUrl, UriKind.Absolute, out tempUri))
            {
                builder.LicenseUrl = tempUri;
            }
            if (Uri.TryCreate(request.ProjectUrl, UriKind.Absolute, out tempUri))
            {
                builder.ProjectUrl = tempUri;
            }
            if (Uri.TryCreate(request.IconUrl, UriKind.Absolute, out tempUri))
            {
                builder.IconUrl = tempUri;
            }
            if (!string.IsNullOrEmpty(request.RepositoryUrl) || !string.IsNullOrEmpty(request.RepositoryType))
            {
                builder.Repository = new RepositoryMetadata(
                    request.RepositoryType,
                    request.RepositoryUrl,
                    request.RepositoryBranch,
                    request.RepositoryCommit);
            }

            builder.LicenseMetadata = BuildLicenseMetadata(request);

            builder.Icon = request.PackageIcon;

            if (request.MinClientVersion != null)
            {
                Version version;
                if (!Version.TryParse(request.MinClientVersion, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5022, string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.InvalidMinClientVersion,
                                                     request.MinClientVersion));
                }

                builder.MinClientVersion = version;
            }

            // The assets file is necessary for project and package references. Pack should not do any traversal,
            // so we leave that work up to restore (which produces the assets file).
            var lockFileFormat = new LockFileFormat();
            var assetsFile     = lockFileFormat.Read(assetsFilePath);

            if (assetsFile.PackageSpec == null)
            {
                throw new PackagingException(NuGetLogCode.NU5025, string.Format(
                                                 CultureInfo.CurrentCulture,
                                                 Strings.AssetsFileDoesNotHaveValidPackageSpec,
                                                 assetsFilePath));
            }

            var projectRefToVersionMap = new Dictionary <string, string>(PathUtility.GetStringComparerBasedOnOS());

            if (request.ProjectReferencesWithVersions != null && request.ProjectReferencesWithVersions.Any())
            {
                projectRefToVersionMap = request
                                         .ProjectReferencesWithVersions
                                         .ToDictionary(msbuildItem => msbuildItem.Identity,
                                                       msbuildItem => msbuildItem.GetProperty("ProjectVersion"), PathUtility.GetStringComparerBasedOnOS());
            }
            var nuGetFrameworkComparer = new NuGetFrameworkFullComparer();
            var frameworksWithSuppressedDependencies = new HashSet <NuGetFramework>(nuGetFrameworkComparer);

            if (request.FrameworksWithSuppressedDependencies != null && request.FrameworksWithSuppressedDependencies.Any())
            {
                frameworksWithSuppressedDependencies =
                    new HashSet <NuGetFramework>(request.FrameworksWithSuppressedDependencies
                                                 .Select(t => NuGetFramework.Parse(t.Identity)).ToList(), nuGetFrameworkComparer);
            }

            PopulateProjectAndPackageReferences(builder,
                                                assetsFile,
                                                projectRefToVersionMap,
                                                frameworksWithSuppressedDependencies);

            PopulateFrameworkAssemblyReferences(builder, request);
            PopulateFrameworkReferences(builder, assetsFile);

            return(builder);
        }
        /// <summary>
        /// Adds refresh files to the specified project for all assemblies references belonging to the packages specified by packageNames.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="packagesFileSystem">The file system pointing to 'packages' folder under the solution.</param>
        /// <param name="packageNames">The package names.</param>
        private void AddRefreshFilesForReferences(Project project, string repositoryPath, IEnumerable<PackageIdentity> packageNames)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (repositoryPath == null)
            {
                throw new ArgumentNullException("repositoryPath");
            }

            if (!packageNames.Any())
            {
                return;
            }

            VSAPIProjectContext context = new VSAPIProjectContext();
            WebSiteProjectSystem projectSystem = new WebSiteProjectSystem(project, context);

            var root = EnvDTEProjectUtility.GetFullPath(project);

            foreach (var packageName in packageNames)
            {
                string packagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", packageName.Id, packageName.Version);

                DirectoryInfo packageFolder = new DirectoryInfo(Path.Combine(repositoryPath, packagePath));

                PackageFolderReader reader = new PackageFolderReader(packageFolder);

                var frameworkGroups = reader.GetReferenceItems();

                var groups = reader.GetReferenceItems();

                var fwComparer = new NuGetFrameworkFullComparer();
                FrameworkReducer reducer = new FrameworkReducer();
                NuGetFramework targetGroupFramework = reducer.GetNearest(projectSystem.TargetFramework, groups.Select(e => e.TargetFramework));

                if (targetGroupFramework != null)
                {
                    var refGroup = groups.Where(e => fwComparer.Equals(targetGroupFramework, e.TargetFramework)).FirstOrDefault();

                    foreach (string refItem in refGroup.Items)
                    {
                        string sourcePath = Path.Combine(packageFolder.FullName, refItem.Replace('/', Path.DirectorySeparatorChar));

                        // create one refresh file for each assembly reference, as per required by Website projects
                        // projectSystem.CreateRefreshFile(assemblyPath);
                        RefreshFileUtility.CreateRefreshFile(projectSystem, sourcePath, context);
                    }
                }
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Retrieve a registration blob
        /// </summary>
        /// <returns>Returns Null if the package does not exist</returns>
        public static async Task<RegistrationInfo> GetRegistrationInfo(
            HttpClient httpClient,
            Uri registrationUri,
            VersionRange range,
            NuGetFramework projectTargetFramework,
            CancellationToken token)
        {
            var frameworkComparer = new NuGetFrameworkFullComparer();
            var frameworkReducer = new FrameworkReducer();
            var dependencies = await GetDependencies(httpClient, registrationUri, range, token);
            
            var registrationInfo = new RegistrationInfo();

            registrationInfo.IncludePrerelease = range.IncludePrerelease;
            foreach (var item in dependencies)
            {
                var packageInfo = new PackageInfo
                    {
                        Listed = item.Listed,
                        Version = item.Identity.Version,
                        PackageContent = new Uri(item.ContentUri)
                    };

                // only one target framework group will be used at install time, which means 
                // we can filter down to that group now by using the project target framework
                var depFrameworks = item.DependencyGroups.Select(e => e.TargetFramework);
                var targetFramework = frameworkReducer.GetNearest(projectTargetFramework, depFrameworks);

                // If no frameworks are compatible we just ignore them - Should this be an exception?
                if (targetFramework != null)
                {
                    var dependencyGroup = item.DependencyGroups.FirstOrDefault(d => frameworkComparer.Equals(targetFramework, d.TargetFramework));
                    if (dependencyGroup != null)
                    {
                        foreach (var dependency in dependencyGroup.Packages)
                        {
                            var dependencyInfo = new DependencyInfo
                                {
                                    Id = dependency.Id,
                                    Range = dependency.VersionRange
                                };

                            packageInfo.Dependencies.Add(dependencyInfo);
                        }
                    }
                }

                registrationInfo.Add(packageInfo);
                registrationInfo.Id = item.Identity.Id;
            }

            return registrationInfo;
        }
Esempio n. 25
0
        /// <summary>
        /// Remove duplicates found in the equivalence mappings.
        /// </summary>
        public IEnumerable<NuGetFramework> Reduce(IEnumerable<NuGetFramework> frameworks)
        {
            // order first so we get consistent results for equivalent frameworks
            var input = frameworks.OrderBy(f => f.DotNetFrameworkName, StringComparer.OrdinalIgnoreCase).ToArray();

            var comparer = new NuGetFrameworkFullComparer();

            for (var i = 0; i < input.Length; i++)
            {
                var dupe = false;

                IEnumerable<NuGetFramework> eqFrameworks = null;
                if (!_mappings.TryGetEquivalentFrameworks(input[i], out eqFrameworks))
                {
                    eqFrameworks = new List<NuGetFramework>() { input[i] };
                }

                for (var j = i + 1; !dupe && j < input.Length; j++)
                {
                    dupe = eqFrameworks.Contains(input[j], comparer);
                }

                if (!dupe)
                {
                    yield return input[i];
                }
            }

            yield break;
        }