private static void CreatePackageConfigs(IFileSystem fs, out PackageReferenceFile f1, out PackageReferenceFile f2)
        {
            f1 = (new PackageReferenceFile(fs, @"c:\test1\packages.config"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.0.0.0"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.1.0.0"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.2.0.0"));

            f2 = (new PackageReferenceFile(fs, @"c:\test2\packages.config"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.0.0.0"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.1.0.0"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.2.0.0"));
        }
        private static void CreatePackageConfigs(IFileSystem fs, out PackageReferenceFile f1, out PackageReferenceFile f2)
        {
            f1 = (new PackageReferenceFile(fs, @"c:\test1\packages.config"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.0.0.0"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.1.0.0"));
            f1.AddEntry("Test", SemanticVersion.Parse("1.2.0.0"));

            f2 = (new PackageReferenceFile(fs, @"c:\test2\packages.config"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.0.0.0"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.1.0.0"));
            f2.AddEntry("Test", SemanticVersion.Parse("1.2.0.0"));
        }
Esempio n. 3
0
        public IEnumerable <string> CreatePackageFile()
        {
            var packagesFile         = Path.Combine(_fileSystem.CurrentDirectory, Constants.PackagesFile);
            var packageReferenceFile = new PackageReferenceFile(packagesFile);

            var packagesFolder = Path.Combine(_fileSystem.CurrentDirectory, Constants.PackagesFolder);
            var repository     = new LocalPackageRepository(packagesFolder);

            var newestPackages = repository.GetPackages().GroupBy(p => p.Id)
                                 .Select(g => g.OrderByDescending(p => p.Version).FirstOrDefault());

            foreach (var package in newestPackages)
            {
                var newestFramework = GetNewestSupportedFramework(package);
                packageReferenceFile.AddEntry(package.Id, package.Version, newestFramework);

                if (newestFramework == null)
                {
                    yield return(string.Format("{0}, Version {1}", package.Id, package.Version));
                }
                else
                {
                    yield return(string.Format("{0}, Version {1}, .NET {2}", package.Id, package.Version, newestFramework.Version));
                }
            }
        }
        /// <summary>
        /// Outputs a package.config file reflecting the set of packages that provides the requested set of assemblies.
        /// </summary>
        public void OutputPackageConfigFile()
        {
            var packagesConfig = Constants.PackageReferenceFile;
            if (_fileSystem.FileExists(packagesConfig))
                _fileSystem.DeleteFile(packagesConfig);

            if (!_fileSystem.FileExists(packagesConfig))
            {
                var prf = new PackageReferenceFile(_fileSystem, string.Format(".\\{0}", packagesConfig));
                foreach (var assemblyToPackageMapping in ResolvedMappings)
                {
                    IPackage smallestPackage;
                    if (assemblyToPackageMapping.Value.Count > 1)
                    {
                        smallestPackage = assemblyToPackageMapping.Value.OrderBy(l => l.GetFiles().Count()).FirstOrDefault();
                        _console.WriteLine(String.Format("{0} : Choosing {1} from {2} choices.", assemblyToPackageMapping.Key, smallestPackage.Id, assemblyToPackageMapping.Value.Count()));
                    }
                    else
                    {
                        smallestPackage = assemblyToPackageMapping.Value.First();
                    }
                    //Only add if we do not have another instance of the ID, not the id/version combo....
                    if (!prf.GetPackageReferences().Any(p => p.Id == smallestPackage.Id))
                        prf.AddEntry(smallestPackage.Id, smallestPackage.Version);
                }
            }
            else
            {
                _console.WriteError("Please move the existing packages.config file....");
            }
        }
        //writes new version of the package to packages.config file
        public void writeToConfig(string fileName, string packageId, SemanticVersion newversion)
        {
            var file = new PackageReferenceFile(fileName);

            file.DeleteEntry(packageId, null);
            file.AddEntry(packageId, newversion);
        }
        private void CreatePackagesConfig(ICollection <IPackage> packagesToAdd, FrameworkName targetFramework)
        {
            _console.WriteLine("Creating {0}", PackageReferenceFilename);
            var packagesConfig = new PackageReferenceFile(_projectFileSystem, PackageReferenceFilename);

            foreach (var package in packagesToAdd)
            {
                if (!packagesConfig.EntryExists(package.Id, package.Version)) //Note we don't re-add entries that have the wrong targetFramework set
                {
                    packagesConfig.AddEntry(package.Id, package.Version, false, targetFramework);
                }
            }
        }
Esempio n. 7
0
        public void InstallPackagesFromConfigFile(DeployMessage.Item[] items, out string packagesDirectory, out string packagesFile, out string version)
        {
            version           = null;
            packagesFile      = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + "\\packages.config");
            packagesDirectory = Path.GetDirectoryName(packagesFile);
            if (!Directory.Exists(packagesDirectory))
            {
                Directory.CreateDirectory(packagesDirectory);
            }
            var referenceFile = new PackageReferenceFile(packagesFile);

            foreach (var item in items)
            {
                referenceFile.AddEntry(item.PackageId, (SemanticVersion.ParseOptionalVersion(item.Version) ?? _emptySemanticVersion));
            }
        }
Esempio n. 8
0
        private void CreateNuGetScaffolding(SharedPackageRepository sharedPackagesRepository, List <ManifestDependency> manifestDependencies, IEnumerable <KeyValuePair <string, List <IPackage> > > resolvedMappings, FileInfo projectFileInfo, Project project, List <string> projectDependencies)
        {
            //Now, create the packages.config for the resolved packages, and update the repositories.config
            Console.WriteLine("Creating packages.config");
            var packagesConfigFilePath = Path.Combine(projectFileInfo.Directory.FullName + "\\", "packages.config");
            var packagesConfig         = new PackageReferenceFile(packagesConfigFilePath);

            foreach (var referenceMapping in resolvedMappings)
            {
                //TODO We shouldnt need to resolve this twice....
                var package = referenceMapping.Value.OrderBy(p => p.GetFiles().Count()).First();
                if (!packagesConfig.EntryExists(package.Id, package.Version))
                {
                    packagesConfig.AddEntry(package.Id, package.Version);
                }
                if (NuSpec && manifestDependencies.All(m => m.Id != package.Id))
                {
                    manifestDependencies.Add(new ManifestDependency {
                        Id = package.Id
                    });
                }
            }

            //This is messy...refactor
            //For any resolved project dependencies, add a manifest dependency if we are doing nuspecs
            if (NuSpec)
            {
                foreach (var projectDependency in projectDependencies)
                {
                    if (manifestDependencies.All(m => m.Id != projectDependency))
                    {
                        manifestDependencies.Add(new ManifestDependency {
                            Id = projectDependency
                        });
                    }
                }
            }
            //Register the packages.config
            sharedPackagesRepository.RegisterRepository(packagesConfigFilePath);

            //Add the packages.config to the project content, otherwise later versions of the VSIX fail...
            if (!project.GetItems("None").Any(i => i.UnevaluatedInclude.Equals("packages.config")))
            {
                project.Xml.AddItemGroup().AddItem("None", "packages.config");
                project.Save();
            }
        }
        /// <summary>
        /// Executes the command.
        /// </summary>
        public override void ExecuteCommand()
        {
            string inputPackagesConfigPath = GetLatestPackagesConfigPath();
            string outputPackagesConfigPath = GetPackagesConfigPath();

            if (String.IsNullOrEmpty(inputPackagesConfigPath) || String.IsNullOrEmpty(outputPackagesConfigPath))
            {
                throw new CommandLineException();
            }

            if (!File.Exists(inputPackagesConfigPath))
            {
                throw new CommandLineException();
            }

            TryCreateAllDirectories(Path.GetDirectoryName(outputPackagesConfigPath));
            if(!File.Exists(outputPackagesConfigPath))
            {
                File.WriteAllText(outputPackagesConfigPath, @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
</packages>");
            }

            PhysicalFileSystem outputFileSystem = new PhysicalFileSystem(Path.GetDirectoryName(outputPackagesConfigPath));
            PackageReferenceFile outputFile = new PackageReferenceFile(outputFileSystem, Path.GetFileName(outputPackagesConfigPath));

            // Remove all existing references from output file
            Dictionary<string, SemanticVersion> existingReferences = new Dictionary<string,SemanticVersion>();
            foreach (PackageReference packageReference in outputFile.GetPackageReferences())
            {
                existingReferences.Add(packageReference.Id, packageReference.Version);
            }
            foreach (KeyValuePair<string, SemanticVersion> pair in existingReferences)
            {
                outputFile.DeleteEntry(pair.Key, pair.Value);
            }

            PhysicalFileSystem inputFileSystem = new PhysicalFileSystem(Path.GetDirectoryName(inputPackagesConfigPath));
            PackageReferenceFile inputFile = new PackageReferenceFile(inputFileSystem, Path.GetFileName(inputPackagesConfigPath));
            foreach (PackageReference packageReference in inputFile.GetPackageReferences())
            {
                IPackage package = GetLatestPackage(packageReference.Id);
                outputFile.AddEntry(packageReference.Id, package.Version, false, packageReference.TargetFramework);
            }
        }
Esempio n. 10
0
        public void CreatePackageFile()
        {
            var packagesFile         = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFile);
            var packageReferenceFile = new PackageReferenceFile(packagesFile);

            var packagesFolder = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFolder);
            var repository     = new LocalPackageRepository(packagesFolder);

            var newestPackages = repository.GetPackages().GroupBy(p => p.Id)
                                 .Select(g => g.OrderByDescending(p => p.Version).FirstOrDefault());

            if (!newestPackages.Any())
            {
                _logger.Info("No packages found!");
                return;
            }

            _logger.InfoFormat("{0} {1}...", (File.Exists(packagesFile) ? "Updating" : "Creating"), _fileSystem.PackagesFile);

            foreach (var package in newestPackages)
            {
                var newestFramework = GetNewestSupportedFramework(package);

                if (!packageReferenceFile.EntryExists(package.Id, package.Version))
                {
                    packageReferenceFile.AddEntry(package.Id, package.Version, package.DevelopmentDependency, newestFramework);

                    if (newestFramework == null)
                    {
                        _logger.InfoFormat("Added {0} (v{1}) to {2}", package.Id, package.Version, _fileSystem.PackagesFile);
                    }
                    else
                    {
                        _logger.InfoFormat("Added {0} (v{1}, .NET {2}) to {3}", package.Id, package.Version, newestFramework.Version, _fileSystem.PackagesFile);
                    }

                    continue;
                }

                _logger.InfoFormat("Skipped {0} because it already exists.", package.Id);
            }

            _logger.InfoFormat("Successfully {0} {1}.", (File.Exists(packagesFile) ? "updated" : "created"), _fileSystem.PackagesFile);
        }
        /// <summary>
        /// Outputs a package.config file reflecting the set of packages that provides the requested set of assemblies.
        /// </summary>
        public void OutputPackageConfigFile()
        {
            var packagesConfig = Constants.PackageReferenceFile;

            if (_fileSystem.FileExists(packagesConfig))
            {
                _fileSystem.DeleteFile(packagesConfig);
            }

            if (!_fileSystem.FileExists(packagesConfig))
            {
                var prf = new PackageReferenceFile(_fileSystem, packagesConfig);
                foreach (var assemblyToPackageMapping in ResolvedMappings)
                {
                    IPackage smallestPackage;
                    if (assemblyToPackageMapping.Value.Count > 1)
                    {
                        smallestPackage = assemblyToPackageMapping.Value.OrderBy(l => l.GetFiles().Count()).FirstOrDefault();
                        _console.WriteLine(String.Format("{0} : Choosing {1} from {2} choices.", assemblyToPackageMapping.Key, smallestPackage.Id, assemblyToPackageMapping.Value.Count()));
                    }
                    else
                    {
                        smallestPackage = assemblyToPackageMapping.Value.First();
                    }
                    //Only add if we do not have another instance of the ID, not the id/version combo....
                    if (!prf.GetPackageReferences().Any(p => p.Id == smallestPackage.Id))
                    {
                        prf.AddEntry(smallestPackage.Id, smallestPackage.Version);
                    }
                }
            }
            else
            {
                _console.WriteError("Please move the existing packages.config file....");
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Installs the packages from config file.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="file">The file.</param>
        /// <param name="target"> </param>
        private IEnumerable <PackageReference> InstallPackagesFromConfigFile(string packagesDirectory, PackageReferenceFile file, string target)
        {
            var packageReferences = file.GetPackageReferences().ToList();
            var installedPackages = new List <PackageReference>();
            var allInstalled      = new List <PackageReference>();

            //We need to create a damn filesystem at the packages directory, so that the ROOT is correct.  Ahuh...
            var fileSystem = CreateFileSystem(packagesDirectory);

            if (!NoCache)
            {
                Console.WriteLine("Using cache....");
            }
            PackageManager packageManager = CreatePackageManager(fileSystem, useMachineCache: !NoCache);

            if (Clean)
            {
                packageManager.CleanPackageFolders();
            }

            bool installedAny = false;

            foreach (var packageReference in packageReferences)
            {
                if (String.IsNullOrEmpty(packageReference.Id))
                {
                    // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                    // with malformed ids / Versions.
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandInvalidPackageReference, target));
                }
                else if (packageReference.Version == null)
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandPackageReferenceInvalidVersion, packageReference.Id));
                }

                packageManager.PackageInstalled += (sender, e) =>
                {
                    var installedPackage = new PackageReference(e.Package.Id, e.Package.Version, null, _frameworkName, false);
                    if (!allInstalled.Contains(installedPackage))
                    {
                        allInstalled.Add(installedPackage);
                    }
                };
                IPackage package = _packageResolutionManager.ResolveLatestInstallablePackage(_repository, packageReference);
                if (package == null)
                {
                    SemanticVersion version = _packageResolutionManager.ResolveInstallableVersion(_repository, packageReference);
                    installedAny |= InstallPackage(packageManager, fileSystem, packageReference.Id, version ?? packageReference.Version);
                    installedPackages.Add(new PackageReference(packageReference.Id, version ?? packageReference.Version, null, _frameworkName, false));
                }
                else
                {
                    //We got it straight from the server, check whether we get a cache hit, else just install
                    var resolvedPackage = _packageResolutionManager.FindPackageInAllLocalSources(packageManager.LocalRepository, packageManager.SourceRepository, package);
                    packageManager.InstallPackage(resolvedPackage ?? package, !IncludeDependencies, false);
                    installedPackages.Add(new PackageReference(package.Id, resolvedPackage != null ? resolvedPackage.Version : package.Version, null, _frameworkName, false));
                }
                // Note that we ignore dependencies here because packages.config already contains the full closure
            }

            if (!installedAny && packageReferences.Any())
            {
                Console.WriteLine(GetResources.GetCommandNothingToInstall, Constants.PackageReferenceFile);
            }

            if (packageReferences != installedPackages)
            {
                foreach (var reference in file.GetPackageReferences())
                {
                    file.DeleteEntry(reference.Id, reference.Version);
                }
                foreach (var installedPackage in installedPackages)
                {
                    file.AddEntry(installedPackage.Id, installedPackage.Version);
                }
            }

            return(allInstalled);
        }
