Nuget is easier than you think 

and 

you should be using it.




By
Justin James


About Me


My name is Justin James.  I'm a software craftsman building  applications in ASP.NET and C# at Intel.  I have been using .NET since the 1.0 beta days.  

You can find all of my presentations at 
http://www.slides.com/digitaldrummerj

Code Demos
github.com/digitaldrummerj/NugetTalk

Follow me on twitter 
@digitaldrummerj

Topics


Nuget Feature Overview

Consuming Packages

Creating Packages

Advanced Creating Packages

Hosting your own package feed

Other Projects using Nuget

More Information

Quick Survey

How many of you have consumed a nuget package?

How many of you have created your own nuget packages?

How many have hosted your own nuget package feed?

What is the heck Nuget?

Package Manager for .NET  

Allows easy sharing of libraries, code, configurations

GUI is integrated into Visual Studio or Command line 

Where can I get nuget packages?


Public Gallery: http://www.nuget.org/packages 

Public Feed:  https://www.nuget.org/api/v2/

 

A package source can be any URL or folder path


You can have multiple sources configured

What happens when I consume a package?


  1. Looks at package  dependencies to figure out what is installed 
  2. Downloads any missing dependencies and installs them
  3. Downloads package and installs it
  4. package.config file created in project folder
  5. repositories.config file is created in the packages folder

Note: The packages are store in a packages folder within the same directory as the <Your Solution>.sln

What does install a package mean?


  1. If package is used before then Uninstall.ps1 is run
  2. References, Source Files, and Config changes are removed
  3. A folder for each package is created in the package folder
  4. Package is uncompressed
  5. Any dll in the lib folder is added as a reference
  6. Anything in the content folder are copied into the project
  7. Files with a .pp extensions are transformed into source files
  8. Xml files with a .transform extension are merged
  9. Xml files with a (un)install.xdt are transformed
  10. Init.ps1 is run
  11. Install.ps1 is run

 

Note: Powershell scripts are optional

What happens when I build a solution?


From within visual studio
Missing packages will automatically be downloaded before the 1st project is built

Using MSBuild:
run nuget.exe restore in the sln directory to download missing packages

Demo


UI Overview

Nuget Commands Overview

Consuming Packages

Package Restore 

Creating Packages Topics


Basic Package Creation

Supporting Multiple Frameworks

Update Configuration Files

Include Source Code 

Install/Uninstall Scripts



Creating Packages Overview

Can create from:
  • project
  • assembly 
  • directory 

Most packages are project level  

Can support multiple .NET framework Versions and Profiles 

Creating Packages Overview

May contain: 
  • assemblies
  • source code
  • powershell scripts
  • executables
  • config files
  • config/source transformations



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

Solution level Packages

Installs a tool or additional commands for the Package Manager console

Does not add references, content, or build customizations to any projects in your solution. 

A package is considered a solution-level package if it and it dependencies do not contain any files in its lib, content, or build directories. 

Tracked in a packages.config file in the .nuget directory, rather than in a packages.config file in a specific project.

Example: psake package

Package Conventions

Nuget uses convention over configuration approach

In general, have one package per assembly.  

Package ID and Version are the identifiers used in the package feed

Version is normally the version number of the assembly

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

supports multiple frameworks in same package

can target any .NET profiles (client, full, compact)

Framework name is case sensitive

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

Examples
lib\net20 to support .NET 2.0
lib\net40-client to support .NET 4.0 client profile

Note:  empty folder indicates don't do anything for that version

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

Example Nuget Spec Non-VS

 <?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>log4net.blank.config</id>
    <version>1.0.0</version>
    <title>Log4Net Blank Configuration File</title>
    <authors>Justin James</authors>
    <owners>Justin James</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Inserts a blank log4net.config file.</description>
    <summary>Log4Net Blank Configuration File</summary>
    <releaseNotes>Initial Rev</releaseNotes>
    <dependencies>
      <dependency id="log4net" version="2.0.3" />
    </dependencies>
  </metadata>                                                                                                                                                                                                                                                                                                                                                                                            

  <files>
    <file src="**" exclude="build.cmd" />
  </files>
</package>

Example Nuget Spec - VS

<?xml version="1.0"?>
<package >
  <metadata>
    <id>$id$</id>
    <version>$version$</version>
    <title>$title$</title>
    <authors>$author$</authors>
    <owners>$author$</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>$description$</description>
    <releaseNotes> Summary of changes made in this release.</releaseNotes>
    <copyright>Copyright 2014</copyright>
    <tags>Demo</tags>
  </metadata>
</package>

Common Nuget Pack Options

Against 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/


Questions on Creation Basics?


Coming Up:

Updating Configuration Files

Including Source Code

Powershell Scripts

2 ways to update configs files

Include a [filename].transform is xml based like a config file

or

Utilize XDT Transforms with 
[filename].install.xdt
[filename].uninstall.xdt

[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



[Filename].*.xdt

- utilizes the XDT syntax
same syntax as web.config.debug/release 

- 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

Transform Source Code

[filename].cs.pp

- works somewhat like project templates

- any project property may be replace in .pp file

- property name surrounded by $ 
example: $rootnamespace$

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

Creating a nuget package from the command line.

Creating same package using Gui instead.

Config / Source Transforms

Install / Uninstall  Powershell Scripts 

Testing XDT Transforms

Script to Increment Package Version

NuGetPsVariables

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.


Can also host nuget gallery locally

Tell Everyone about the Feed

Create a Nuget.Config file

Defines nuget configuration includes sources.

Loads from the default location
then loads any file named NuGet.config  starting 
from the  root of the current drive 
and ending in the current directory.

Default Location: %AppData%\Nuget\Nuget.Config

Demo 


Creating Remote Feed

Adding new package source 

Nuget.config overview

Updating nuget


Visual Studio Tools -> Extensions and Updates

Command Line -> nuget update -self

Nuget vNext (aka 3.0) 

Totally redesigned UI

  • Consolidated installed/online/updates views together
  • Version selection for installs/updates within UI
  • WhatIf available in the UI
  • Control over dependency version selection
  • Open for multiple projects at once
  • Ability to leave UI open


Now available in Visual Studio 2015

Other projects using nuget


Chocolatey - windows package manager

BoxStarter - uses 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

Documentation

NuGet Team Blog

Apps Built On Top of Nuget

Twitter Feed of Latest Packages

Books



Pro NuGet (Amazon Link)

Nuget 2 Essentials (Amazon Link)

Questions?


Blog: digitaldrummerj.azurewebsites.net

Email: digitaldrummerj at gmail.com

Twitter: @digitaldrummerj

Slides: http://www.slides.com/digitaldrummerj

Backup

What does a nupkg 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

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

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

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)

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 

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 #]

Common Commands

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

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

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


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





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)


Hosting Remote Feed in Azure 



or 


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 

Can be grouped by Framework by putting in 
  • <group targetFramework=""></group>
  • if framework blank, acts as like the flat file list

Note: can either be grouped or  flat but not mixed.

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.

Can be grouped by Framework by putting in 
  • <group targetFramework=""></group>
  • if framework blank, acts as like the flat file list

Note: can either be grouped or  flat but not mixed.

Framework Assembly References

You can also reference Framework assemblies that are installed in the GAC

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


Can specify multiple frameworks by separating by comma

if left blank, always add

UI Preview



NuGet

By Justin James

NuGet

Teaching you how to use NuGet and why you should use it.

  • 4,487