Nuget Essentials








Justin James

Code: github.com/digitaldrummerj/NugetTalk/  
Blog: digitaldrummerj.azurewebsites.net  
Email: digitaldrummerj at gmail.com
Twitter: @digitaldrummerj  

Topics

Why I should care

Consuming Packages

Creating Packages

Advanced Creating Packages

Hosting your own package feed

Other Projects

More Information

What is the heck Nuget?

.NET Package Manager integrated into Visual Studio 

Easy way to quickly add:            
  • references   
  • source files 
  • update config files
  • run powershell scripts

On uninstall reverses changes made to the project

Integrated into Visual Studio or command line

Package extension is .nupkg

Powershell 2.0 is required.

Possible Package Locations


Source can be a URL or folder path

Default Source:  https://www.nuget.org/api/v2/

Add/Update/Delete/Disable Sources 
Tools -> Options -> Package Manager -> Package Sources 

-Source switch for nuget commands to change source 

Finding Packages


In Visual Studio under Tools -> Nuget Package Manager: 

  • Manage Nuget Packages for Solution 
  • Package Manager Console 

or 

In Solution Explorer, right click on project, select Manage Nuget Packages 

or 

http://nuget.org/

Installing Nuget


VS2010 - Available thru VS Extension Manager

VS2012+ - included with every edition by default

WebMatrix 3 - integrated with the id of "NuGetPackageManager"

Command Line - Can be downloaded at http://nuget.org/nuget.exe



3 ways to play with packages

For Whole Solution:
Tools -> Nuget Package Manager ->  Manage Nuget Packages for Solution


For Project:
In Solution Explorer -> Right-click on project -> select Manage Nuget Packages


Powershell Based
Tools -> Nuget Package Manager ->  Package Manager Console

Common Commands

Manage Nuget Packages for Solution 
  • List / Search
  • Install 
  • Update 
  • Uninstall

PM Console Commands 
  • Install-Package 
  • Update-Package 
  • Uninstall-Package
  • Get-Package

Getting Help


All of nuget's documentation:  http://docs.nuget.org/

Package Manager Command Help

get-help nuget -> gets available nuget commands

get-help [nuget command] -> get specific command help

common help parameters:
  • -examples 
  • -detailed
  • -full
  • -online 

Package Restore

Don't store package in source control.


Use Automatic Package Restore instead 

As of NuGet 2.7, packages will be restored when a VS build begins.
Or  
Command Line: 
nuget.exe restore
nuget.exe restore contoso.sln
nuget.exe restore contoso

Demo


Nuget Commands Overview

Adding new package source 

Consuming Packages

Package Restore 

Creating Packages


Create from a project or assembly or directory

May contain: assemblies, source code to be injected, powershell scripts, executables, config files, config/source transformations, etc.

Most packages are project level but you can create solution level packages.

Can support multiple .NET framework Versions and Profiles

If publishing package publicly, need a free account at http://nuget.org/ 

Package Conventions


Package ID should be Namespace.Usage.

In general, have one package per assembly.  

Version is normally the version number of the assembly
(Major.Minor.Patch)

Standard Directories:
Tools - powershell scripts and programs accessible from PM
lib - Assemblies are added as references during install
content - files to copy to root of your project during install
build - MSBuild targets that are inserted into project file

Supporting Multiple Frameworks


can put multiple framework versions in same package

naming convention is 
[lib/content/tools]\{framework}\{version}

folder can be empty to indicate don't do anything for that version

can also target profiles by adding -[Profile Name] to the {framework} 

name is case sensitive

Basic Package Creation

Download nuget command line 
Put nuget.exe into your path

Generate from assembly
  • nuget spec MyAssembly.dll 
  • nuget pack MyAssembly.nuspec

Generate from project file 
  • nuget spec -> from the project file dir
  • nuget pack MyProject.csproj 

Generate from convention based directory
  • nuget spec package.id
  • nuget pack  package.id.nuspec

Spec Replacement Tokens



$id$ -> The Assembly Name

