Tải bản đầy đủ
Objective 5.4: Manage packages by NuGet

Objective 5.4: Manage packages by NuGet

Tải bản đầy đủ

You are expected to know how to manage packages with NuGet for the exam. You should
also be able to define the necessary steps for creating your own NuGet feed. This section
explains how NuGet as a package manager manages libraries internally and externally, and
ensures that you can consume them with minimal effort.

This objective covers how to:
■■

Install and update an existing NuGet package

■■

Create and configure a NuGet package

■■

Connect to a local repository cache

■■

Set up your own package repository

Installing and updating an existing NuGet package
At http://nuget.org, you can find the NuGet gallery. This gallery contains all packages that are
currently available. At the time of writing, there are tens of thousands of packages that are
downloaded millions of times.
As you can see, this offers you a wealth of potentially useful packages that you can use
in your own projects. Almost all popular frameworks, such as jQuery, Json.NET, or the Entity
Framework, are available from NuGet. If the exam asks you to reference a popular library, you
should immediately think of NuGet.
Starting with Visual Studio 2012, the project templates are based on NuGet packages.
Instead of distributing one fixed version of a library with Visual Studio, Microsoft chose to use
the packages available from NuGet in its templates.
If you create a new ASP.NET MVC project based on the Internet template in Visual Studio
2012, you get a file called packages.config in the root of your project. You can see the contents of this file in Listing 5-1.
LISTING 5-1  packages.config




targetFramework="net45" />
/>
/>
targetFramework="net45" />




394

CHAPTER 5

Deploying web applications and services




targetFramework="net45" />

targetFramework="net45" />

targetFramework="net45" />
targetFramework="net45" />

targetFramework="net45" />
/>
targetFramework="net45" />
targetFramework="net45" />
targetFramework="net45" />


targetFramework="net45" />
targetFramework="net45" />

/>






As you can see, a typical ASP.NET MVC project uses quite a lot of packages. Packages can
contain all types of content. Some packages consist of a set of assemblies that are automatically referenced when you add them to your project. Others contain JavaScript and CSS files
that are added to the correct folders in your project. Other packages modify your web.config
file or add code to your project.
EXAM TIP

Remember that a NuGet package is not only about adding references to your project. A
NuGet package can contain all kinds of data, such as code or script files and even configuration changes that can be added to your project.



Objective 5.4: Manage packages by using NuGet

CHAPTER 5

395

This also makes it clear why NuGet is so popular. Instead of having to manually download
assemblies, reference them in your project, change some configuration settings, and write
some code, this can all be done in an automated way using NuGet.

Using the Manage NuGet Packages window
You can use Visual Studio to get a more graphical view of the packages you have installed in
a project or in your solution by opening the Manage NuGet Packages window. To view all the
packages in your solution, open it from Tools → Library Package Manager → Manage NuGet
Packages for solutions. As you can see in Figure 5-11, this window shows the packages you
have installed in your solution.

FIGURE 5-11  The Manage NuGet Packages window in Visual Studio

To view the installed packages for only one project, you can right-click the References
folder in Solution Explorer and choose Manage NuGet Packages. Both windows look identical.
The only difference is that the solution-wide option lets you select which projects you want to
apply changes to.
You can use the NuGet package window to install new packages. By selecting the Online
option, you can search the NuGet gallery directly from Visual Studio and select the packages
you want to install.
You also see an Update tab in the window. When you select this tab, Visual Studio will determine whether there are updates for any of the packages you have installed in your project.
You can then easily update your packages to the newest version.

396

CHAPTER 5

Deploying web applications and services

One big advantage of using NuGet to install a package is that it automatically detects any
required dependencies and installs them together with your package. This way, you never
have to manually search for any dependencies or other prerequisites. This is all taken care of
for you by NuGet.

Package Manager Console
The Manage NuGet Packages window is one option to install packages into your solution. You
can also use the Package Manager Console. This console is a Windows PowerShell window
that’s integrated into Visual Studio. By opening this console, you can execute commands to
install, update, and remove packages. Figure 5-12 shows how this console looks when you
open it for the first time.

