NuGet has become one of the best choices for package management in Microsoft .NET. It simplifies handling of third-party libraries, automatically configures your project by adding references to all the necessary assemblies, and updates source and configuration files.
Before NuGet, there was no real dependency management system for .NET projects that could handle adding, saving, and maintaining libraries to solutions and source control systems.
The official NuGet feed is located on http://www.nuget.org and it is a place for over 15,000 unique packages.
As a project grows, the need for additional functionality increases. Some of this functionality can be found in various libraries, so the first issue depends on the decision whether to use external libraries or not. There is a variety of solutions out there and sometimes software companies try to invent their own. We usually end up with one of the two different approaches when doing work on various projects.
The first approach we encountered is simply not using external libraries. Although not having to deal with libraries saves you all the troubles related to third-party dependencies, but you end up reinventing the wheel over and over again.
The second approach is much better and more common: having all the external assemblies in the root project folder (named as lib
, References
, or Dependencies
) and referencing them in projects where needed. Adding these assemblies—either binaries or source code—in source control can save you the trouble when building a solution or setting up a new development environment.
Once a third-party assembly is added to the repository, it is very likely that the assembly never gets updated to a newer version; we do not receive any notification about the new version being released. Updating to a new library release is complicated. The most common reason for version update is when the newer version solved a specific issue encountered by the development team. Upgrading these libraries can cause headaches, problems with backward compatibility, and even requires migration to a newer version of the .NET Framework.
Software developers often search for these third-party assemblies on various open source code repositories such as GitHub, Codeplex, and similar. Once we find a site for the required library, we will start looking for documentation, date of last build, and last check in; basically, everything that will convince us the library is trustworthy and reliable.
NuGet solves all these problems in a simple and convenient way via a graphical user interface or a PowerShell-based command line named Package Management Console.
In the following sections, we will first demonstrate how we would add a third-party library and then reach the same goal using NuGet. We will also cover the installation of NuGet.
In this chapter we will describe the most common way a developer finds a library and adds it to a solution. For the sake of simplicity, let us create a console application that will retrieve and parse an JSON result from a web service, for example, Google query search.
Let us start by creating a new console application:
In Visual Studio 2012, navigate to File | New Project.
In the New Project dialog, choose the Console Application Visual C# template.
Let us name our solution
CH1_01_GoogleApiSearcher
, and start writing some code as shown:class Program { static void Main() { var request = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=nuget"; using (var webClient = new WebClient()) { var result = webClient.DownloadString(request); Console.WriteLine(result); } } }
In the first line of the Main
method, we store a HTTP request in a string, and it is used to query Google's Search API for search results for the nuget
query. In the second line of this method, we are creating an instance of WebClient
, making the web request, and then storing the result in a new string variable. The last line outputs the raw result to the console, in the form of a large unformatted JSON string.
Great, we have a JSON result. We now need a JSON library to parse our result into a meaningful form. When dealing with unknown libraries, the best choice is to type some relevant keywords into our favorite search engine.
For example, let's write json for .net
into Google's search engine. The first hit on Google is Json.NET - Home, which sounds about right. As we all know, the first hit is not necessarily the best choice when searching for third-party libraries, but in this case we got lucky. Following the first hit, we are forwarded to http://json.codeplex.com/. After reading the description, we are sure that this is the appropriate library for our problem. So, we will find a download button and transfer the archived files to the computer. After opening the archived file, we will see two folders: Bin
and Source
. We decide that we will not be needing the library's source code; let us just choose the binary assembly and reference it from our project. In the Bin
folder, we see another subset of folders with platform names as shown in the following screenshot; so again, we have to choose what to use in our code:

Since we are writing our application in .NET Framework 4.5, files in the Net45
folder should be the right ones. But where should we put these files? There are no clear guidelines about how and where external references should be stored. In our root solution folder we should create a folder that will contain our external references. Let's name our newly created folder ExternalReferences
and place the assemblies there.
Now we are set to add a reference in our project:
Choose Add Reference from the context menu in Solution Explorer on the References node.
Use the Browse button to select our assembly file from the file dialog box. The assembly file is located in the
ExternalReferences
folder in our project's root folder.Click on the OK button to confirm the selection and add the assembly to the project.
Now we are ready to use the Newtonsoft.Json
library for JSON manipulations. By changing our source code, we are able to get more useful information from our web service result. Let's make changes to our Main
method, so it will look as shown:
static void Main(string[] args) { var request = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=nuget"; string result; using (var webClient = new WebClient()) { result = webClient.DownloadString(request); } // Deserializing JSON string to object dynamic data = JsonConvert.DeserializeObject(result); // Looping throughout results foreach (var item in data.responseData.results) { Console.WriteLine("{0} {1}", item.titleNoFormatting, item.url); } }
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We used a method from our recently-added JsonConvert.DeserializeObject
library. This code is written in .Net 4.5 and we can use the dynamic type for our result.
Tip
The dynamic
keyword is also available in .Net 4.0; more about the dynamic
keyword is available at http://bit.ly/csdynmc.
In the foreach
loop, we are looping through results and displaying the titleNoFormatting
and url
properties of results, which are our search results. Running the application outputs the following to the console window:
NuGet Gallery | Home http://nuget.org/ NuGet - Home http://nuget.codeplex.com/ NuGet - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/NuGet NuGet Package Manager extension - Visual Studio Gallery - Microsoft http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
This library did not require editing of the configuration file, which is usually the most time-consuming step when using third-party libraries. Now, we have added a reference manually and successfully used it in our project. In the next chapter, we will learn how to set up NuGet in a Visual Studio environment; then we will take a look at how to add references using the NuGet Package Management.
This section will cover setting up NuGet in your development environment. If you are using Visual Studio 2012, you can skip it. NuGet client is a part of Visual Studio 2012 and it is fully integrated by default.
Let's start with the operating system requirements. PowerShell 2.0 or later is required by NuGet Package Manager Console. It is already installed on the following operating systems:
Windows 8/8.1
Windows 7
Windows Server 2008 R2
If you are using an older version of Windows, you have to install PowerShell 2.0 manually. This is required for the following systems:
Windows XP SP3
Windows Server 2008
Windows Vista SP1
Windows Server 2003 R2
Tip
Installation of PowerShell 2.0 is not a subject of this book. The detailed PowerShell 2.0 installation procedure can be found at http://bit.ly/PS20instll.
Visual Studio 2010 requires installation of NuGet Package Manager. First let us check if the NuGet extension is already installed in your Visual Studio. If NuGet is already installed, there should be Library Package Manager under the Tools menu.
You can install NuGet from Microsoft's Visual Studio gallery by performing the following steps:
Downloading and running the VSIX file from http://bit.ly/ngtvsix should bring up the VSIX Installer.
After selecting the Visual Studio instances where you wish to install NuGet Package Manager, you need to agree with the terms and click on the Install button.
After the installation is complete, a restart of Visual Studio is required. Once Visual Studio restarts, NuGet is ready to use.
We can install NuGet Package Manager from Visual Studio 2010 using the Extension Manager, as follows:
Navigating to Tools | Extension Manager brings up an Extension Manager dialog box.
Selecting the Online Gallery tab from the left side of the dialog box shows us all the available extensions from the Visual Studio Gallery.
Type
nuget
in the search box to find the NuGet Package Manager extension.When NuGet Package Manager is selected, the Download button appears; and after clicking on it, we start the installation process described in the previous section.
By using the NuGet.exe
command-line utility, we can interact with NuGet directly from the command line. The NuGet.exe
utility is available for download at http://bit.ly/nugetdl. When the downloading is complete, we would recommend adding NuGet.exe
to the PATH
environment variable.
Note
How to add a tool to the PATH
environment is described at http://bit.ly/pathset.
Now it is time to open the command prompt and start using the NuGet command-line utility. Just by typing nuget
we get a list of available commands.
In this section, we will introduce a way of adding libraries with NuGet. Assuming you have successfully installed NuGet to your environment, you are now ready to start with a new project.
We are going to create a new empty console application, just like we did in the previous demo. In Visual Studio, perform the following steps:
Navigate to File | New Project | Console Application.
Name the project
CH1_02_GoogleApiSearcherNuget
and then confirm by clicking on the OK button.
When the project is created, a Program.cs
source file with an empty Main
method is opened in the text editor. In Solution Explorer our project's tree view is displayed. Right-clicking on the References node brings up the context menu, which contains three different menu items for adding a reference:
Add Reference…
Add Service Reference
Manage NuGet Packages…
In the previous example we added a reference using the first option. Now our goal is to add a library using NuGet. Selecting Manage NuGet Packages… opens the dialog box, where we are managing all the packages related to the selected project. By default, the dialog opens on the Installed packages view, which is empty in our case since we have not added any packages yet. Selecting the
Online option from the left-hand side menu lists every available package in the NuGet official package source. There are a lot of packages in this source; using the Search online textbox we can narrow down the results. Typing json
into the textbox will automatically trigger a query on the NuGet feed, returning only the packages related to json
. The list view in the middle of a dialog contains the search results. When selecting an item in the list view, the Install button appears. On the details pane on the right side, we can see all the important information about the selected package, for example, who is the creator, what is the package version, links to the project sites, library terms, and dependencies.
Let us select Json.NET and then click on the Install button. After a couple of progress bars, a green check icon appears on the package, meaning the package is installed in our project, as shown in the following screenshot:

Now we can re-use the code from the previous sample and compile the solution. Output is the same as that of the previous program, only this time we spent a lot less time for adding the reference.
By adding a NuGet package, we gained two files. The first file is the assembly under the References
folder and the other is packages.config
in our project's root. Information about our packages is stored in the packages.config
file. For each package there is a unique package ID, version, and target framework version. We will see how NuGet uses this information in the next chapter.
In this section, I would like to cover how NuGet handles dependencies. Let us continue with our solution from the previous section. If we want to create a portable class library from our project, we will not have the WebClient
class available to us.
Tip
Using the Portable Class Library project you can create assemblies that work on multiple .NET Framework platforms. More information about cross-platform development is available at http://bit.ly/pcb_net.
The problem is solved using the NuGet package called Microsoft.Net.Http
. Perform the following steps:
In Solution Explorer, right-click on the References node and then select Manage NuGet Packages….
Search for
httpclient
in the Online tab; when the search is complete, select Microsoft HTTP Client Libraries.
In the package summary window under Description and Tags, we can see that this package has two dependencies: Microsoft.Bcl and Microsoft.Bcl.Build. This means that these two libraries must be installed while installing the package Microsoft HTTP Client Libraries. Let us install this package and accept terms when prompted. This time we gained three extra lines in our packages.config
file: one for our package and two dependency packages that are required for our package.
Now we can use HttpClient
instead of WebClient
. Instead of the following code:
using (var webClient = new WebClient()) { result = webClient.DownloadString(request); }
Use the following code:
using (var webClient = new HttpClient()) { result = webClient.GetStringAsync(request).Result; }
It should produce the same result. GetStringAsync
is a task-based asynchronous pattern method. For the sake of simplicity, we are calling the Result
property, which triggers synchronous execution. More about this pattern is available at http://bit.ly/taskasync.
This chapter has introduced NuGet and covered many of its benefits. We have briefly described the manageability problems with third-party libraries without NuGet and how NuGet solves these issues. We have also described the installation process for NuGet and all the tools required for the development environment. We added an external library manually by following a step-by-step tutorial. We concluded with a tutorial where we used NuGet to achieve the same result; we also used NuGet to add a library with dependencies on other libraries. In the next chapter, we will take a dive deep into the NuGet features such as updating referenced third-party libraries, multitarget platform support, and using NuGet with source control.