NuGet 2 Essentials

By Damir Arh , Dejan Dakić
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

NuGet has made the process of finding and referencing libraries from Visual Studio much easier and has strongly contributed to the expansion of an open source ecosystem. In the three years since its release, it has become an essential tool for both consuming and publishing class libraries for the .NET framework.

A concise and practical guide to everything that NuGet has to offer to both consumers and publishers. Through many hands on examples, NuGet2 Essentials will demonstrate all of NuGet’s features and teach you how to use them in everyday development in a .NET framework.

Starting out by using NuGet for consuming third-party libraries, this concise guide continues with a detailed look at creating your own packages, and ends by teaching you how to set up your own internal server. Through practical examples, you will learn to manage versions of installed libraries on all development and build machines. You will also discover how to create packages for your own libraries so they can be easily consumed, no matter how much configuration they require. By hosting an internal server, you will have full control of packages being used in your development environment.


By the end of the book, you will know about everything that NuGet has to offer, and how it can make your development process better.

Publication date:
November 2013
Publisher
Packt
Pages
116
ISBN
9781782165866

 

Chapter 1. Using a Package Manager in Visual Studio

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.

 

Benefits of using a package manager


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.

 

Manually adding third-party library references


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:

  1. In Visual Studio 2012, navigate to File | New Project.

  2. In the New Project dialog, choose the Console Application Visual C# template.

  3. 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:

  1. Choose Add Reference from the context menu in Solution Explorer on the References node.

  2. 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.

  3. 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.

 

Setting up NuGet in Visual Studio


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.

Requirements

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.

Installing NuGet

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.

Installing from the Visual Studio gallery

You can install NuGet from Microsoft's Visual Studio gallery by performing the following steps:

  1. Downloading and running the VSIX file from http://bit.ly/ngtvsix should bring up the VSIX Installer.

  2. 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.

  3. After the installation is complete, a restart of Visual Studio is required. Once Visual Studio restarts, NuGet is ready to use.

Installing from the Extension Manager

We can install NuGet Package Manager from Visual Studio 2010 using the Extension Manager, as follows:

  1. Navigating to Tools | Extension Manager brings up an Extension Manager dialog box.

  2. Selecting the Online Gallery tab from the left side of the dialog box shows us all the available extensions from the Visual Studio Gallery.

  3. Type nuget in the search box to find the NuGet Package Manager extension.

  4. 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.

Installing the command-line utility

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.

 

Adding references to third-party libraries using NuGet


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:

  1. Navigate to File | New Project | Console Application.

  2. 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.

Dependencies with NuGet

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:

  1. In Solution Explorer, right-click on the References node and then select Manage NuGet Packages….

  2. 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.

 

Summary


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.

About the Authors

  • Damir Arh

    Damir Arh is a software architect and developer, who is interested in using new technologies and methodologies to make development processes more efficient and improve the user experience in software.

    He is a big proponent of TDD (test-driven development) and unit testing in general. He regularly uses NUnit and MsTest unit testing frameworks and is very fond of the NCrunch continuous testing tool. It really changes the way you look at unit tests.

    He has a lot of experience with setting up continuous integration servers (CruiseControl.NET and TeamCity), and has used and administered different source control tools (SVN, GIT, TFS, and VSS).

    He has been working with Microsoft development tools all of his professional career. He has lots of experience with most parts of the .NET framework: client-side (WPF, Windows Forms), server-side (WCF, WF, and ASP.NET), and data access (ADO.NET, Entity Framework).

    Lately, he has been very interested in mobile platforms, such as WinRT and Windows Phone. He has been a fan of Portable Class Libraries since they were first released.

    In the past, he spent a lot of time in the field of COM-.NET interoperability, as well as with Word and Excel automation.

    He is also experienced with all aspects of SQL Server (Database Services, Analysis Services, DTS, and Integrations Services).

    He loves to share his knowledge with other developers. He is a speaker at local events (Microsoft NT conference, Bleeding Edge, and local user group meetings). He regularly posts on his blog and is an active user on Stack Overflow.

    Browse publications by this author
  • Dejan Dakić

    Dejan Dakić has been working with the .NET Framework for over five years. He has the most experience with ASP.NET but has also done a lot of work in Windows Forms and WPF. He has been active in mobile development since Windows Mobile, and now he has progressed to Windows RT. Lately, he has been spending time in the Windows Azure environment, focusing on web development, both client- and server-side. Currently, he works in a team with Damir as a software developer for Adacta—a company specializing in development of software for insurance companies, which is based in Ljubljana, Slovenia.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Start FREE trial