FIGURE 5-12  Package Manager Console

Let’s say you want to add a new package to your project. You can do this from the console
by using the install-package command. For example, the following line adds Ninject (a dependency injection library) to your project:
Install-package Ninject

After executing this command (by hitting Enter), you get the following result:
You are downloading Ninject from Ninject Project Contributors, the license
agreement to which is available at https://github.com/ninject/ninject/raw/master/
LICENSE.txt. Check the package for additional dependencies, which may come
with their own license agreement(s). Your use of the package and dependencies
constitutes your acceptance of their license agreements. If you do not accept the
license agreement(s), then delete the relevant components from your device.
Successfully installed 'Ninject 3.0.1.10'.
Successfully added 'Ninject 3.0.1.10' to NuGetTest.

If you now look in your References folder, you see a new reference to a Ninject assembly.
This assembly is located in your solution folder in a folder called packages. Each package is
downloaded to a folder and referenced from your project.
When you type in the Package Manager Console, it’s sometimes hard to remember the
exact name of a command or the name of a package. You can use the Tab key to show a


Objective 5.4: Manage packages by using NuGet

CHAPTER 5

397

drop-down list with possible options. If you type i and then press Tab, you get a drop-down
list for all commands starting with the letter “i”. You can then scroll through this list and pick
the command you want. If there is only one option left pressing Tab automatically selects
that option. So if you type install-p and then press Tab, it automatically expands to InstallPackage.
The same trick works when selecting a package name. Pressing Tab displays a list of packages that you can use to find the package you are looking for.
You can remove a package from your project by using the uninstall-package command. If
you want to remove Ninject, use the following line:
Uninstall-Package Ninject

This code removes the package from your packages.config file, removes the reference
from your project, and deletes the folder from your packages folder. If your package install
made more changes, to your app.config file, for example, all those changes will be removed
so your package doesn’t leave any clutter. If dependencies were installed for you, they are not
automatically removed when uninstalling the package.
You can also update a package from the console by using the Update-Package command
like this:
Update-Package Ninject

If you want to update all packages in all projects in your solution, you can use this:
Update-Package

If you want to update only the packages in a specific project, you can use the –Project
parameter to specify the project name:
Update-Package -Project NuGetTest

By default, all the commands you run will execute against the first project in your solution.
This is the project name displayed in the Default Project drop-down list in the console window. By changing this drop-down list, you can target another project with your commands or
use the –Project parameter to select a different project.
Some packages also offer extra commands that are integrated into the console. For example, after you install the Entity Framework (EF) package, you can use commands such as
Enable-Migrations, Add-Migration, and Update-Database to use Code First Migrations.
MORE INFO  NUGET WINDOWS POWERSHELL REFERENCE

For a list of the available Windows PowerShell commands and their parameters in NuGet,
see http://docs.nuget.org/docs/Reference/Package-Manager-Console-PowerShell-Reference.

398

CHAPTER 5

Deploying web applications and services

Sharing packages with your team
Including all the packages that you install into your project in your source control is not a best
practice. All this package data needs to be stored on your source control server and has to be
downloaded to each user who accesses your project. If you forget to add a package to source
control, other users will get compile errors because of missing packages.
When you right-click your solution file in Visual Studio, you can Enable Package Restore
On Build. A solution folder called .nuget is added that contains the NuGet.exe file. If you now
build your project, NuGet will see whether all packages are correctly downloaded. If a package is missing, it will download it from NuGet and add it to the packages folder. This way you
can be sure that everyone has all the required packages installed without having to share the
packages through source control.
If you want to change the default location of where packages are installed, you can do this
through a configuration file. You do this by adding a nuget.config file to your solution with
the following content:

 
   
 



Creating and configuring a NuGet package
NuGet is based on the idea that everyone can add new packages to the NuGet gallery. This
means that if you have a project of your own that you want to share with others, you can easily add it to the official NuGet gallery so everyone can access it.

Understanding the content of a package
A NuGet package is described by a package manifest, the nuspec file. This file uses XML to
describe your package. It contains information such as the version, title, author(s), description,
release notes, and dependencies of your package. A nuspec file looks something like this:


 
    sample
    1.0.0
    Microsoft
   
     
     
   

 