Esempio n. 13
0
        private void CreateNuGetScaffolding(SharedPackageRepository sharedPackagesRepository, List<ManifestDependency> manifestDependencies, IEnumerable<KeyValuePair<string, List<IPackage>>> resolvedMappings, FileInfo projectFileInfo, Project project, List<string> projectDependencies)
        {
            //Now, create the packages.config for the resolved packages, and update the repositories.config
            Console.WriteLine("Creating packages.config");
            var packagesConfigFilePath = Path.Combine(projectFileInfo.Directory.FullName + "\\", "packages.config");
            var packagesConfig = new PackageReferenceFile(packagesConfigFilePath);
            foreach (var referenceMapping in resolvedMappings)
            {
                //TODO We shouldnt need to resolve this twice....
                var package = referenceMapping.Value.OrderBy(p => p.GetFiles().Count()).First();
                if (!packagesConfig.EntryExists(package.Id, package.Version))
                    packagesConfig.AddEntry(package.Id, package.Version);
                if (NuSpec && manifestDependencies.All(m => m.Id != package.Id))
                {
                    manifestDependencies.Add(new ManifestDependency {Id = package.Id});
                }
            }

            //This is messy...refactor
            //For any resolved project dependencies, add a manifest dependency if we are doing nuspecs
            if (NuSpec)
            {
                foreach (var projectDependency in projectDependencies)
                {
                    if (manifestDependencies.All(m => m.Id != projectDependency))
                    {
                        manifestDependencies.Add(new ManifestDependency {Id = projectDependency});
                    }
                }
            }
            //Register the packages.config
            sharedPackagesRepository.RegisterRepository(packagesConfigFilePath);

            //Add the packages.config to the project content, otherwise later versions of the VSIX fail...
            if (!project.GetItems("None").Any(i => i.UnevaluatedInclude.Equals("packages.config")))
            {
                project.Xml.AddItemGroup().AddItem("None", "packages.config");
                project.Save();
            }
        }