$version$ - version specified in the AssemblyVersion attribute

$author$ - company in the AssemblyCompany attribute

$description$ - description in the AssemblyDescription attribute

$configuration$ - build configuration (debug/release)

Include/Exclude Files

<files>
<file src="" target="" exclude="" />
</files>

src -> location of files.  
* wildcard is allowed.   
** wildcard recursive directory search.

target -> relative path to put files into

exclude -> file(s) to exclude.  
can contain semi-colon delimited list or file pattern
can use * and ** wildcards

Dependencies


<dependencies>
  <dependency id="" version="" />
</dependencies>

id -> package id

version -> package version #

Dependencies by Framework


<dependencies> 
   <group targetFramework="">
<dependency id="" version="" />
   </group>

targetFramework:
framework to use
if blank, acts as like the flat file list

Note:
can either use this model or the flat model on the previous slide but not combined.

Assembly References


<references>
  <reference file="xunit.dll" />
</references>

Assemblies in the lib directory to add to the project reference list.

works just like dependencies with either flat list or grouped.

Framework Assembly References

<frameworkAssemblies>
  <frameworkAssembly 
assemblyName="System.ServiceModel" 
targetFramework="net40" />

  <frameworkAssembly 
assemblyName="System.SomethingElse"  />
</frameworkAssemblies>


Common Nuget Pack Options

When creating from Visual Studio Project:

  • -IncludeReferencedProjects
  • -Prop Configuration=Release
  • -Build

-OutputDirectory control where the nupkg is saved to.


Using a GUI to create packages


Not everyone wants to use the command line to create package.


The Nuget Package Explorer is the GUI use for package creation.

Install using Chocolatey or http://npe.codeplex.com/


Publishing Packages


nuget setapikey [Api Key] 

nuget push <package path> [API Key] [options]

Options:
  • -Source
  • -ApiKey
  • -Timeout

Default source is nuget.org unless specified or DefaultPushSource in NuGet config file is set (%AppData%\Nuget\Nuget.config)


Demo 


Creating a nuget package from the command line.

Creating same package using Gui instead.


Transforming Config Files 

[filename].transform

- contains XML that looks like config

- contains only sections to be merged.

- only adds elements or adds attributes 

- does not change existing elements or attributes

- merged elements/attributes are removed on uninstall



Support for XDT

[filename].install.xdt
[filename].uninstall.xdt

- utilizes the XDT syntax 

- Allows manipulating of the structure instead of just merge

- xdt:Locator  element that you want to change

- xdt:Transform what to do to the elements
- Insert, InsertIfMissing, InsertAfter, InsertBefore, SetAttributes
- Remove, RemoveAll, RemoveAttributes

http://msdn.microsoft.com/en-us/library/dd465326.aspx

Transform Source Code

[filename].cs.pp

- works somewhat like project templates

- useful if package includes source code to be added to the project

- any project property may be replace in .pp file

- project name surrounded by $ 
example: $rootnamespace$

http://msdn.microsoft.com/en-us/library/vslangproj.projectproperties_properties(VS.80).aspx

Powershell Scripts

Files should be located in the tools directory

Init.ps1
- run the 1st time package is installed into solution
- runs every time solution is opened in Visual Studio
- has to be in root of tools folder else will be ignored

Install.ps1
- run each time package is installed into a project
- must have files in content or lib folders to run
- runs after Init.ps1

Uninstall.ps1
- run each time package is uninstalled or updated 

Powershell Scripts Cont.

Add this line at top of each file:
param($installPath, $toolsPath, $package, $project)

$installPath - path to the folder where package is installed

$toolsPath - path to tools directory

$package - reference to the package object

$project -  reference to EnvDTE project object  and  null in Init.ps1

Helper Package to see values: NuGetPsVariables
- writes above values to log file and then uninstall itself

Demo

NsGetPsVariables

Config / Source Transforms

Install / Uninstall   Powershell Scripts 

Testing XDT Transforms

Script to Increment Package Version



Hosting Your Own Nuget Feed