Objective 5.4: Manage packages by using NuGet

CHAPTER 5

399

MORE INFO  NUSPEC REFERENCE

For a list of all the elements that you can use in a nuspec file, see http://docs.nuget.org/
docs/reference/nuspec-reference.

In addition to this manifest file, the package contains your assemblies, content files, and
other tools that you want to distribute. NuGet follows a convention over configuration approach, meaning that you don’t need to configure a lot of settings if you just follow some
simple rules. One of those rules is the way in which you structure your package. You can use
the following three folders:
■■

\lib

■■

\content

■■

\tools

The lib folder is used for your assemblies. If you target different platforms (for example,
Windows Phone, Windows Store, and the full .NET Framework) you can use subfolders to
separate those versions of your project, following the NuGet naming convention.
The content folder can contain files such as configuration files, images, JavaScript files,
Cascading Style Sheets (CSS), or other files that you want to distribute with your package. All
files contained in your content folder will be included in your project. This means that if you
have an image file in \content\images\myimg.png, this file will end up as \images\myimg.png
in the target project.
The files you put in the content folder can also be used to apply transformations to
your configuration files. If you create a file called app.config.transformation or web.config.
transformation, NuGet will use those files during installation to apply changes to the configuration files. It does so by adding the XML elements from your transformation files that are
missing in the target files.
Transformations can also be used on code files. You create a file with a .cs.pp extension
such as MyUtil.cs.pp, and add it to the content folder in your package. Maybe you want to
add code to the Global.asax file or add some classes to the project. Transformations are most
often used to insert the correct namespace when adding code.
The following file uses the $rootnamespace$ token to make sure that the correct
namespace is used:
namespace $rootnamespace$.Models
{
    public class Person
{
        public string FirstName;
        public string LastName;   
}
}

400

CHAPTER 5

Deploying web applications and services

MORE INFO  CODE TRANSFORMATION TOKENS

For a list of all the tokens that you can use in a code transformation, see http://msdn.microsoft.com/en-us/library/vslangproj.projectproperties_properties.aspx.

Next to the lib and content folders, you can also use a tools folder. In this folder, you
can put Windows PowerShell scripts that run when your package is loaded, installed, and
uninstalled:
■■

Init.ps1 runs every time a solution that contains your package is loaded.

■■

Install.ps1 runs when your package is installed into a solution.

■■

Uninstall.ps1 runs when your package is uninstalled.

If your package doesn’t have anything in the content and lib folders, it is considered as a
solution level package. You can use it if all you want to do is add commands to the Package
Manager Console.
For example, if you install the EF package in your project, you get the following content for
the tools folder:
■■

EntityFramework.PowerShell.dll

■■

EntityFramework.PowerShell.Utility.dll

■■

EntityFramework.PS3.psd1

■■

EntityFramework.psd1

■■

EntityFramework.psm1

■■

init.ps1

■■

install.ps1

■■

migrate.exe

■■

Redirect.config

■■

Redirect.VS11.config

The EF team created init.ps1 and install.ps1 files that are called by NuGet. The install file
is run only once and initializes a ConnectionFactoryConfigurator. The init file is called every
time the EF package is loaded in a solution. This file makes sure that all EF–specific Windows
PowerShell commands are added to the NuGet Package Manager Console window. As you
can see, there is even an .exe file that is a part of the package.

Creating your own NuGet package
You can create your own NuGet packages by using the command line or by using a visual designer. If you want to use the command line, you need to make sure that you have
the NuGet.exe file (which can be downloaded from http://nuget.codeplex.com/releases/
view/58939). Make sure that you add the location of your NuGet.exe file to your path environment variable so you can use it from a command prompt.



Objective 5.4: Manage packages by using NuGet

CHAPTER 5

401

The first command you have to run is this:
NuGet Update -self

This will update your version of NuGet to the latest version. Now you can start creating
your package. If you just want to create a package from an assembly, you can run the following command:
nuget spec MyAssembly.dll