Esempio n. 14
0
        public override void ExecuteCommand()
        {
            if (string.IsNullOrEmpty(Directory))
            {
                Directory = Environment.CurrentDirectory;
            }

            if (_repository == null)
            {
                _repository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source);
            }

            var packageFiles = _fileSystem.GetFiles(Directory, "packages.config", true).ToList();

            Console.WriteLine("Processing : {0} files.", packageFiles.Count);
            Parallel.ForEach(packageFiles, packageFile =>
            {
                Console.WriteLine("\t{0}", packageFile);
                var newReferences      = new List <PackageReference>();
                var packageFileDetails = new PackageReferenceFile(_fileSystem, packageFile);
                foreach (var packageReference in packageFileDetails.GetPackageReferences())
                {
                    Console.WriteLine("\t\t{0}", packageReference.ToString());
                    var exists = _repository.FindPackage(packageReference.Id, packageReference.Version);
                    if (exists != null)
                    {
                        Console.WriteLine("\t\t\tExists, not changing.");
                        newReferences.Add(packageReference);
                    }
                    else
                    {
                        var package = _repository.FindPackagesById(packageReference.Id).FirstOrDefault();
                        if (package == null)
                        {
                            Console.WriteLine("\t\t\tNot found, no change.");
                            newReferences.Add(packageReference);
                        }
                        else
                        {
                            var newReference = new PackageReference(package.Id, package.Version, new VersionSpec(), new FrameworkName(".NET Framework, Version=4.0"), false);
                            Console.WriteLine("\t\t\tUpdated to {0}", newReference.ToString());
                            newReferences.Add(newReference);
                        }
                    }
                }

                //TODO Clear the file (must be an easier way).
                Console.WriteLine("Clearing existing file...");
                foreach (var packageReference in packageFileDetails.GetPackageReferences())
                {
                    packageFileDetails.DeleteEntry(packageReference.Id, packageReference.Version);
                }

                //Add the new references.
                Console.WriteLine("Adding new references...");
                foreach (var packageReference in newReferences)
                {
                    packageFileDetails.AddEntry(packageReference.Id, packageReference.Version);
                }
            });
        }
