Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download and unzip packages using NuGet v3 API

I have been using the following code from the NuGet.Core package, which I found on http://blog.nuget.org/20130520/Play-with-packages.html

//ID of the package to be looked up
string packageID = "EntityFramework";

//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

//Initialize the package manager string path = <PATH_TO_WHERE_THE_PACKAGES_SHOULD_BE_INSTALLED>
PackageManager packageManager = new PackageManager(repo, path);

//Download and unzip the package
packageManager.InstallPackage(packageID, SemanticVersion.Parse("5.0.0"));

This has worked perfectly, but I had to update the framework to .NET Core, which the NuGet.Core package does not support. I think the package NuGet.Protocol.Core.v3 should have what I need, but I haven't been able to find a way to do it. I found plenty of information about the NuGet v3 API on http://daveaglick.com/posts/exploring-the-nuget-v3-libraries-part-1

So my question is: How do I download and unzip packages programmatically using NuGet v3?

like image 878
Luxaes Avatar asked Sep 19 '16 09:09

Luxaes


1 Answers

Introduction

I'm using nuget v2 in some projects. Recently, I tested the nuget v3, because there are a lot of packages that throw errors indicating to use the nuget v3. So I tried to test the nuget v3 in an example project. I'm not an expert, but the download works.

Type of project

I found 3 types of NuGet projects.

  • PackagesConfigNuGetProject
  • FolderNuGetProject
  • MSBuildNuGetProject

PackagesConfigNuGetProject:

Represents a NuGet project as represented by packages.config.

Note : It will download your package in the packages.config (in fact, it will add an entry for your package in the packages.config). Your NuGet package won't be in your disk, only in the packages.config. So if you want to get or use the dll, you need to use the FolderNuGetProject #

FolderNuGetProject:

This class represents a NuGetProject based on a folder such as packages folder on a VisualStudio solution.

Use this class if you want your packages installed on your disk. #

MSBuildNuGetProject:

This class represents a NuGetProject based on a .NET project. This also contains an instance of a FolderNuGetProject

I don't know what project type you want to use. In this example, I picked the FolderNuGetProject.

Code example

1- Initialize the source repository

List<Lazy<INuGetResourceProvider>> providers = new List<Lazy<INuGetResourceProvider>>();
providers.AddRange(Repository.Provider.GetCoreV3());

PackageSource packageSource = new PackageSource("https://api.nuget.org/v3/index.json");
SourceRepository sourceRepository = new SourceRepository(packageSource, providers);
Logger logger = new Logger();

2- Initialize the Nuget package manager

var rootPath = @"yourPathToNugetFolder";
var settings = Settings.LoadDefaultSettings(rootPath, null, new MachineWideSettings());
var packageSourceProvider = new PackageSourceProvider(settings);
var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);

var project = new FolderNuGetProject(rootPath);
var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
{
    PackagesFolderNuGetProject = project
};

3- Search a package (in this example I chose: Newtonsoft.Json)

var searchResource = await sourceRepository.GetResourceAsync<PackageSearchResource>();
var supportedFramework = new[] { ".NETFramework,Version=v4.6" };
var searchFilter = new SearchFilter(true)
{
    SupportedFrameworks = supportedFramework,
    IncludeDelisted = false
};

var jsonNugetPackages = await searchResource
    .SearchAsync("Newtonsoft.Json", searchFilter, 0, 10, logger, CancellationToken.None);

4- Install the package (Newtonsoft.Json)

Be careful when install a nuget package in a project. It will freeze the UI. You should do the process using a BackgroundWorker or something similar.

var allowPrereleaseVersions = true;
var allowUnlisted = false;
INuGetProjectContext projectContext = new ProjectContext();
ResolutionContext resolutionContext = new ResolutionContext(
    DependencyBehavior.Lowest,
    allowPrereleaseVersions,
    allowUnlisted,
    VersionConstraints.None);

var jsonPackage = jsonNugetPackages.First();
var identity = new PackageIdentity(jsonPackage.Identity.Id, jsonPackage.Identity.Version);
await packageManager.InstallPackageAsync(
    project,
    identity,
    resolutionContext,
    projectContext,
    sourceRepository,
    new List<SourceRepository>(),
    CancellationToken.None);

5- Utilities classes

public class MachineWideSettings : IMachineWideSettings
{
    private readonly Lazy<IEnumerable<Settings>> _settings;

    public MachineWideSettings()
    {
        var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory);
        _settings = new Lazy<IEnumerable<Settings>>(
            () => global::NuGet.Configuration.Settings.LoadMachineWideSettings(baseDirectory));
    }

    public IEnumerable<Settings> Settings => _settings.Value;
}

public class Logger : ILogger
{
    private List<string> logs = new List<string>();

    public void LogDebug(string data)
    {
        logs.Add(data);
    }

    public void LogVerbose(string data)
    {
        logs.Add(data);
    }

    public void LogInformation(string data)
    {
        logs.Add(data);
    }

    public void LogMinimal(string data)
    {
        logs.Add(data);
    }

    public void LogWarning(string data)
    {
        logs.Add(data);
    }

    public void LogError(string data)
    {
        logs.Add(data);
    }

    public void LogInformationSummary(string data)
    {
        logs.Add(data);
    }

    public void LogErrorSummary(string data)
    {
        logs.Add(data);
    }
}

public class ProjectContext : INuGetProjectContext
{
    private List<string> logs = new List<string>();

    public List<string> GetLogs()
    {
        return logs;
    }

    public void Log(MessageLevel level, string message, params object[] args)
    {
        var formattedMessage = String.Format(message, args);
        logs.Add(formattedMessage);
        // Do your logging here...
    }

    public FileConflictAction ResolveFileConflict(string message)
    {
        logs.Add(message);
        return FileConflictAction.Ignore;
    }


    public PackageExtractionContext PackageExtractionContext
    {
        get;
        set;
    }

    public NuGet.ProjectManagement.ExecutionContext ExecutionContext
    {
        get;
    }

    public XDocument OriginalPackagesConfig
    {
        get; set;
    }

    public ISourceControlManagerProvider SourceControlManagerProvider
    {
        get;
        set;
    }

    public void ReportError(string message)
    {
        logs.Add(message);
    }

    public NuGetActionType ActionType
    {
        get; set;
    }

    public TelemetryServiceHelper TelemetryService
    {
        get; set;
    }
}

Hope this will help you!

like image 196
yanckst Avatar answered Nov 14 '22 12:11

yanckst