Local Feed: point at a folder on your system

Remote Feeds:  You can host a remote feed on a server that runs IIS.
- use Nuget.Server package

Can also host nuget gallery locally

Demo 


Creating Remote Feed

Other projects using nuget


Chocolatey - windows package manager

BoxStarter - use chocolatey.  better way to setup new machine

Resharper Extension Manager - uses custom NuGet Gallery 

JetBrains TeamCity - consume, create, publish tasks 

MyGet - NuGet server to create/host you own feeds.

OctopusDeploy - convention-based automated deployment

SymbolSource - debug packages by downloading symbols/source

More Information

Main NuGet Web Site and Package Repository
http://nuget.org/ 

Documentation
http://docs.nuget.org/ 

NuGet Team Blog
http://blog.nuget.org/

Apps Built On Top of Nuget
http://docs.nuget.org/docs/reference/ecosystem

Twitter Feed of Latest Packages
https://twitter.com/NuGetLatest

Books



Pro NuGet (Amazon Link)

Nuget 2 Essentials (Amazon Link)

Questions?


Come to my talk on Chocolatey @ 2:15 in room 230


Blog: randomcoder.azurewebsites.net

Email: digitaldrummerj at gmail.com

Twitter: @digitaldrummerj


Backup

Installing Packages


In Solution Explorer: 

  • Right click on project or solution 
  • Select Manage Nuget Packages
  • Select Online-> All or specific source
  • Select for the package you want
  • Click Install ( Always installs latest version)

In Package Manager Console:

  • Install-Package [Package Name]
  • Install-Package [Package Name] -Version [Version #]

Updating Packages


In Solution Explorer: 
  • Right click on project or solution 
  • Select Manage Nuget Packages
  • Select Updates -> All or specific source

In Package Manager Console:
  • Update-Package [Package Name] -> Specific Package
  • Update-Package  -> All packages

Warning: Update-Package with no parameters will update each package to latest version regardless of dependency version.

Warning #2:  Update uninstalls previous version before install

Uninstall Package

In Solution Explorer: 
  • Right click on project or solution 
  • Select Manage Nuget Packages
  • Select Installed Packages 
  • Select Package to Uninstall
  • Click Uninstall

In Package Manager Console:
  • Uninstall-Package [Package Name] 

Note: You can not delete packages that are a dependency to another package

Re-Install Packages

Best accomplished in the package manager console

In Manage Nuget Packages: 
  • Would have to uninstall package and then go install package

In Package Manager Console:
The -Reinstall switch will uninstall and install package(s) including dependencies.

  • Update-Package [Package Name] -Reinstall -> Specific Package
  • Update-Package  -Reinstall -> All packages


Framework and Profiles

Framework:
.NET Framework -> net
Silverlight -> sl
.NET Micro Framework -> netmf
Windows Phone 8 -> windowsphone8

Profiles:

Client -> client
Windows Phone 7 -> wp
Compact Framework -> cf
Full -> full

Framework Versions Examples

.NET 3.5 -> net35
.NET 4.0 -> net40

.NET 3.5 Client - net35-client
.NET 4.0 Full -> net40-full

Silverlight 3 -> sl3

windows phone 8 -> windowsphone8

Portable Class Library for Windows Store App & .NET 4.5 -> portable-windows8+net45

Full Docs

Useful PM Console Switches

-ProjectName -> specific projects to take action on

-Version -> version of package to use.  default latest

-WhatIf -> displays the actions that would be taken

-Source -> specifics url or directory path to use





Automate Builds


Check in nuget.exe to version control

Before building any projects run 
nuget.exe restore path\to\Solution.sln

Note: make sure that packages directory 
is excluded from version control.

Updating nuget


Visual Studio Tools -> Extensions and Updates

Package Manager Console -> nuget update -self

What does a nuget package do?


Includes everything necessary to install a library or tool 

Installs package dependencies

Can copy files to your solution 

Can add references

Can update app.config / web.config

Can run powershell scripts including in the package

On uninstall, removes files, and reverses changes made in the project