Esempio n. 15
0
        public static void ManagePackage(PackageReference packageReference, IEnumerable<Project> checkedProjects, IEnumerable<LibraryReference> libraries)
        {
            if (!IsSolutionOpen)
                return;

            foreach (var project in DTE.Solution.Projects.OfType<Project>().Where(n => n.IsSupported()))
            {
                var resultLibraries = Enumerable.Empty<LibraryReference>();

                var projectLibraries = libraries.Where(n => n.ProjectName == project.GetName());

                switch (packageReference.Type)
                {
                    case DeveloperLibraryType.VcInclude:
                        project.ManageIncludeDirectories(packageReference, checkedProjects);
                        break;
                    case DeveloperLibraryType.VcLibrary:
                        project.ManageLinkerDefinitions(packageReference, checkedProjects, projectLibraries);
                        resultLibraries = projectLibraries.Where(n => n.IsChecked);
                        break;
                    case DeveloperLibraryType.Net:
                        project.ManageReferences(packageReference, projectLibraries);
                        resultLibraries = projectLibraries.Where(n => n.IsChecked);
                        break;
                }

                var packageReferenceFile = new PackageReferenceFile(project.GetDirectory() + "/coapp.packages.config");

                if (checkedProjects.Any(n => n.FullName == project.FullName))
                {
                    packageReferenceFile.AddEntry(packageReference.CanonicalName, resultLibraries, packageReference.Type);
                }
                else
                {
                    packageReferenceFile.DeleteEntry(packageReference.CanonicalName);
                }

                project.Save(project.FullName);
            }
        }
        public override void ExecuteCommand()
        {
            if (string.IsNullOrEmpty(Directory))
            {
                Directory = Environment.CurrentDirectory;
            }

            if (_repository == null)
            {
                _repository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source);
            }

            var packageFiles = _fileSystem.GetFiles(Directory, "packages.config", true).ToList();
            Console.WriteLine("Processing : {0} files.",packageFiles.Count);
            Parallel.ForEach(packageFiles, packageFile =>
                {
                    Console.WriteLine("\t{0}", packageFile);
                    var newReferences = new List<PackageReference>();
                    var packageFileDetails = new PackageReferenceFile(_fileSystem, packageFile);
                    foreach (var packageReference in packageFileDetails.GetPackageReferences())
                    {
                        Console.WriteLine("\t\t{0}",packageReference.ToString());
                        var exists = _repository.FindPackage(packageReference.Id, packageReference.Version);
                        if (exists != null)
                        {
                            Console.WriteLine("\t\t\tExists, not changing.");
                            newReferences.Add(packageReference);
                        }
                        else
                        {
                            var package = _repository.FindPackagesById(packageReference.Id).FirstOrDefault();
                            if (package == null)
                            {
                                Console.WriteLine("\t\t\tNot found, no change.");
                                newReferences.Add(packageReference);
                            }
                            else
                            {
                                var newReference = new PackageReference(package.Id, package.Version, new VersionSpec(), new FrameworkName(".NET Framework, Version=4.0"), false);
                                Console.WriteLine("\t\t\tUpdated to {0}", newReference.ToString());
                                newReferences.Add(newReference);
                            }
                        }
                    }

                    //TODO Clear the file (must be an easier way).
                    Console.WriteLine("Clearing existing file...");
                    foreach (var packageReference in packageFileDetails.GetPackageReferences())
                    {
                        packageFileDetails.DeleteEntry(packageReference.Id, packageReference.Version);
                    }

                    //Add the new references.
                    Console.WriteLine("Adding new references...");
                    foreach (var packageReference in newReferences)
                    {
                        packageFileDetails.AddEntry(packageReference.Id, packageReference.Version);
                    }
                });
        }