This code creates a MyAssembly.nuspec file for you that contains your manifest. You can
now edit this file to make sure that things such as the title and description and the dependencies are correct. After that, you can create your package:
nuget pack MyAssembly.nuspec

This code results in a MyAssembly.dll.1.0.0.nupkg package file. You can now test your
package from Visual Studio by opening a project and executing the following command from
the Package Manager Console:
install-package MyAssembly.dll -Source "C:\"

If you now look at the references of your project, you will see that there is a new reference
to MyAssembly. You can also create a NuGet package from a Visual Studio project. You do
this by first creating a nuspec file by running the following command from the folder in which
your csproj file is located:
nuget spec

This will create a nuspec file with some special tokens such as id, version, author, and
description. The data for these tokens is loaded from your AssemblyInfo.cs file. By default, the
AssemblyInfo.cs file does not contain those tokens. You need to edit this file and add additional data or remove tokens if you want static data.
After you finish with your nuspec file, you need to create your package:
nuget pack MyProject.csproj

This code creates a package of your project file with the data that you put in your nuspec
file.
If you want to create a more complex package that uses the tools, content, and lib folders,
you need to create your package manually. You start with a default spec file created from
scratch by running this:
nuget spec

402

CHAPTER 5

Deploying web applications and services

Then you need to edit the nuspec file that’s created and fill in all the values you want. After
that, create your three folders (lib, content, and tools) and copy all the necessary files to the
correct folder. Now you can run one final NuGet command to create your package:
nuget pack YourPackage.nuspec

Now that your package is ready, you can publish it to NuGet. You need an application programming interface (API) key that you get when you register for an account on NuGet. You
can copy this API key and then configure NuGet with it:
NuGet SetApiKey Your-API-Key

Now you can run the following to publish your package to NuGet:
NuGet Push YourPackage.nupkg

If you don’t like the command line, you can also use a Windows GUI application to create
a package. You can download the package from http://nuget.codeplex.com/releases/59864/
clickOnce/NuGetPackageExplorer.application. This tool enables you to create your manifest
with a nice graphical editor. You can then add files to the tools, lib, and content folders and
press the Publish button to publish your package to NuGet.
You can also use the NuGet Package Explorer to open packages both from your local PC
and directly from the package feed. You can then read the manifest and check the content of
the package.

Setting up your own package repository
NuGet displays packages from the package sources that you have configured. When installing
Visual Studio, you get a default package reference to the official package source of NuGet.
You can add additional package sources that NuGet can use to install packages from. Maybe you have some packages that you want to share with your development team, or you want
to have a local backup of the packages that you will install for a presentation or something.
A local feed can easily be created by going to the Tools menu, selecting Library Package
Manager and then clicking Package Manager Settings. If you look at the Package Source tab,
you can see the window shown in Figure 5-13.



Objective 5.4: Manage packages by using NuGet

CHAPTER 5

403

FIGURE 5-13  The package sources options for NuGet

To add a local folder as a package source, you can click the Add button, enter a name, and
point to a folder on your computer. You then need to add your .nupkg package files to this
folder. After that, you can select your local package source from the package source dropdown list in the Package Manager Console. The feed also shows up in the Online tab of the
Manage NuGet Packages window.
You can also create a remote feed that needs to run on IIS. Of course, you can choose to
make it publicly available or only internal. You create a remote feed by starting with an empty
web application in Visual Studio. In your project, install the NuGet.Server package, which will
add all the code necessary to expose your packages as an Atom Syndication Format (ATOM)
feed.
A Packages folder is now inside your project. You can add your package files to this folder,
or you can use the appSettings element of the web.config file to configure a different path
(virtual or absolute).
If you want, you can also enable publishing to your custom remote feed, just as you can
publish packages to the official NuGet gallery. To do this, you need to add an API key to the
appSettings element. If you leave the API key empty, publishing is disabled.
That’s all that’s required. You can now deploy your application to IIS and access the feed of
available packages by navigating to http:///nuget/. If you add this URL as
a package source to the Packet Manager, you can now install packages from this server into
your projects.

404

CHAPTER 5

Deploying web applications and services