Installing a NuGet package programmatically

I've been struggling for some time to make NuGet work for my online .Net IDE project, Chpokk. The good news is that there turned out to be a command line tool, NuGet.exe, which can be used on a build server, so I though I'd just use its functionality. The bad news is that it turned out that it only downloaded packages, not modifying the project. Then the good news is that there's ProjectManager class, which can handle the required modifications to the project. And of course there's the bad news -- while this guy downloads the packages, it doesn't copy the unzipped files to the package folder from the temporary location. Fortunately, the final news was good -- the ProjectManager class proved to be extensible enough to make it work. Although I haven't tested some advanced stuff, like ps scripts or config transforms, it works for the most situations, and extending it would be pretty simple.

Here's the main part of the code:

public void InstallPackage(string packageIdstring projectPathstring targetFolder = null) {
	var packagePathResolver = new DefaultPackagePathResolver(targetFolder);
	var packagesFolderFileSystem = new PhysicalFileSystem(targetFolder);
	var projectSystem = new BetterThanMSBuildProjectSystem(projectPath) { Logger = _console };
	var localRepository = new BetterThanLocalPackageRepository(packagePathResolverpackagesFolderFileSystemprojectSystem);
	var projectManager = new ProjectManager(_packageRepositorypackagePathResolverprojectSystem,
											localRepository) {Logger = _console};
 
	projectManager.PackageReferenceAdded += (senderargs=> args.Package.GetLibFiles()
	                                                              .Each(file => SaveAssemblyFile(args.InstallPathfile));
	projectManager.AddPackageReference(packageId);
	projectSystem.Save();
}

The most work is done by the ProjectManager class. I had to add three extensions though. First, in the PackageReferenceAdded handler, I make sure that the assembly files are saved to install path. Second, I extend the MSBuildProjectSystem class in order to add the content files to the project. Last, I'm subclassing the LockalPackageRepository class. This class is used, in particular, for checking whether a package is already installed. The implementation just checked that either a *.nuspec or *.nupkg file existed.

You can find a working project at https://github.com/uluhonolulu/BlogSamples/tree/master/NuGetSample. Download the project and build a console executable that, when run, installs the NUnit (or another, if you add an argument) package to the "testPackages" folder and adds a reference to the project.

Happy Nuggeting!

blog comments powered by Disqus

Latest blog posts

Powered by FeedBurner

Archives