Esempio n. 17
0
        /// <summary>
        /// Installs the packages from config file.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="file">The file.</param>
        /// <param name="target"> </param>
        private IEnumerable<PackageReference> InstallPackagesFromConfigFile(string packagesDirectory, PackageReferenceFile file, string target)
        {
            var packageReferences = file.GetPackageReferences().ToList();
            var installedPackages = new List<PackageReference>();
            var allInstalled = new List<PackageReference>();

            //We need to create a damn filesystem at the packages directory, so that the ROOT is correct.  Ahuh...
            var fileSystem = CreateFileSystem(packagesDirectory);

            if (!NoCache)
                Console.WriteLine("Using cache....");
            PackageManager packageManager = CreatePackageManager(fileSystem, useMachineCache: !NoCache);

            if (Clean)
                packageManager.CleanPackageFolders();

            bool installedAny = false;
            foreach (var packageReference in packageReferences)
            {
                if (String.IsNullOrEmpty(packageReference.Id))
                {
                    // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                    // with malformed ids / Versions.
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandInvalidPackageReference, target));
                }
                else if (packageReference.Version == null)
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, GetResources.GetCommandPackageReferenceInvalidVersion, packageReference.Id));
                }

                packageManager.PackageInstalled += (sender, e) => 
                    { 
                        var installedPackage = new PackageReference(e.Package.Id, e.Package.Version, null, _frameworkName, false);
                        if (!allInstalled.Contains(installedPackage))
                            allInstalled.Add(installedPackage);
                    };
                IPackage package = _packageResolutionManager.ResolveLatestInstallablePackage(_repository, packageReference);
                if (package == null)
                {
                    SemanticVersion version = _packageResolutionManager.ResolveInstallableVersion(_repository, packageReference);
                    installedAny |= InstallPackage(packageManager, fileSystem, packageReference.Id, version ?? packageReference.Version);
                    installedPackages.Add(new PackageReference(packageReference.Id, version ?? packageReference.Version, null, _frameworkName, false));
                }
                else
                {
                    //We got it straight from the server, check whether we get a cache hit, else just install
                    var resolvedPackage = _packageResolutionManager.FindPackageInAllLocalSources(packageManager.LocalRepository, packageManager.SourceRepository, package);
                    packageManager.InstallPackage(resolvedPackage ?? package, !IncludeDependencies, false);
                    installedPackages.Add(new PackageReference(package.Id, resolvedPackage != null ? resolvedPackage.Version : package.Version, null, _frameworkName, false));
                }
                // Note that we ignore dependencies here because packages.config already contains the full closure
            }

            if (!installedAny && packageReferences.Any())
            {
                Console.WriteLine(GetResources.GetCommandNothingToInstall, Constants.PackageReferenceFile);
            }
            
            if (packageReferences != installedPackages)
            {
                foreach (var reference in file.GetPackageReferences())
                    file.DeleteEntry(reference.Id, reference.Version);
                foreach (var installedPackage in installedPackages)
                {
                    file.AddEntry(installedPackage.Id,installedPackage.Version);
                }
            }

            return allInstalled;
        }
        /// <summary>
        /// Outputs a package.config file reflecting the set of packages that provides the requested set of assemblies.
        /// </summary>
        public void OutputPackageConfigFile()
        {
            if (fileSystem.FileExists("packages.config"))
                fileSystem.DeleteFile("packages.config");

            if (!fileSystem.FileExists("packages.config"))
            {
                var prf = new PackageReferenceFile(fileSystem,".\\packages.config");
                foreach (var assemblyToPackageMapping in resolvedAssemblies)
                {
                    if (assemblyToPackageMapping.Value.Count() > 0)
                    {
                        IPackage smallestPackage;
                        if (assemblyToPackageMapping.Value.Count > 1)
                        {
                            smallestPackage = assemblyToPackageMapping.Value.OrderBy(l => l.GetFiles().Count()).FirstOrDefault();
                            Console.WriteLine(String.Format("{0} : Choosing : {1} - {2} to choose from.", assemblyToPackageMapping.Key, smallestPackage.Id, assemblyToPackageMapping.Value.Count()));
                        }
                        else
                        {
                            smallestPackage = assemblyToPackageMapping.Value.First();
                        }
                        //Only add if we do not have another instance of the ID, not the id/version combo....
                        if (!prf.GetPackageReferences().Any(p => p.Id == smallestPackage.Id))
                            prf.AddEntry(smallestPackage.Id, smallestPackage.Version);
                    }
                }
            }
            else
            {
                Console.WriteError("Please move the existing packages.config file....");
            }
        }
 private void CreatePackagesConfig(ICollection<IPackage> packagesToAdd, FrameworkName targetFramework = null)
 {
     _console.WriteLine("Creating {0}", PackageReferenceFilename);
     var packagesConfig = new PackageReferenceFile(_projectFileSystem, PackageReferenceFilename);
     foreach (var package in packagesToAdd)
     {
         if (!packagesConfig.EntryExists(package.Id, package.Version)) //Note we don't re-add entries that have the wrong targetFramework set
         {
             packagesConfig.AddEntry(package.Id, package.Version, false, targetFramework);
         }
     }
 }