This commit is contained in:
feiling 2014-04-03 15:52:56 -07:00
Родитель ebf5c12272 8137761729
Коммит 10393e7a4c
103 изменённых файлов: 4741 добавлений и 549 удалений

Просмотреть файл

@ -53,7 +53,7 @@
build servers and those built locally. -->
<MajorVersion>2</MajorVersion>
<MinorVersion>8</MinorVersion>
<Patch>0</Patch>
<Patch>1</Patch>
<!-- Ensure that we come up with a new version every 65535 years -->
<VersionStartYear>2010</VersionStartYear>

Просмотреть файл

@ -14,8 +14,8 @@ using System.Runtime.InteropServices;
// Build\Build.proj.
// When built locally, the NuGet release version is the values specified in this file.
#if !FIXED_ASSEMBLY_VERSION
[assembly: AssemblyVersion("2.8.0.0")]
[assembly: AssemblyInformationalVersion("2.8.0")]
[assembly: AssemblyVersion("2.8.1.0")]
[assembly: AssemblyInformationalVersion("2.8.1")]
#endif
[assembly: NeutralResourcesLanguage("en-US")]

Просмотреть файл

@ -29,7 +29,7 @@ namespace NuGet
if (object.ReferenceEquals(resourceMan, null))
{
// Find the CommonResources.resources file's full resource name in this assembly
string commonResourcesName = Assembly.GetExecutingAssembly().GetManifestResourceNames().Single(s => s.EndsWith("CommonResources.resources", StringComparison.OrdinalIgnoreCase));
string commonResourcesName = Assembly.GetExecutingAssembly().GetManifestResourceNames().First(s => s.EndsWith("CommonResources.resources", StringComparison.OrdinalIgnoreCase));
// Trim off the ".resources"
commonResourcesName = commonResourcesName.Substring(0, commonResourcesName.Length - 10);

Просмотреть файл

@ -10,7 +10,55 @@ namespace NuGet
{
private const string targetName = "EnsureNuGetPackageBuildImports";
public static void AddEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
/// <summary>
/// Adds an Import element to this project file if it doesn't already exist.
/// </summary>
/// <param name="project">The project file.</param>
/// <param name="targetsPath">The path to the imported file.</param>
/// <param name="location">The location where the Import is added.</param>
public static void AddImportStatement(MsBuildProject project, string targetsPath, ProjectImportLocation location)
{
if (project.Xml.Imports == null ||
project.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
{
ProjectImportElement pie = project.Xml.AddImport(targetsPath);
pie.Condition = "Exists('" + targetsPath + "')";
if (location == ProjectImportLocation.Top)
{
// There's no public constructor to create a ProjectImportElement directly.
// So we have to cheat by adding Import at the end, then remove it and insert at the beginning
pie.Parent.RemoveChild(pie);
project.Xml.InsertBeforeChild(pie, project.Xml.FirstChild);
}
NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(project, targetsPath);
project.ReevaluateIfNecessary();
}
}
/// <summary>
/// Removes the Import element from the project file.
/// </summary>
/// <param name="project">The project file.</param>
/// <param name="targetsPath">The path to the imported file.</param>
public static void RemoveImportStatement(MsBuildProject project, string targetsPath)
{
if (project.Xml.Imports != null)
{
// search for this import statement and remove it
var importElement = project.Xml.Imports.FirstOrDefault(
import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));
if (importElement != null)
{
importElement.Parent.RemoveChild(importElement);
NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(project, targetsPath);
project.ReevaluateIfNecessary();
}
}
}
private static void AddEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
{
// get the target
var targetElement = buildProject.Xml.Targets.FirstOrDefault(
@ -37,7 +85,7 @@ namespace NuGet
errorTask.SetParameter("Text", errorText);
}
public static void RemoveEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
private static void RemoveEnsureImportedTarget(MsBuildProject buildProject, string targetsPath)
{
var targetElement = buildProject.Xml.Targets.FirstOrDefault(
target => string.Equals(target.Name, targetName, StringComparison.OrdinalIgnoreCase));

Просмотреть файл

@ -2,18 +2,25 @@ NuGet Hall of Fame
==================
## NuGet 2.8
1. [leppie](https://www.codeplex.com/site/users/view/leppie)
1. [Llewellyn Pritchard](https://www.codeplex.com/site/users/view/leppie) ([@leppie](https://twitter.com/leppie))
- [#3466](https://nuget.codeplex.com/workitem/3466) - When packing packages, verifying Id of dependency packages.
1. [maartenba](https://www.codeplex.com/site/users/view/maartenba) ([@Maarten Balliauw](https://twitter.com/maartenballiauw))
1. [Maarten Balliauw](https://www.codeplex.com/site/users/view/maartenba) ([@maartenballiauw](https://twitter.com/maartenballiauw))
- [#2379](https://nuget.codeplex.com/workitem/2379) - Remove the $metadata suffix when persistening feed credentials.
1. [FilipDeVos](https://www.codeplex.com/site/users/view/FilipDeVos) ([@Filip De Vos](https://twitter.com/foxtricks))
1. [Filip De Vos](https://www.codeplex.com/site/users/view/FilipDeVos) ([@foxtricks](https://twitter.com/foxtricks))
- [#3538](http://nuget.codeplex.com/workitem/3538) - Support specifying project file for the nuget.exe update command.
1. [jjgonzalez](https://www.codeplex.com/site/users/view/jjgonzalez)
1. [Juan Gonzalez](https://www.codeplex.com/site/users/view/jjgonzalez)
- [#3536](http://nuget.codeplex.com/workitem/3536) - Replacement tokens not passed with -IncludeReferencedProjects.
1. [Sarkie](https://www.codeplex.com/site/users/view/Sarkie)
1. [David Poole](https://www.codeplex.com/site/users/view/Sarkie) ([@Sarkie_Dave](https://twitter.com/Sarkie_Dave))
- [#3677](http://nuget.codeplex.com/workitem/3677) - Fix nuget.push throwing OutOfMemoryException when pushing large package.
1. [Despostes](https://www.codeplex.com/site/users/view/Despostes)
1. [Wouter Ouwens](https://www.codeplex.com/site/users/view/Despotes)
- [#3666](http://nuget.codeplex.com/workitem/3666) - Fix incorrect target path when project references another CLI/C++ project.
1. [Adam Ralph](http://www.codeplex.com/site/users/view/adamralph) ([@adamralph](https://twitter.com/adamralph))
- [#3639](https://nuget.codeplex.com/workitem/3639) - Allow packages to be installed as development dependencies by default
1. [David Fowler](https://www.codeplex.com/site/users/view/dfowler) ([@davidfowl](https://twitter.com/davidfowl))
- [#3717](https://nuget.codeplex.com/workitem/3717) - Remove implicit upgrades to the latest patch version
1. [Gregory Vandenbrouck](https://www.codeplex.com/site/users/view/vdbg)
- Several bug fixes and improvements for NuGet.Server, the nuget.exe mirror command, and others.
- This work was done over several months, with Gregory working with us on the right timing to integrate into master for 2.8.
## NuGet 2.7
@ -47,6 +54,8 @@ NuGet Hall of Fame
- [#3460](https://nuget.codeplex.com/workitem/3460) - Fix bug NullReferenceException if requireApiKey = true, but the header X-NUGET-APIKEY isn't present
1. [Michael Friis](https://www.codeplex.com/site/users/view/friism) ([@friism](https://twitter.com/friism))
- [#3278](https://nuget.codeplex.com/workitem/3278) - Fixes NuGet.Build targets file to so that it works correctly on MonoDevelop
1. [Pranav Krishnamoorthy](https://www.codeplex.com/site/users/view/pranavkm) ([@pranav_km](https://twitter.com/pranav_km))
- Improve Restore command performance by increasing parallelization
## NuGet 2.5

Двоичные данные
lib/Microsoft.Web.XmlTransform.dll

Двоичный файл не отображается.

Просмотреть файл

@ -36,21 +36,14 @@
</PropertyGroup>
<PropertyGroup>
<PackagesProjectConfig>packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
<PackagesProjectConfig Condition=" '$(OS)' == 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
<PackagesProjectConfig Condition=" '$(OS)' != 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config</PackagesProjectConfig>
</PropertyGroup>
<Choose>
<When Condition="Exists('$(PackagesProjectConfig)')">
<PropertyGroup>
<PackagesConfig>$(PackagesProjectConfig)</PackagesConfig>
</PropertyGroup>
</When>
<When Condition="Exists('packages.config')">
<PropertyGroup>
<PackagesConfig>packages.config</PackagesConfig>
</PropertyGroup>
</When>
</Choose>
<PropertyGroup>
<PackagesConfig Condition="Exists('$(MSBuildProjectDirectory)\packages.config')">$(MSBuildProjectDirectory)\packages.config</PackagesConfig>
<PackagesConfig Condition="Exists('$(PackagesProjectConfig)')">$(PackagesProjectConfig)</PackagesConfig>
</PropertyGroup>
<PropertyGroup>
<!-- NuGet command -->

Просмотреть файл

@ -75,13 +75,14 @@ namespace NuGet.ServerExtensions
public int MirrorPackage(IPackage package, FrameworkName targetFramework, bool allowPrereleaseVersions, MirrorDependenciesMode mirrorDependenciesMode)
{
return Execute(package, new InstallWalker(TargetRepository,
sourceRepository: mirrorDependenciesMode == MirrorDependenciesMode.Fail ? TargetRepository : SourceRepository,
targetFramework: targetFramework,
logger: Logger,
ignoreDependencies: mirrorDependenciesMode == MirrorDependenciesMode.Ignore,
allowPrereleaseVersions: allowPrereleaseVersions));
return Execute(package, new InstallWalker(
TargetRepository,
sourceRepository: mirrorDependenciesMode == MirrorDependenciesMode.Fail ? TargetRepository : SourceRepository,
targetFramework: targetFramework,
logger: Logger,
ignoreDependencies: mirrorDependenciesMode == MirrorDependenciesMode.Ignore,
allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: DependencyVersion.Lowest));
}
private int Execute(IPackage package, IPackageOperationResolver resolver)

Просмотреть файл

@ -245,6 +245,10 @@ namespace NuGet.Commands
string packageId,
SemanticVersion version)
{
if (version == null)
{
NoCache = true;
}
var packageManager = CreatePackageManager(fileSystem, AllowMultipleVersions);
if (!PackageInstallNeeded(packageManager, packageId, version))
@ -253,6 +257,18 @@ namespace NuGet.Commands
return;
}
if (version == null)
{
var latestVersion = GetLastestPackageVersion(
packageManager.SourceRepository,
packageId,
allowPrereleaseVersions: Prerelease);
if (latestVersion != null)
{
version = latestVersion.Version;
}
}
using (packageManager.SourceRepository.StartOperation(
RepositoryOperationNames.Install,
packageId,
@ -262,6 +278,84 @@ namespace NuGet.Commands
}
}
/// <summary>
/// Find the latest version of a package in the given repo.
/// </summary>
/// <param name="repo">The repository where to find the latest version of the package.</param>
/// <param name="id">The id of the package.</param>
/// <param name="allowPrereleaseVersions">Indicates if prerelease version is allowed.</param>
/// <returns>the latest version of the package; or null if the package doesn't exist
/// in the repo.</returns>
private static IPackage GetLastestPackageVersion(IPackageRepository repo, string id, bool allowPrereleaseVersions)
{
IPackage latestVersion = null;
var latestPackageLookup = repo as ILatestPackageLookup;
if (latestPackageLookup != null &&
latestPackageLookup.TryFindLatestPackageById(id, allowPrereleaseVersions, out latestVersion))
{
return latestVersion;
}
var aggregateRepository = repo as AggregateRepository;
if (aggregateRepository != null)
{
return GetLatestVersionPackageByIdFromAggregateRepository(
aggregateRepository, id, allowPrereleaseVersions);
}
IEnumerable<IPackage> packages = repo.FindPackagesById(id).OrderByDescending(p => p.Version);
if (!allowPrereleaseVersions)
{
packages = packages.Where(p => p.IsReleaseVersion());
}
latestVersion = packages.FirstOrDefault();
return latestVersion;
}
/// <summary>
/// Find the latest version of a package in the given aggregate repository.
/// </summary>
/// <param name="repo">The aggregate repository where to find the latest version of the package.</param>
/// <param name="id">The id of the package.</param>
/// <param name="allowPrereleaseVersions">Indicates if prerelease version is allowed.</param>
/// <returns>the latest version of the package; or null if the package doesn't exist
/// in the repo.</returns>
private static IPackage GetLatestVersionPackageByIdFromAggregateRepository(
AggregateRepository repo, string id,
bool allowPrereleaseVersions)
{
var tasks = repo.Repositories.Select(p => Task.Factory.StartNew(
state => GetLastestPackageVersion(p, id, allowPrereleaseVersions), p)).ToArray();
try
{
Task.WaitAll(tasks);
}
catch (AggregateException)
{
if (!repo.IgnoreFailingRepositories)
{
throw;
}
}
var versions = new List<IPackage>();
foreach (var task in tasks)
{
if (task.IsFaulted)
{
repo.LogRepository((IPackageRepository)task.AsyncState, task.Exception);
}
else if (task.Result != null)
{
versions.Add(task.Result);
}
}
return versions.OrderByDescending(v => v.Version).FirstOrDefault();
}
/// <summary>
/// Returns true if package install is needed.
/// Package install is not needed if

Просмотреть файл

@ -866,6 +866,14 @@ namespace NuGet.Commands
continue;
}
// Skip target file paths containing msbuild variables since we do not offer a way to install files with variable paths.
// These are show up in shared files found in universal apps.
if (targetFilePath.IndexOf("$(MSBuild", StringComparison.OrdinalIgnoreCase) > -1)
{
Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_UnresolvedFilePath"), targetFilePath);
continue;
}
// if IncludeReferencedProjects is true and we are adding source files,
// add projectName as part of the target to avoid file conflicts.
string targetPath = IncludeReferencedProjects && itemType == SourcesItemType ?

Просмотреть файл

@ -136,7 +136,14 @@ namespace NuGet.Commands
}
catch (Exception e)
{
Console.WriteWarning(e.Message);
if (Console.Verbosity == NuGet.Verbosity.Detailed)
{
Console.WriteWarning(e.ToString());
}
else
{
Console.WriteWarning(e.Message);
}
}
}
}
@ -335,7 +342,14 @@ namespace NuGet.Commands
}
catch (InvalidOperationException e)
{
Console.WriteWarning(e.Message);
if (Console.Verbosity == NuGet.Verbosity.Detailed)
{
Console.WriteWarning(e.ToString());
}
else
{
Console.WriteWarning(e.Message);
}
}
}
}

Просмотреть файл

@ -1,4 +1,6 @@

using System.Windows;
namespace NuGet.Common
{
public class CommandLineRepositoryFactory : PackageRepositoryFactory
@ -16,11 +18,15 @@ namespace NuGet.Common
{
var repository = base.CreateRepository(packageSource);
var httpClientEvents = repository as IHttpClientEvents;
if (httpClientEvents != null)
{
httpClientEvents.SendingRequest += (sender, args) =>
{
if (sender != httpClientEvents)
{
return;
}
if (_console.Verbosity == Verbosity.Detailed)
{
_console.WriteLine(

Просмотреть файл

@ -141,14 +141,8 @@ namespace NuGet.Common
var targetRelativePath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetFullPath);
// adds an <Import> element to this project file.
if (Project.Xml.Imports == null ||
Project.Xml.Imports.All(import => !targetRelativePath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
{
Project.Xml.AddImport(targetRelativePath);
NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(Project, targetRelativePath);
Project.Save();
}
NuGet.MSBuildProjectUtility.AddImportStatement(Project, targetRelativePath, location);
Project.Save();
}
public void RemoveImport(string targetFullPath)
@ -157,22 +151,10 @@ namespace NuGet.Common
{
throw new ArgumentNullException("targetFullPath");
}
if (Project.Xml.Imports != null)
{
var targetRelativePath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetFullPath);
// search for this import statement and remove it
var importElement = Project.Xml.Imports.FirstOrDefault(
import => targetRelativePath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));
if (importElement != null)
{
Project.Xml.RemoveChild(importElement);
NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(Project, targetRelativePath);
Project.Save();
}
}
var targetRelativePath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetFullPath);
NuGet.MSBuildProjectUtility.RemoveImportStatement(Project, targetRelativePath);
Project.Save();
}
public bool Equals(MSBuildProjectSystem other)

Просмотреть файл

@ -11,6 +11,8 @@ namespace NuGet.Common
".csproj",
".vbproj",
".fsproj",
".vcxproj",
".jsproj",
};
public static HashSet<string> SupportedProjectExtensions

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
@ -2854,45 +2854,6 @@ nuget pack foo.csproj -Build -Symbols -Properties Configuration=Release
nuget pack foo.nuspec -Version 2.1.0</value>
</data>
<data name="PushCommandDescription_csy" xml:space="preserve">
<value>Předá balíček na server a volitelně jej publikuje.</value>
</data>
<data name="PushCommandDescription_deu" xml:space="preserve">
<value>Sendet ein Paket mittels Push an den Server und veröffentlicht es optional.</value>
</data>
<data name="PushCommandDescription_esp" xml:space="preserve">
<value>Inserta un paquete al servidor y lo publica de forma opcional.</value>
</data>
<data name="PushCommandDescription_fra" xml:space="preserve">
<value>Transmet un package vers le serveur et le publie éventuellement.</value>
</data>
<data name="PushCommandDescription_ita" xml:space="preserve">
<value>Esegue il push al serve e lo pubblica.</value>
</data>
<data name="PushCommandDescription_jpn" xml:space="preserve">
<value>パッケージをサーバーにプッシュし、必要に応じて発行します。</value>
</data>
<data name="PushCommandDescription_kor" xml:space="preserve">
<value>서버에 패키지를 푸시하고 선택적으로 게시합니다.</value>
</data>
<data name="PushCommandDescription_plk" xml:space="preserve">
<value>Wypycha pakiet na serwer i opcjonalnie go publikuje.</value>
</data>
<data name="PushCommandDescription_ptb" xml:space="preserve">
<value>Envia um pacote para o servidor e, opcionalmente, o publica.</value>
</data>
<data name="PushCommandDescription_rus" xml:space="preserve">
<value>Отправляет пакет на сервер и публикует его (необязательно).</value>
</data>
<data name="PushCommandDescription_trk" xml:space="preserve">
<value>Paketi sürücüye iletir ve isteğe bağlı olarak bunu yayımlar.</value>
</data>
<data name="PushCommandDescription_chs" xml:space="preserve">
<value>将程序包推送到服务器并可以选择发布它。</value>
</data>
<data name="PushCommandDescription_cht" xml:space="preserve">
<value>將封裝推入伺服器並選擇性地發行。</value>
</data>
<data name="PushCommandSourceDescription_csy" xml:space="preserve">
<value>Určuje adresu URL serveru. Není-li zadána, použije se adresa nuget.org, pokud v konfiguračním souboru NuGet není nastavena konfigurační hodnota DefaultPushSource.</value>
</data>
@ -5038,4 +4999,238 @@ nuget update -Self</value>
<data name="RestoreCommandUsageSummary_cht" xml:space="preserve">
<value>[&lt;方案&gt; | &lt;packages.config 檔案&gt;] [選項]</value>
</data>
</root>
<data name="CommandNoCache_csy" xml:space="preserve">
<value>Zakáže použití mezipaměti počítače jako prvního zdroje balíčků.</value>
</data>
<data name="CommandNoCache_deu" xml:space="preserve">
<value>Deaktivieren der Verwendung des Computercaches als erste Paketquelle.</value>
</data>
<data name="CommandNoCache_esp" xml:space="preserve">
<value>Deshabilitar el uso de la caché del equipo como primer origen del paquete.</value>
</data>
<data name="CommandNoCache_fra" xml:space="preserve">
<value>Désactivez l'utilisation du cache de l'ordinateur comme première source de package.</value>
</data>
<data name="CommandNoCache_ita" xml:space="preserve">
<value>Disabilitare utilizzando la cache del computer come prima origine pacchetto.</value>
</data>
<data name="CommandNoCache_jpn" xml:space="preserve">
<value>最初のパッケージ ソースとしてマシン キャッシュを使用して無効にします。</value>
</data>
<data name="CommandNoCache_kor" xml:space="preserve">
<value>시스템 캐시를 첫 번째 패키지 소스로 사용하지 않도록 설정합니다.</value>
</data>
<data name="CommandNoCache_plk" xml:space="preserve">
<value>Wyłącz, używając pamięci podręcznej komputera jako pierwszego źródła pakietu.</value>
</data>
<data name="CommandNoCache_ptb" xml:space="preserve">
<value>Desativar usando o cache da máquina como a primeira origem de pacotes.</value>
</data>
<data name="CommandNoCache_rus" xml:space="preserve">
<value>Отключает использование кэша компьютера в качестве первого источника пакетов.</value>
</data>
<data name="CommandNoCache_trk" xml:space="preserve">
<value>Makine önbelleğini ilk paket kaynağı olarak kullanarak devre dışı bırakın.</value>
</data>
<data name="CommandNoCache_chs" xml:space="preserve">
<value>禁止使用计算机缓存作为第一个程序包源。</value>
</data>
<data name="CommandNoCache_cht" xml:space="preserve">
<value>停用使用機器快取做為第一個套件</value>
</data>
<data name="CommandSourceDescription_csy" xml:space="preserve">
<value>Seznam zdrojů balíčků použitých tímto příkazem</value>
</data>
<data name="CommandSourceDescription_deu" xml:space="preserve">
<value>Eine Liste der Paketquellen, die für diesen Befehl verwendet werden sollen.</value>
</data>
<data name="CommandSourceDescription_esp" xml:space="preserve">
<value>Lista de orígenes de paquetes para usar para este comando.</value>
</data>
<data name="CommandSourceDescription_fra" xml:space="preserve">
<value>Liste de sources de packages à utiliser pour cette commande.</value>
</data>
<data name="CommandSourceDescription_ita" xml:space="preserve">
<value>Elenco di origini pacchetti da utilizzare per questo comando.</value>
</data>
<data name="CommandSourceDescription_jpn" xml:space="preserve">
<value>このコマンドで使用するパッケージ ソースの一覧。</value>
</data>
<data name="CommandSourceDescription_kor" xml:space="preserve">
<value>이 명령에 사용할 패키지 소스 목록입니다.</value>
</data>
<data name="CommandSourceDescription_plk" xml:space="preserve">
<value>Lista źródeł pakietów do użycia na potrzeby tego polecenia.</value>
</data>
<data name="CommandSourceDescription_ptb" xml:space="preserve">
<value>Uma lista de origens de pacotes para usar para esse comando.</value>
</data>
<data name="CommandSourceDescription_rus" xml:space="preserve">
<value>Список источников пакетов, используемых для этой команды.</value>
</data>
<data name="CommandSourceDescription_trk" xml:space="preserve">
<value>Bu komut için kullanılacak paket kaynaklarının listesi.</value>
</data>
<data name="CommandSourceDescription_chs" xml:space="preserve">
<value>要用于此命令的程序包源列表。</value>
</data>
<data name="CommandSourceDescription_cht" xml:space="preserve">
<value>此命令使用的套件來源清單。</value>
</data>
<data name="PushCommandDescription_csy" xml:space="preserve">
<value>Předá balíček na server a publikuje jej.</value>
</data>
<data name="PushCommandDescription_deu" xml:space="preserve">
<value>Übertragen eines Paket mithilfe von Push auf den Server und Veröffentlichen des Pakets.</value>
</data>
<data name="PushCommandDescription_esp" xml:space="preserve">
<value>Inserta un paquete en el servidor y lo publica.</value>
</data>
<data name="PushCommandDescription_fra" xml:space="preserve">
<value>Applique au package un Push vers le serveur et le publie.</value>
</data>
<data name="PushCommandDescription_ita" xml:space="preserve">
<value>Effettua il push di un pacchetto verso il server e lo pubblica.</value>
</data>
<data name="PushCommandDescription_jpn" xml:space="preserve">
<value>サーバーにパッケージをプッシュして、公開します。</value>
</data>
<data name="PushCommandDescription_kor" xml:space="preserve">
<value>서버에 패키지를 푸시하고 게시합니다.</value>
</data>
<data name="PushCommandDescription_plk" xml:space="preserve">
<value>Wypycha pakiet na serwer i go publikuje.</value>
</data>
<data name="PushCommandDescription_ptb" xml:space="preserve">
<value>Envia um pacote para o servidor e publica-o.</value>
</data>
<data name="PushCommandDescription_rus" xml:space="preserve">
<value>Отправляет пакет на сервер и публикует его.</value>
</data>
<data name="PushCommandDescription_trk" xml:space="preserve">
<value>Paketi sunucuya gönderir ve yayımlar.</value>
</data>
<data name="PushCommandDescription_chs" xml:space="preserve">
<value>将程序包推送到服务器并进行发布。</value>
</data>
<data name="PushCommandDescription_cht" xml:space="preserve">
<value>將套件推向伺服器並發佈。</value>
</data>
<data name="SourcesCommandFormatDescription_csy" xml:space="preserve">
<value>Použije se na akce se seznamem. Přijímá dvě hodnoty: Podrobné (výchozí hodnota) a Krátké.</value>
</data>
<data name="SourcesCommandFormatDescription_deu" xml:space="preserve">
<value>Gilt für die Listenaktion. Nimmt zwei Werte an: "Detailed" (Standardwert) und "Short".</value>
</data>
<data name="SourcesCommandFormatDescription_esp" xml:space="preserve">
<value>Se aplica a la acción de la lista. Acepta dos valores: Detallado (predeterminado) y Breve.</value>
</data>
<data name="SourcesCommandFormatDescription_fra" xml:space="preserve">
<value>S'applique à l'action de la liste. Accepte deux valeurs : Détaillé (valeur par défaut) et Bref.</value>
</data>
<data name="SourcesCommandFormatDescription_ita" xml:space="preserve">
<value>Si applica all'azione list. Accetta due valori: Detailed (impostazione predefinita) e Short.</value>
</data>
<data name="SourcesCommandFormatDescription_jpn" xml:space="preserve">
<value>リストの操作に適用します。Detailed (既定) および Short の 2 つの値を受け入れます。</value>
</data>
<data name="SourcesCommandFormatDescription_kor" xml:space="preserve">
<value>목록 동작에 적용합니다. [자세히](기본값) 및 [짧게]의 두 가지 값을 사용할 수 있습니다.</value>
</data>
<data name="SourcesCommandFormatDescription_plk" xml:space="preserve">
<value>Jest stosowany do akcji z listy. Akceptuje dwie wartości: Szczegółowe (wartość domyślna) i Krótkie.</value>
</data>
<data name="SourcesCommandFormatDescription_ptb" xml:space="preserve">
<value>Aplica à ação da lista. Aceita dois valores: Detalhada (a padrão) e Curta.</value>
</data>
<data name="SourcesCommandFormatDescription_rus" xml:space="preserve">
<value>Применяется к действию со списком. Принимает два значения: "Detailed" (по умолчанию) и "Short".</value>
</data>
<data name="SourcesCommandFormatDescription_trk" xml:space="preserve">
<value>Liste eylemi için geçerlidir. Ayrıntılı (varsayılan) ve Kısa olmak üzere iki değer kabul eder.</value>
</data>
<data name="SourcesCommandFormatDescription_chs" xml:space="preserve">
<value>适用于列表操作。接受两个值:“详细”(默认值)和“简短”。</value>
</data>
<data name="SourcesCommandFormatDescription_cht" xml:space="preserve">
<value>套用至清單動作。接受兩種值: 詳細 (預設) 及簡短。</value>
</data>
<data name="CommandDisableParallelProcessing_csy" xml:space="preserve">
<value>Zakáže pro tento příkaz paralelní zpracování balíčků.</value>
</data>
<data name="CommandDisableParallelProcessing_deu" xml:space="preserve">
<value>Deaktivieren paralleler Verarbeitung von Pakten für diesen Befehl.</value>
</data>
<data name="CommandDisableParallelProcessing_esp" xml:space="preserve">
<value>Deshabilitar el procesamiento paralelo de paquetes para este comando.</value>
</data>
<data name="CommandDisableParallelProcessing_fra" xml:space="preserve">
<value>Désactive le traitement parallèle des packages pour cette commande.</value>
</data>
<data name="CommandDisableParallelProcessing_ita" xml:space="preserve">
<value>Disabilitare l'elaborazione parallela dei pacchetti per questo comando.</value>
</data>
<data name="CommandDisableParallelProcessing_jpn" xml:space="preserve">
<value>このコマンドのために、パッケージの並列処理を無効にします。</value>
</data>
<data name="CommandDisableParallelProcessing_kor" xml:space="preserve">
<value>이 명령에 대한 패키지 병렬 처리를 사용하지 않도록 설정합니다.</value>
</data>
<data name="CommandDisableParallelProcessing_plk" xml:space="preserve">
<value>Wyłącz równoległe przetwarzanie pakietów dla tego polecenia.</value>
</data>
<data name="CommandDisableParallelProcessing_ptb" xml:space="preserve">
<value>Desativar processamento paralelo de pacotes para esse comando.</value>
</data>
<data name="CommandDisableParallelProcessing_rus" xml:space="preserve">
<value>Отключает параллельную обработку пакетов для этой команды.</value>
</data>
<data name="CommandDisableParallelProcessing_trk" xml:space="preserve">
<value>Bu komut için paketlerin paralel işlenmesini devre dışı bırak.</value>
</data>
<data name="CommandDisableParallelProcessing_chs" xml:space="preserve">
<value>禁止为此命令并行处理程序包。</value>
</data>
<data name="CommandDisableParallelProcessing_cht" xml:space="preserve">
<value>停用此項目的套件平行處理</value>
</data>
<data name="CommandPackageSaveMode_csy" xml:space="preserve">
<value>Určuje typy souborů, které se mají po instalaci balíčku uložit: nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_deu" xml:space="preserve">
<value>Angeben von Dateitypen, die nach der Paketinstallation gespeichert werden sollen: nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_esp" xml:space="preserve">
<value>Especifica los tipos de archivo que se guardarán después de la instalación del paquete: nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_fra" xml:space="preserve">
<value>Spécifie les types de fichiers à enregistrer après l'installation du package : nuspec, nupkg, nuspec, nupkg.</value>
</data>
<data name="CommandPackageSaveMode_ita" xml:space="preserve">
<value>Specifica i tipi di file per il salvataggio dopo l'installazione del pacchetto: nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_jpn" xml:space="preserve">
<value>パッケージのインストール後に保存するファイルの種類を指定します: nuspec、nupkg、nuspec;nupkg。</value>
</data>
<data name="CommandPackageSaveMode_kor" xml:space="preserve">
<value>패키지 설치 후에 저장할 파일 형식을 지정합니다. nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_plk" xml:space="preserve">
<value>Określa typy plików do zapisania po zainstalowaniu pakietów: nuspec, nupkg, nuspec, nupkg.</value>
</data>
<data name="CommandPackageSaveMode_ptb" xml:space="preserve">
<value>Especifica tipos de arquivos para salvar após instalação de pacote: nuspec, nupkg, nuspec;nupkg.</value>
</data>
<data name="CommandPackageSaveMode_rus" xml:space="preserve">
<value>Задает типы файлов, сохраняемых после установки пакета: nuspec, nupkg, nuspec, nupkg.</value>
</data>
<data name="CommandPackageSaveMode_trk" xml:space="preserve">
<value>Paket kurulumundan sonra kaydedilecek dosya türlerini belirtir: nuspec, nupkg, nuspec;nupkg</value>
</data>
<data name="CommandPackageSaveMode_chs" xml:space="preserve">
<value>指定要在安装程序包后保存的文件类型: nuspec、nupkg、nuspec;nupkg。</value>
</data>
<data name="CommandPackageSaveMode_cht" xml:space="preserve">
<value>指定套件安裝之後要儲存的檔案類型: nuspec, nupkg, nuspec;nupkg。</value>
</data>
</root>

Просмотреть файл

@ -237,6 +237,9 @@
<data name="Warning_FileDoesNotExist" xml:space="preserve">
<value>'{0}' was included in the project but doesn't exist. Skipping...</value>
</data>
<data name="Warning_UnresolvedFilePath" xml:space="preserve">
<value>'{0}' was included in the project but the path could not be resolved. Skipping...</value>
</data>
<data name="Warning_UnspecifiedField" xml:space="preserve">
<value>{0} was not specified. Using '{1}'.</value>
</data>
@ -2438,45 +2441,6 @@ To prevent NuGet from downloading packages during build, open the Visual Studio
<data name="UnableToFindBuildOutput_cht" xml:space="preserve">
<value>找不到 '{0}'。確定已建置專案。</value>
</data>
<data name="InvalidFile_csy" xml:space="preserve">
<value>Nebyl zadán žádný soubor packages.config ani soubor řešení. K aktualizaci souboru NuGet.exe použijte přepínač -self.</value>
</data>
<data name="InvalidFile_deu" xml:space="preserve">
<value>Es wurde keine Datei "packages.config" oder Projektdatei angegeben. Verwenden Sie den Schalter "-self", um "NuGet.exe" zu aktualisieren.</value>
</data>
<data name="InvalidFile_esp" xml:space="preserve">
<value>No se ha especificado ningún archivo de soluciones ni packages.config. Use el conmutador automático para actualizar NuGet.exe.</value>
</data>
<data name="InvalidFile_fra" xml:space="preserve">
<value>Aucun fichier packages.config ou solution spécifié. Utilisez le commutateur @@@-self pour mettre à jour NuGet.exe.</value>
</data>
<data name="InvalidFile_ita" xml:space="preserve">
<value>Nessun packages.config o solution file specificati. Usare il self switch per aggiornare a NuGet.exe.</value>
</data>
<data name="InvalidFile_jpn" xml:space="preserve">
<value>packages.config またはソリューション ファイルが指定されていません。NuGet.exe を更新するには、-self スイッチを使用してください。</value>
</data>
<data name="InvalidFile_kor" xml:space="preserve">
<value>packages.config 또는 솔루션 파일이 지정되지 않았습니다. -self 스위치를 사용하여 NuGet.exe를 업데이트하십시오.</value>
</data>
<data name="InvalidFile_plk" xml:space="preserve">
<value>Nie określono pliku packages.config ani pliku rozwiązania. Użyj przełącznika -self, aby zaktualizować pakiet NuGet.exe.</value>
</data>
<data name="InvalidFile_ptb" xml:space="preserve">
<value>Nenhum arquivo packages.config ou de solução especificada. Use o botão automático para atualizar o NuGet.exe.</value>
</data>
<data name="InvalidFile_rus" xml:space="preserve">
<value>Не указан файл packages.config или файл решения. Используйте параметр -self для обновления NuGet.exe.</value>
</data>
<data name="InvalidFile_trk" xml:space="preserve">
<value>Herhangi bir packages.config veya çözüm dosyası belirtilmedi. NuGet.exe öğesini güncellemek için -self anahtarını kullanın .</value>
</data>
<data name="InvalidFile_chs" xml:space="preserve">
<value>未指定 packages.config 或解决方案文件。请使用 -self 开关更新 NuGet.exe。</value>
</data>
<data name="InvalidFile_cht" xml:space="preserve">
<value>未指定 packages.config 或方案檔案。使用 -self 切換以更新 NuGet.exe。</value>
</data>
<data name="PackageDoesNotExist_csy" xml:space="preserve">
<value>Nelze vyhledat {0} {1}. Před spuštěním aktualizace ověřte, zda jsou k dispozici všechny balíčky ve složce balíčků.</value>
</data>
@ -5748,4 +5712,316 @@ Oluşturma sırasında NuGet'in paketleri indirmesini önlemek için, Visual Stu
<value>For more information, visit {0}</value>
<comment>{0} will be replaced with a url.</comment>
</data>
</root>
<data name="InvalidFile_csy" xml:space="preserve">
<value>Nebyl určen žádný soubor packages.config, soubor projektu nebo balíčku. Použijte přepínač -self a aktualizujte soubor NuGet.exe.</value>
</data>
<data name="InvalidFile_deu" xml:space="preserve">
<value>Es wurde keine packages.config-, Projekt- oder Lösungsdatei angegeben. Verwenden Sie den Schalter "-self", um "NuGet.exe" zu aktualisieren.</value>
</data>
<data name="InvalidFile_esp" xml:space="preserve">
<value>No se ha especificado ningún archivo de solución, proyecto o packages.config. Use el modificador -self para actualizar NuGet.exe.</value>
</data>
<data name="InvalidFile_fra" xml:space="preserve">
<value>Aucun packages.config, projet ou fichier de solution spécifié. Utilisez le commutateur -self pour mettre à jour NuGet.exe.</value>
</data>
<data name="InvalidFile_ita" xml:space="preserve">
<value>Nessun file packages.config, di progetto o di soluzione specificato. Utilizzare l'opzione -self per aggiornare NuGet.exe.</value>
</data>
<data name="InvalidFile_jpn" xml:space="preserve">
<value>packages.config、プロジェクトまたはソリューション ファイルが指定されていません。-self スイッチ使用して、NuGet.exe を更新してください。</value>
</data>
<data name="InvalidFile_kor" xml:space="preserve">
<value>packages.config, 프로젝트 또는 솔루션 파일이 지정되지 않았습니다. -self 스위치를 사용하여 NuGet.exe를 업데이트하십시오.</value>
</data>
<data name="InvalidFile_plk" xml:space="preserve">
<value>Nie określono pliku packages.config, pliku projektu ani pliku rozwiązania. Użyj przełącznika -self, aby zaktualizować pakiet NuGet.exe.</value>
</data>
<data name="InvalidFile_ptb" xml:space="preserve">
<value>Nenhum arquivo de solução, projeto ou packages.config especificado. Use a chave -self para atualizar o NuGet.exe.</value>
</data>
<data name="InvalidFile_rus" xml:space="preserve">
<value>Не указан файл packages.config, файл проекта или решения. Используйте переключатель -self, чтобы обновить NuGet.exe.</value>
</data>
<data name="InvalidFile_trk" xml:space="preserve">
<value>packages.config, proje veya çözüm dosyası belirtilmemiş. NuGet.exe'yi güncelleştirmek için -self anahtarını kullanın.</value>
</data>
<data name="InvalidFile_chs" xml:space="preserve">
<value>未指定 packages.config、项目或解决方案文件。请使用 -self 开关更新 NuGet.exe。</value>
</data>
<data name="InvalidFile_cht" xml:space="preserve">
<value>未指定 packages.config、專案或方案。使用 -self 切換以更新 NuGet.exe。</value>
</data>
<data name="MultipleProjectFilesFound_csy" xml:space="preserve">
<value>Bylo nalezeno více souborů projektu pro {0}.</value>
</data>
<data name="MultipleProjectFilesFound_deu" xml:space="preserve">
<value>Es wurden mehrere Projektdateien für "{0}" gefunden.</value>
</data>
<data name="MultipleProjectFilesFound_esp" xml:space="preserve">
<value>Se encontraron varios archivos de proyecto para '{0}'.</value>
</data>
<data name="MultipleProjectFilesFound_fra" xml:space="preserve">
<value>Plusieurs fichiers de projet trouvés pour '{0}'.</value>
</data>
<data name="MultipleProjectFilesFound_ita" xml:space="preserve">
<value>Trovati più file di progetto per '{0}'.</value>
</data>
<data name="MultipleProjectFilesFound_jpn" xml:space="preserve">
<value>{0}' に複数のプロジェクト ファイルが見つかりました。</value>
</data>
<data name="MultipleProjectFilesFound_kor" xml:space="preserve">
<value>'{0}'에 대한 프로젝트 파일이 여러 개 있습니다.</value>
</data>
<data name="MultipleProjectFilesFound_plk" xml:space="preserve">
<value>Znaleziono wiele plików projektów dla elementu „{0}”.</value>
</data>
<data name="MultipleProjectFilesFound_ptb" xml:space="preserve">
<value>Encontrados diversos arquivos de projeto para '{0}'.</value>
</data>
<data name="MultipleProjectFilesFound_rus" xml:space="preserve">
<value>Обнаружено несколько файлов проектов для "{0}".</value>
</data>
<data name="MultipleProjectFilesFound_trk" xml:space="preserve">
<value>{0} için birden çok proje dosyası bulundu.</value>
</data>
<data name="MultipleProjectFilesFound_chs" xml:space="preserve">
<value>发现了“{0}”的多个项目文件。</value>
</data>
<data name="MultipleProjectFilesFound_cht" xml:space="preserve">
<value>找到 '{0}' 的多個專案檔案。</value>
</data>
<data name="UnableToFindProject_csy" xml:space="preserve">
<value>Projekt {0} nebyl nalezen.</value>
</data>
<data name="UnableToFindProject_deu" xml:space="preserve">
<value>Das Projekt "{0}" wurde nicht gefunden.</value>
</data>
<data name="UnableToFindProject_esp" xml:space="preserve">
<value>No se encuentra el proyecto '{0}'.</value>
</data>
<data name="UnableToFindProject_fra" xml:space="preserve">
<value>Impossible de trouver le projet '{0}'.</value>
</data>
<data name="UnableToFindProject_ita" xml:space="preserve">
<value>Impossibile trovare il progetto '{0}'.</value>
</data>
<data name="UnableToFindProject_jpn" xml:space="preserve">
<value>プロジェクト '{0}' が見つかりません。</value>
</data>
<data name="UnableToFindProject_kor" xml:space="preserve">
<value>'{0}' 프로젝트를 찾을 수 없습니다.</value>
</data>
<data name="UnableToFindProject_plk" xml:space="preserve">
<value>Nie można odnaleźć projektu „{0}”.</value>
</data>
<data name="UnableToFindProject_ptb" xml:space="preserve">
<value>Não é possível encontrar o projeto '{0}'.</value>
</data>
<data name="UnableToFindProject_rus" xml:space="preserve">
<value>Не удалось найти проект "{0}".</value>
</data>
<data name="UnableToFindProject_trk" xml:space="preserve">
<value>{0}' projesi bulunamadı.</value>
</data>
<data name="UnableToFindProject_chs" xml:space="preserve">
<value>找不到项目“{0}”。</value>
</data>
<data name="UnableToFindProject_cht" xml:space="preserve">
<value>找不到專案 '{0}'。</value>
</data>
<data name="Warning_InvalidPackageSaveMode_csy" xml:space="preserve">
<value>Hodnota PackageSaveMode {0} je neplatná.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_deu" xml:space="preserve">
<value>Ungültiger PackageSaveMode-Wert "{0}".</value>
</data>
<data name="Warning_InvalidPackageSaveMode_esp" xml:space="preserve">
<value>El valor de PackageSaveMode '{0}' no es válido.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_fra" xml:space="preserve">
<value>valeur PackageSaveMode non valide : '{0}'.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_ita" xml:space="preserve">
<value>Valore '{0}' di PackageSaveMode non valido.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_jpn" xml:space="preserve">
<value>無効な PackageSaveMode 値 '{0}' です。</value>
</data>
<data name="Warning_InvalidPackageSaveMode_kor" xml:space="preserve">
<value>잘못된 PackageSaveMode 값 '{0}'입니다.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_plk" xml:space="preserve">
<value>Nieprawidłowa wartość opcji PackageSaveMode („{0}”).</value>
</data>
<data name="Warning_InvalidPackageSaveMode_ptb" xml:space="preserve">
<value>Valor PackageSaveMode inválido '{0}'.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_rus" xml:space="preserve">
<value>Недопустимое значение PackageSaveMode: "{0}".</value>
</data>
<data name="Warning_InvalidPackageSaveMode_trk" xml:space="preserve">
<value>PackageSaveMode değeri '{0}' geçersiz.</value>
</data>
<data name="Warning_InvalidPackageSaveMode_chs" xml:space="preserve">
<value>PackageSaveMode 值“{0}”无效。</value>
</data>
<data name="Warning_InvalidPackageSaveMode_cht" xml:space="preserve">
<value>無效的 PackageSaveMode 值 '{0}'。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_csy" xml:space="preserve">
<value>Verze závislosti {0} není určena.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_deu" xml:space="preserve">
<value>Die Version der Abhängigkeit "{0}" wurde nicht angegeben.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_esp" xml:space="preserve">
<value>No se ha especificado la versión de la dependencia '{0}'.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_fra" xml:space="preserve">
<value>La version de dépendance '{0}' n'est pas spécifiée.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_ita" xml:space="preserve">
<value>Versione della dipendenza '{0}' non specificata.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_jpn" xml:space="preserve">
<value>依存関係のバージョン '{0}' が指定されていません。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_kor" xml:space="preserve">
<value>'{0}' 종속성 버전이 지정되지 않았습니다.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_plk" xml:space="preserve">
<value>Nie określono wersji zależności „{0}”.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_ptb" xml:space="preserve">
<value>A versão de dependência '{0}' não é especificada.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_rus" xml:space="preserve">
<value>Не указана версия зависимости "{0}".</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_trk" xml:space="preserve">
<value>{0}' bağımlılığının sürümü belirtilmemiş.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_chs" xml:space="preserve">
<value>未指定依赖项“{0}”的版本。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersion_cht" xml:space="preserve">
<value>未指定相依項 '{0}' 版本。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_csy" xml:space="preserve">
<value>Určete verzi závislosti a sestavte balíček znovu.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_deu" xml:space="preserve">
<value>Angeben der Version der Abhängigkeit und erneutes Erstellen des Pakets.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_esp" xml:space="preserve">
<value>Especifique la versión de la dependencia y recompile el paquete.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_fra" xml:space="preserve">
<value>Spécifiez la version de dépendance et regénérez votre package.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_ita" xml:space="preserve">
<value>Specificare la versione della dipendenza e ricompilare il pacchetto.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_jpn" xml:space="preserve">
<value>依存関係のバージョンを指定して、パッケージを再構築してください。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_kor" xml:space="preserve">
<value>종속성 버전을 지정하고 패키지를 다시 빌드하십시오.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_plk" xml:space="preserve">
<value>Określ wersję zależności i ponownie skompiluj pakiet.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_ptb" xml:space="preserve">
<value>Especifique a versão de dependência e reconstrua seu pacote.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_rus" xml:space="preserve">
<value>Укажите версию зависимости и повторите построение проекта.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_trk" xml:space="preserve">
<value>Bağımlılığın sürümünü belirtin ve paketinizi tekrar oluşturun.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_chs" xml:space="preserve">
<value>指定依赖项的版本并重新生成你的程序包。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionSolution_cht" xml:space="preserve">
<value>指定相依相版本並重新建置您的套件。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_csy" xml:space="preserve">
<value>Určete verzi závislostí.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_deu" xml:space="preserve">
<value>Angeben der Version der Abhängigkeiten.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_esp" xml:space="preserve">
<value>Especifique la versión de las dependencias.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_fra" xml:space="preserve">
<value>Spécifiez la version des dépendances.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_ita" xml:space="preserve">
<value>Specificare la versione delle dipendenze.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_jpn" xml:space="preserve">
<value>依存関係のバージョンを指定してください。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_kor" xml:space="preserve">
<value>종속성 버전을 지정하십시오.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_plk" xml:space="preserve">
<value>Określ wersję zależności.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_ptb" xml:space="preserve">
<value>Especifique uma versão de dependências.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_rus" xml:space="preserve">
<value>Укажите версию зависимостей.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_trk" xml:space="preserve">
<value>Bağımlılıkların sürümlerini belirtin.</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_chs" xml:space="preserve">
<value>指定依赖项的版本。</value>
</data>
<data name="Warning_UnspecifiedDependencyVersionTitle_cht" xml:space="preserve">
<value>指定相依項版本。</value>
</data>
<data name="HelpCommandForMoreInfo_csy" xml:space="preserve">
<value>Další informace naleznete na adrese {0}</value>
</data>
<data name="HelpCommandForMoreInfo_deu" xml:space="preserve">
<value>Besuchen Sie "{0}", um weitere Informationen zu erhalten.</value>
</data>
<data name="HelpCommandForMoreInfo_esp" xml:space="preserve">
<value>Para obtener más información, visite {0}</value>
</data>
<data name="HelpCommandForMoreInfo_fra" xml:space="preserve">
<value>Pour plus d'informations, consultez {0}</value>
</data>
<data name="HelpCommandForMoreInfo_ita" xml:space="preserve">
<value>Per ulteriori informazioni, visitare {0}</value>
</data>
<data name="HelpCommandForMoreInfo_jpn" xml:space="preserve">
<value>詳細については、{0} を参照してください</value>
</data>
<data name="HelpCommandForMoreInfo_kor" xml:space="preserve">
<value>자세한 내용은 {0}을(를) 참조하십시오.</value>
</data>
<data name="HelpCommandForMoreInfo_plk" xml:space="preserve">
<value>Aby uzyskać więcej informacji, odwiedź stronę {0}</value>
</data>
<data name="HelpCommandForMoreInfo_ptb" xml:space="preserve">
<value>Para obter mais informações, visite {0}</value>
</data>
<data name="HelpCommandForMoreInfo_rus" xml:space="preserve">
<value>Дополнительные сведения см. на веб-сайте {0}</value>
</data>
<data name="HelpCommandForMoreInfo_trk" xml:space="preserve">
<value>Daha fazla bilgi için {0} adresini ziyaret edin.</value>
</data>
<data name="HelpCommandForMoreInfo_chs" xml:space="preserve">
<value>有关详细信息,请访问 {0}</value>
</data>
<data name="HelpCommandForMoreInfo_cht" xml:space="preserve">
<value>如需詳細資訊,請造訪 {0}</value>
</data>
</root>

Просмотреть файл

@ -259,6 +259,14 @@ namespace NuGet
return packages.Where(BuildSearchExpression<T>(propertiesToSearch, nonNullTerms));
}
/// <summary>
/// Returns a find query that is further restricted to just the latest package version.
/// </summary>
public static IQueryable<T> FindLatestVersion<T>(this IQueryable<T> packages) where T : IPackage
{
return from p in packages where p.IsLatestVersion select p;
}
/// <summary>
/// Constructs an expression to search for individual tokens in a search term in the Id and Description of packages
/// </summary>

Просмотреть файл

@ -64,22 +64,7 @@ namespace NuGet
public static Stream AsStream(this string value, Encoding encoding)
{
var memoryStream = new MemoryStream();
try
{
var bytes = encoding.GetPreamble();
memoryStream.Write(bytes, 0, bytes.Length);
bytes = encoding.GetBytes(value);
memoryStream.Write(bytes, 0, bytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
catch
{
memoryStream.Dispose();
throw;
}
return new MemoryStream(encoding.GetBytes(value));
}
/// <summary>

Просмотреть файл

@ -47,9 +47,16 @@ namespace NuGet
bool succeeded = transformation.Apply(document);
if (succeeded)
{
using (var fileStream = projectSystem.CreateFile(targetPath))
using (var memoryStream = new MemoryStream())
{
document.Save(fileStream);
// save the result into a memoryStream first so that if there is any
// exception during document.Save(), the original file won't be truncated.
document.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var fileStream = projectSystem.CreateFile(targetPath))
{
memoryStream.CopyTo(fileStream);
}
}
}
}

Просмотреть файл

@ -24,6 +24,8 @@ namespace NuGet
bool continueIfFailed = true;
int proxyCredentialsRetryCount = 0;
int credentialsRetryCount = 0;
int failureCount = 0;
const int MaxFailureCount = 10;
while (true)
{
@ -96,6 +98,12 @@ namespace NuGet
}
catch (WebException ex)
{
++failureCount;
if (failureCount >= MaxFailureCount)
{
throw;
}
using (IHttpWebResponse response = GetResponse(ex.Response))
{
if (response == null &&

Просмотреть файл

@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
@ -12,11 +13,17 @@ namespace NuGet
public static void AddListener(IHttpClientEvents source, IWeakEventListener listener)
{
// weak event pattern cannot be used if we're running from command line.
Debug.Assert(!EnvironmentUtility.RunningFromCommandLine);
SendingRequestEventManager.CurrentManager.ProtectedAddListener(source, listener);
}
public static void RemoveListener(IHttpClientEvents source, IWeakEventListener listener)
{
// weak event pattern cannot be used if we're running from command line.
Debug.Assert(!EnvironmentUtility.RunningFromCommandLine);
SendingRequestEventManager.CurrentManager.ProtectedRemoveListener(source, listener);
}

Просмотреть файл

@ -143,10 +143,10 @@ namespace NuGet
var installerWalker = new InstallWalker(
LocalRepository, SourceRepository,
targetFramework, Logger,
ignoreDependencies, allowPrereleaseVersions)
ignoreDependencies, allowPrereleaseVersions,
DependencyVersion)
{
DisableWalkInfo = ignoreWalkInfo,
DependencyVersion = DependencyVersion,
CheckDowngrade = CheckDowngrade
};
Execute(package, installerWalker);
@ -184,7 +184,7 @@ namespace NuGet
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageOperation, operation.Action, operation.Package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_InstallPackage, operation.Package);
}
else
{
@ -198,7 +198,7 @@ namespace NuGet
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageOperation, operation.Action, operation.Package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_UninstallPackage, operation.Package);
}
else
{

Просмотреть файл

@ -26,8 +26,9 @@ namespace NuGet
IPackageRepository sourceRepository,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions)
: this(localRepository, sourceRepository, null, logger, ignoreDependencies, allowPrereleaseVersions)
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion)
: this(localRepository, sourceRepository, null, logger, ignoreDependencies, allowPrereleaseVersions, dependencyVersion)
{
}
@ -36,14 +37,16 @@ namespace NuGet
FrameworkName targetFramework,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions) :
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion) :
this(localRepository,
sourceRepository,
constraintProvider: NullConstraintProvider.Instance,
targetFramework: targetFramework,
logger: logger,
ignoreDependencies: ignoreDependencies,
allowPrereleaseVersions: allowPrereleaseVersions)
allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: dependencyVersion)
{
}
@ -53,7 +56,8 @@ namespace NuGet
FrameworkName targetFramework,
ILogger logger,
bool ignoreDependencies,
bool allowPrereleaseVersions)
bool allowPrereleaseVersions,
DependencyVersion dependencyVersion)
: base(targetFramework)
{
@ -77,6 +81,7 @@ namespace NuGet
ConstraintProvider = constraintProvider;
_operations = new OperationLookup();
_allowPrereleaseVersions = allowPrereleaseVersions;
DependencyVersion = dependencyVersion;
CheckDowngrade = true;
}

Просмотреть файл

@ -26,7 +26,7 @@ namespace NuGet
ILogger logger,
bool updateDependencies,
bool allowPrereleaseVersions)
: base(localRepository, sourceRepository, constraintProvider, targetFramework, logger, !updateDependencies, allowPrereleaseVersions)
: base(localRepository, sourceRepository, constraintProvider, targetFramework, logger, !updateDependencies, allowPrereleaseVersions, DependencyVersion.Lowest)
{
_dependentsResolver = dependentsResolver;
AcceptedTargets = PackageTargets.All;

Просмотреть файл

@ -194,7 +194,14 @@ namespace NuGet
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageOperation, operation.Action, operation.Package);
Logger.Log(
MessageLevel.Info,
NuGetResources.Log_InstallPackageIntoProject,
operation.Package,
Project.ProjectName);
PackageOperationEventArgs args = CreateOperation(operation.Package);
OnPackageReferenceAdding(args);
}
else
{
@ -208,7 +215,14 @@ namespace NuGet
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageOperation, operation.Action, operation.Package);
Logger.Log(
MessageLevel.Info,
NuGetResources.Log_UninstallPackageFromProject,
operation.Package,
Project.ProjectName);
PackageOperationEventArgs args = CreateOperation(operation.Package);
OnPackageReferenceRemoved(args);
}
else
{
@ -269,28 +283,8 @@ namespace NuGet
try
{
if (assemblyReferences.Count > 0 || contentFiles.Count > 0 || buildFiles.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), Project.ProjectName, VersionUtility.GetShortFrameworkName(Project.TargetFramework));
if (assemblyReferences.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_AssemblyReferences,
Path.GetDirectoryName(assemblyReferences[0].Path), VersionUtility.GetTargetFrameworkLogString(assemblyReferences[0].TargetFramework));
}
if (contentFiles.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_ContentFiles,
Path.GetDirectoryName(contentFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(contentFiles[0].TargetFramework));
}
if (buildFiles.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_BuildFiles,
Path.GetDirectoryName(buildFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(buildFiles[0].TargetFramework));
}
}
// Log target framework info for debugging
LogTargetFrameworkInfo(package, assemblyReferences, contentFiles, buildFiles);
// Add content files
Project.AddFiles(contentFiles, _fileTransformers);
@ -352,6 +346,35 @@ namespace NuGet
}
}
private void LogTargetFrameworkInfo(IPackage package, List<IPackageAssemblyReference> assemblyReferences, List<IPackageFile> contentFiles, List<IPackageFile> buildFiles)
{
if (assemblyReferences.Count > 0 || contentFiles.Count > 0 || buildFiles.Count > 0)
{
// targetFramework can be null for unknown project types
string shortFramework = Project.TargetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(Project.TargetFramework);
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), Project.ProjectName, shortFramework);
if (assemblyReferences.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_AssemblyReferences,
Path.GetDirectoryName(assemblyReferences[0].Path), VersionUtility.GetTargetFrameworkLogString(assemblyReferences[0].TargetFramework));
}
if (contentFiles.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_ContentFiles,
Path.GetDirectoryName(contentFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(contentFiles[0].TargetFramework));
}
if (buildFiles.Count > 0)
{
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_BuildFiles,
Path.GetDirectoryName(buildFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(buildFiles[0].TargetFramework));
}
}
}
private void FilterAssemblyReferences(List<IPackageAssemblyReference> assemblyReferences, ICollection<PackageReferenceSet> packageAssemblyReferences)
{
if (packageAssemblyReferences != null && packageAssemblyReferences.Count > 0)

Просмотреть файл

@ -162,7 +162,7 @@ namespace NuGet
return factory;
}
private void LogRepository(IPackageRepository repository, Exception ex)
public void LogRepository(IPackageRepository repository, Exception ex)
{
_failingRepositories.Add(repository);
Logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(ex).Message);

56
src/Core/Resources/NuGetResources.Designer.cs сгенерированный
Просмотреть файл

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -285,6 +285,15 @@ namespace NuGet.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Too many automatic redirections were attempted..
/// </summary>
public static string Error_TooManyRedirections {
get {
return ResourceManager.GetString("Error_TooManyRedirections", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while loading packages from &apos;{0}&apos;: {1}.
/// </summary>
@ -465,6 +474,24 @@ namespace NuGet.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Install &apos;{0}&apos;.
/// </summary>
public static string Log_InstallPackage {
get {
return ResourceManager.GetString("Log_InstallPackage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add &apos;{0}&apos; to project {1}..
/// </summary>
public static string Log_InstallPackageIntoProject {
get {
return ResourceManager.GetString("Log_InstallPackageIntoProject", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No updates available for &apos;{0}&apos;..
/// </summary>
@ -501,15 +528,6 @@ namespace NuGet.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to {0} {1}.
/// </summary>
public static string Log_PackageOperation {
get {
return ResourceManager.GetString("Log_PackageOperation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} already has a reference to &apos;{1}&apos;..
/// </summary>
@ -546,6 +564,24 @@ namespace NuGet.Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Uninstall &apos;{0}&apos;..
/// </summary>
public static string Log_UninstallPackage {
get {
return ResourceManager.GetString("Log_UninstallPackage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove &apos;{0}&apos; from project {1}..
/// </summary>
public static string Log_UninstallPackageFromProject {
get {
return ResourceManager.GetString("Log_UninstallPackageFromProject", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating &apos;{0}&apos; from version &apos;{1}&apos; to &apos;{2}&apos; in project &apos;{3}&apos;..
/// </summary>

Просмотреть файл

@ -433,9 +433,6 @@
<data name="Error_PackageAlreadyExists" xml:space="preserve">
<value>Package '{0}' already exists.</value>
</data>
<data name="Log_PackageOperation" xml:space="preserve">
<value>{0} {1}</value>
</data>
<data name="Log_UpdatingPackagesWithoutOldVersion" xml:space="preserve">
<value>Updating '{0}' to version '{1}' in project '{2}'.</value>
</data>
@ -460,4 +457,19 @@
<data name="Debug_TargetFrameworkInfo_PowershellScripts" xml:space="preserve">
<value>&gt;&gt; PowerShell scripts are being executed from '{0}'{1}</value>
</data>
<data name="Log_InstallPackage" xml:space="preserve">
<value>Install '{0}'</value>
</data>
<data name="Log_InstallPackageIntoProject" xml:space="preserve">
<value>Add '{0}' to project {1}.</value>
</data>
<data name="Log_UninstallPackage" xml:space="preserve">
<value>Uninstall '{0}'.</value>
</data>
<data name="Log_UninstallPackageFromProject" xml:space="preserve">
<value>Remove '{0}' from project {1}.</value>
</data>
<data name="Error_TooManyRedirections" xml:space="preserve">
<value>Too many automatic redirections were attempted.</value>
</data>
</root>

Просмотреть файл

@ -10,8 +10,9 @@ namespace NuGet
{
private const string ServiceEndpoint = "/api/v2/package";
private const string ApiKeyHeader = "X-NuGet-ApiKey";
private const int MaxRediretionCount = 20;
private readonly Lazy<Uri> _baseUri;
private Lazy<Uri> _baseUri;
private readonly string _source;
private readonly string _userAgent;
@ -79,35 +80,50 @@ namespace NuGet
long packageSize,
int timeout)
{
HttpClient client = GetClient("", "PUT", "application/octet-stream");
client.SendingRequest += (sender, e) =>
int redirectionCount = 0;
while (true)
{
SendingRequest(this, e);
var request = (HttpWebRequest)e.Request;
request.AllowWriteStreamBuffering = false;
request.KeepAlive = false;
HttpClient client = GetClient("", "PUT", "application/octet-stream");
// Set the timeout
if (timeout <= 0)
client.SendingRequest += (sender, e) =>
{
timeout = request.ReadWriteTimeout; // Default to 5 minutes if the value is invalid.
SendingRequest(this, e);
var request = (HttpWebRequest)e.Request;
request.AllowWriteStreamBuffering = false;
// Set the timeout
if (timeout <= 0)
{
timeout = request.ReadWriteTimeout; // Default to 5 minutes if the value is invalid.
}
request.Timeout = timeout;
request.ReadWriteTimeout = timeout;
if (!String.IsNullOrEmpty(apiKey))
{
request.Headers.Add(ApiKeyHeader, apiKey);
}
var multiPartRequest = new MultipartWebRequest();
multiPartRequest.AddFile(packageStreamFactory, "package", packageSize);
multiPartRequest.CreateMultipartRequest(request);
};
// Since AllowWriteStreamBuffering is set to false, redirection will not be handled
// automatically by HttpWebRequest. So we need to check redirect status code and
// update _baseUri and retry if redirection happens.
if (EnsureSuccessfulResponse(client))
{
return;
}
request.Timeout = timeout;
request.ReadWriteTimeout = timeout;
if (!String.IsNullOrEmpty(apiKey))
++redirectionCount;
if (redirectionCount > MaxRediretionCount)
{
request.Headers.Add(ApiKeyHeader, apiKey);
throw new WebException(NuGetResources.Error_TooManyRedirections);
}
var multiPartRequest = new MultipartWebRequest();
multiPartRequest.AddFile(packageStreamFactory, "package", packageSize);
multiPartRequest.CreateMultipartRequest(request);
};
EnsureSuccessfulResponse(client);
}
}
/// <summary>
@ -215,7 +231,15 @@ namespace NuGet
return requestUri;
}
private static void EnsureSuccessfulResponse(HttpClient client, HttpStatusCode? expectedStatusCode = null)
/// <summary>
/// Ensures that success response is received.
/// </summary>
/// <param name="client">The client that is making the request.</param>
/// <param name="expectedStatusCode">The exected status code.</param>
/// <returns>True if success response is received; false if redirection response is received.
/// In this case, _baseUri will be updated to be the new redirected Uri and the requrest
/// should be retried.</returns>
private bool EnsureSuccessfulResponse(HttpClient client, HttpStatusCode? expectedStatusCode = null)
{
HttpWebResponse response = null;
try
@ -230,6 +254,8 @@ namespace NuGet
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, String.Empty));
}
return true;
}
catch (WebException e)
{
@ -238,10 +264,31 @@ namespace NuGet
throw;
}
response = (HttpWebResponse)e.Response;
// Check if the error is caused by redirection
if (response.StatusCode == HttpStatusCode.MultipleChoices ||
response.StatusCode == HttpStatusCode.MovedPermanently ||
response.StatusCode == HttpStatusCode.Found ||
response.StatusCode == HttpStatusCode.SeeOther ||
response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
var location = response.Headers["Location"];
Uri newUri;
if (!Uri.TryCreate(client.Uri, location, out newUri))
{
throw;
}
_baseUri = new Lazy<Uri>(() => newUri);
return false;
}
if (expectedStatusCode != response.StatusCode)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageServerError, response.StatusDescription, e.Message), e);
}
return true;
}
finally
{

Просмотреть файл

@ -61,7 +61,9 @@ namespace NuGet
{ "MonoAndroid", "MonoAndroid" },
{ "MonoTouch", "MonoTouch" },
{ "MonoMac", "MonoMac" },
{ "native", "native"}
{ "native", "native"},
{ "WindowsPhoneApp", "WindowsPhoneApp"},
{ "wpa", "WindowsPhoneApp"}
};
private static readonly Dictionary<string, string> _knownProfiles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
@ -79,7 +81,8 @@ namespace NuGet
{ ".NETCore", "win"},
{ "Windows", "win"},
{ ".NETPortable", "portable" },
{ "WindowsPhone", "wp"}
{ "WindowsPhone", "wp"},
{ "WindowsPhoneApp", "wpa"}
};
private static readonly Dictionary<string, string> _identifierToProfileFolder = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
@ -111,6 +114,7 @@ namespace NuGet
{ new FrameworkName("WindowsPhone, Version=v7.0"), new FrameworkName("Silverlight, Version=v3.0, Profile=WindowsPhone") },
{ new FrameworkName("WindowsPhone, Version=v7.1"), new FrameworkName("Silverlight, Version=v4.0, Profile=WindowsPhone71") },
{ new FrameworkName("WindowsPhone, Version=v8.0"), new FrameworkName("Silverlight, Version=v8.0, Profile=WindowsPhone") },
{ new FrameworkName("WindowsPhone, Version=v8.1"), new FrameworkName("Silverlight, Version=v8.1, Profile=WindowsPhone") },
{ new FrameworkName("Windows, Version=v0.0"), new FrameworkName(".NETCore, Version=v4.5") },
{ new FrameworkName("Windows, Version=v8.0"), new FrameworkName(".NETCore, Version=v4.5") },

Просмотреть файл

@ -672,7 +672,8 @@ namespace NuGet.Dialog.Providers
project.GetTargetFrameworkName(),
this,
ignoreDependencies: false,
allowPrereleaseVersions: IncludePrerelease);
allowPrereleaseVersions: IncludePrerelease,
dependencyVersion: packageManager.DependencyVersion);
allOperations.AddRange(walker.ResolveOperations(package));
}
@ -693,8 +694,8 @@ namespace NuGet.Dialog.Providers
targetFramework,
this,
ignoreDependencies: false,
allowPrereleaseVersions: IncludePrerelease);
allowPrereleaseVersions: IncludePrerelease,
dependencyVersion: packageManager.DependencyVersion);
operations = walker.ResolveOperations(package).ToList();
return ShowLicenseAgreement(packageManager, operations);
}

Просмотреть файл

@ -177,7 +177,8 @@ namespace NuGet.Dialog.Providers
_project.GetTargetFrameworkName(),
logger: this,
ignoreDependencies: false,
allowPrereleaseVersions: IncludePrerelease);
allowPrereleaseVersions: IncludePrerelease,
dependencyVersion: activePackageManager.DependencyVersion);
var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease);
allOperations = installWalker.ResolveOperations(allPackages, out packagesByDependencyOrder);

Просмотреть файл

@ -44,6 +44,17 @@ namespace NuGet.Server.Infrastructure
{
throw new InvalidOperationException(String.Format(NuGetResources.Error_PackageAlreadyExists, package));
}
_cacheLock.EnterWriteLock();
try
{
_derivedDataLookup.Remove(package);
}
finally
{
_cacheLock.ExitWriteLock();
}
using (Stream stream = package.GetStream())
{
FileSystem.AddFile(fileName, stream);

Просмотреть файл

@ -57,8 +57,11 @@ namespace NuGet.VisualStudio
{
if (project != null && scriptFile != null)
{
logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), project.Name,
VersionUtility.GetShortFrameworkName(targetFramework));
// targetFramework can be null for unknown project types
string shortFramework = targetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(targetFramework);
logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(),
project.Name, shortFramework);
logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo_PowershellScripts,
Path.GetDirectoryName(scriptFile.Path), VersionUtility.GetTargetFrameworkLogString(scriptFile.TargetFramework));

Просмотреть файл

@ -8,6 +8,9 @@ using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using EnvDTE;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Project.Designers;
@ -133,15 +136,17 @@ namespace NuGet.VisualStudio
_waitDialogFactory.CreateInstance(out waitDialog);
try
{
waitDialog.StartWaitDialog(
VsResources.DialogTitle,
VsResources.PackageRestoreWaitMessage,
String.Empty,
varStatusBmpAnim: null,
szStatusBarText: null,
iDelayToShowDialog: 0,
fIsCancelable: false,
fShowMarqueeProgress: true);
// Start the wait dialog on the UI thread
InvokeOnUIThread(() =>
waitDialog.StartWaitDialog(
VsResources.DialogTitle,
VsResources.PackageRestoreWaitMessage,
String.Empty,
varStatusBmpAnim: null,
szStatusBarText: null,
iDelayToShowDialog: 0,
fIsCancelable: false,
fShowMarqueeProgress: true));
if (fromActivation)
{
@ -159,7 +164,8 @@ namespace NuGet.VisualStudio
finally
{
int canceled;
waitDialog.EndWaitDialog(out canceled);
InvokeOnUIThread(() => waitDialog.EndWaitDialog(out canceled));
}
if (fromActivation)
@ -283,7 +289,7 @@ namespace NuGet.VisualStudio
return;
}
if (!VsVersionHelper.IsVisualStudio2010 &&
if (!VsVersionHelper.IsVisualStudio2010 &&
(project.IsJavaScriptProject() || project.IsNativeProject()))
{
if (VsVersionHelper.IsVisualStudio2012)
@ -336,7 +342,7 @@ namespace NuGet.VisualStudio
private void AddNuGetTargets(MsBuildProject buildProject)
{
string targetsPath = Path.Combine(@"$(SolutionDir)", NuGetTargetsFile);
buildProject.AddImportStatement(targetsPath, ProjectImportLocation.Bottom);
NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, targetsPath, ProjectImportLocation.Bottom);
}
private void AddSolutionDirProperty(MsBuildProject buildProject)
@ -350,7 +356,7 @@ namespace NuGet.VisualStudio
buildProject.FullPath,
PathUtility.EnsureTrailingSlash(_solutionManager.SolutionDirectory));
relativeSolutionPath = PathUtility.EnsureTrailingSlash(relativeSolutionPath);
var solutionDirProperty = buildProject.Xml.AddProperty(solutiondir, relativeSolutionPath);
solutionDirProperty.Condition =
String.Format(
@ -381,7 +387,7 @@ namespace NuGet.VisualStudio
{
// download NuGet.Build and NuGet.CommandLine packages into the .nuget folder,
// using the active package source first and fall back to other enabled package sources.
IPackageRepository repository = CreatePackageRestoreRepository();
IPackageRepository repository = CreatePackageRestoreRepository();
var installPackages = new string[] { NuGetBuildPackageName, NuGetCommandLinePackageName };
foreach (var packageId in installPackages)
@ -608,5 +614,20 @@ namespace NuGet.VisualStudio
return new PackageReference[0];
}
/// <summary>
/// Invokes the action on the UI thread if one exists.
/// </summary>
private void InvokeOnUIThread(Action action)
{
if (Application.Current != null)
{
Application.Current.Dispatcher.Invoke(action);
}
else
{
action();
}
}
}
}

Просмотреть файл

@ -1,19 +1,19 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using EnvDTE;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Project.Designers;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using VSLangProj;
using VsWebSite;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
@ -357,10 +357,20 @@ namespace NuGet.VisualStudio
if (project.IsJavaScriptProject())
{
// HACK: The JS Metro project does not have a TargetFrameworkMoniker property set.
// We read the TargetPlatformVersion instead
// JavaScript apps do not have a TargetFrameworkMoniker property set.
// We read the TargetPlatformIdentifier and TargetPlatformVersion instead
string platformIdentifier = project.GetPropertyValue<string>("TargetPlatformIdentifier");
string platformVersion = project.GetPropertyValue<string>("TargetPlatformVersion");
return String.IsNullOrEmpty(platformVersion) ? "Windows, Version=0.0" : "Windows, Version=" + platformVersion;
// use the default values for JS if they were not given
if (String.IsNullOrEmpty(platformVersion))
platformVersion = "0.0";
if (String.IsNullOrEmpty(platformIdentifier))
platformIdentifier = "Windows";
return String.Format(CultureInfo.InvariantCulture, "{0}, Version={1}", platformIdentifier, platformVersion);
}
if (project.IsNativeProject())
@ -849,63 +859,13 @@ namespace NuGet.VisualStudio
}
public static void AddImportStatement(this Project project, string targetsPath, ProjectImportLocation location)
{
AddImportStatement(project.AsMSBuildProject(), targetsPath, location);
}
public static void AddImportStatement(this MsBuildProject buildProject, string targetsPath, ProjectImportLocation location)
{
// adds an <Import> element to this project file if it doesn't already exist.
if (buildProject.Xml.Imports == null ||
buildProject.Xml.Imports.All(import => !targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase)))
{
ProjectImportElement pie = buildProject.Xml.AddImport(targetsPath);
pie.Condition = "Exists('" + targetsPath + "')";
if (location == ProjectImportLocation.Top)
{
// There's no public constructor to create a ProjectImportElement directly.
// So we have to cheat by adding Import at the end, then remove it and insert at the beginning
pie.Parent.RemoveChild(pie);
buildProject.Xml.InsertBeforeChild(pie, buildProject.Xml.FirstChild);
}
else
{
// the import might get added into an ImportGroup. In this case,
// we remove it from the ImportGroup and add it at the end of the
// project.
if (pie.Parent.GetType() == typeof(ProjectImportGroupElement))
{
pie.Parent.RemoveChild(pie);
buildProject.Xml.AppendChild(pie);
}
}
NuGet.MSBuildProjectUtility.AddEnsureImportedTarget(buildProject, targetsPath);
buildProject.ReevaluateIfNecessary();
}
{
NuGet.MSBuildProjectUtility.AddImportStatement(project.AsMSBuildProject(), targetsPath, location);
}
public static void RemoveImportStatement(this Project project, string targetsPath)
{
RemoveImportStatement(project.AsMSBuildProject(), targetsPath);
}
public static void RemoveImportStatement(this MsBuildProject buildProject, string targetsPath)
{
if (buildProject.Xml.Imports != null)
{
// search for this import statement and remove it
var importElement = buildProject.Xml.Imports.FirstOrDefault(
import => targetsPath.Equals(import.Project, StringComparison.OrdinalIgnoreCase));
if (importElement != null)
{
importElement.Parent.RemoveChild(importElement);
NuGet.MSBuildProjectUtility.RemoveEnsureImportedTarget(buildProject, targetsPath);
buildProject.ReevaluateIfNecessary();
}
}
NuGet.MSBuildProjectUtility.RemoveImportStatement(project.AsMSBuildProject(), targetsPath);
}
/// <summary>
@ -1049,5 +1009,29 @@ namespace NuGet.VisualStudio
return Path.GetFileName(obj).GetHashCode();
}
}
/// <summary>
/// Check if the project has the SharedAssetsProject capability. This is true
/// for shared projects in universal apps.
/// </summary>
public static bool IsSharedProject(this Project project)
{
bool isShared = false;
var hier = project.ToVsHierarchy();
// VSHPROPID_ProjectCapabilities is a space delimited list of capabilities (Dev11+)
object capObj;
if (ErrorHandler.Succeeded(hier.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID5.VSHPROPID_ProjectCapabilities, out capObj)) && capObj != null)
{
string cap = capObj as string;
if (!String.IsNullOrEmpty(cap))
{
isShared = cap.Split(' ').Any(s => StringComparer.OrdinalIgnoreCase.Equals("SharedAssetsProject", s));
}
}
return isShared;
}
}
}

Просмотреть файл

@ -41,7 +41,7 @@ namespace NuGet.VisualStudio
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
if (VsVersionHelper.IsVisualStudio2012)
{
Project.DoWorkInWriterLock(buildProject => buildProject.AddImportStatement(relativeTargetPath, location));
Project.DoWorkInWriterLock(buildProject => NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, relativeTargetPath, location));
Project.Save(this);
}
else
@ -59,7 +59,10 @@ namespace NuGet.VisualStudio
NuGet.VisualStudio12.ProjectHelper.DoWorkInWriterLock(
Project,
Project.ToVsHierarchy(),
buildProject => buildProject.AddImportStatement(relativeTargetPath, location));
buildProject => NuGet.MSBuildProjectUtility.AddImportStatement(buildProject, relativeTargetPath, location));
// notify the project system of the change
UpdateImportStamp(Project);
}
public override void RemoveImport(string targetPath)
@ -79,7 +82,7 @@ namespace NuGet.VisualStudio
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
if (VsVersionHelper.IsVisualStudio2012)
{
Project.DoWorkInWriterLock(buildProject => buildProject.RemoveImportStatement(relativeTargetPath));
Project.DoWorkInWriterLock(buildProject => NuGet.MSBuildProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));
Project.Save(this);
}
else
@ -97,7 +100,10 @@ namespace NuGet.VisualStudio
NuGet.VisualStudio12.ProjectHelper.DoWorkInWriterLock(
Project,
Project.ToVsHierarchy(),
buildProject => buildProject.RemoveImportStatement(relativeTargetPath));
buildProject => NuGet.MSBuildProjectUtility.RemoveImportStatement(buildProject, relativeTargetPath));
// notify the project system of the change
UpdateImportStamp(Project);
}
}
}

Просмотреть файл

@ -8,7 +8,9 @@ using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem;
@ -391,8 +393,12 @@ namespace NuGet.VisualStudio
}
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.AddImportStatement(relativeTargetPath, location);
Project.AddImportStatement(relativeTargetPath, location);
Project.Save(this);
// notify the project system of the change
UpdateImportStamp(Project);
}
public virtual void RemoveImport(string targetPath)
@ -404,6 +410,9 @@ namespace NuGet.VisualStudio
string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath);
Project.RemoveImportStatement(relativeTargetPath);
Project.Save(this);
// notify the project system of the change
UpdateImportStamp(Project);
}
public virtual bool IsSupportedFile(string path)
@ -470,6 +479,25 @@ namespace NuGet.VisualStudio
return y.Path.CompareTo(x.Path);
}
/// <summary>
/// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out of date.
/// The value does not matter, it just needs to change.
/// </summary>
protected static void UpdateImportStamp(Project project)
{
// There is no reason to call this for pre-Dev12 project systems.
if (VsVersionHelper.IsVisualStudio2013)
{
IVsBuildPropertyStorage propStore = project.ToVsHierarchy() as IVsBuildPropertyStorage;
if (propStore != null)
{
// <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp>
string stamp = Guid.NewGuid().ToString().Split('-')[0];
ErrorHandler.ThrowOnFailure(propStore.SetPropertyValue("NuGetPackageImportStamp", string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp));
}
}
}
private static void TrySetCopyLocal(dynamic reference)
{
// Always set copy local to true for references that we add

Просмотреть файл

@ -53,5 +53,30 @@ namespace NuGet.VisualStudio
{
return ServiceLocator.GetInstance<ISettings>();
}
/// <summary>
/// Adds a new package source.
/// </summary>
/// <param name="name">Name of the new source.</param>
/// <param name="source">Value (uri) of the new source.</param>
public static void AddSource(string name, string source)
{
var packageSourceProvider = ServiceLocator.GetInstance<IPackageSourceProvider>();
var sources = packageSourceProvider.LoadPackageSources().ToList();
sources.Add(new PackageSource(source, name));
packageSourceProvider.SavePackageSources(sources);
}
/// <summary>
/// Removes a new package source.
/// </summary>
/// <param name="name">Name of the source.</param>
public static void RemoveSource(string name)
{
var packageSourceProvider = ServiceLocator.GetInstance<IPackageSourceProvider>();
var sources = packageSourceProvider.LoadPackageSources();
sources = sources.Where(s => s.Name != name).ToList();
packageSourceProvider.SavePackageSources(sources);
}
}
}

Просмотреть файл

@ -170,10 +170,7 @@ namespace NuGet.VisualStudio
ignoreDependencies,
allowPrereleaseVersions);
if (!WhatIf)
{
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
}
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
});
}
}
@ -196,6 +193,7 @@ namespace NuGet.VisualStudio
throw new ArgumentNullException("operations");
}
projectManager.DependencyVersion = DependencyVersion;
using (StartInstallOperation(package.Id, package.Version.ToString()))
{
ExecuteOperationsWithPackage(
@ -423,11 +421,11 @@ namespace NuGet.VisualStudio
foreach (Project project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
var oldWhatIfValue = projectManager.WhatIf;
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
foreach (var package in packages)
@ -447,6 +445,7 @@ namespace NuGet.VisualStudio
}
finally
{
projectManager.WhatIf = oldWhatIfValue;
eventListener.OnAfterAddPackageReference(project);
}
}
@ -539,7 +538,8 @@ namespace NuGet.VisualStudio
// NOTE THAT allowPrereleaseVersions should be true for pre-release packages alone, even if the user did not specify it
// since we are trying to reinstall packages here. However, ResolveOperations below will take care of this problem via allowPrereleaseVersionsBasedOnPackage parameter
var installWalker = new InstallWalker(LocalRepository, SourceRepository, null, logger ?? NullLogger.Instance,
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions);
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: DependencyVersion);
IList<IPackage> packagesUninstalledInDependencyOrder;
var operations = installWalker.ResolveOperations(allPackagesToBeReinstalled, out packagesUninstalledInDependencyOrder, allowPrereleaseVersionsBasedOnPackage: true);
@ -580,7 +580,8 @@ namespace NuGet.VisualStudio
// NOTE THAT allowPrereleaseVersions should be true for pre-release packages alone, even if the user did not specify it
// since we are trying to reinstall packages here. However, ResolveOperations below will take care of this problem via allowPrereleaseVersionsBasedOnPackage parameter
var installWalker = new InstallWalker(projectManager.LocalRepository, SourceRepository, projectManager.Project.TargetFramework, logger ?? NullLogger.Instance,
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions);
ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions,
dependencyVersion: DependencyVersion);
IList<IPackage> packagesUninstalledInDependencyOrder;
var operations = installWalker.ResolveOperations(packagesToBeReinstalled, out packagesUninstalledInDependencyOrder, allowPrereleaseVersionsBasedOnPackage: true);
@ -1420,7 +1421,14 @@ namespace NuGet.VisualStudio
// then we need to install it.
if (!LocalRepository.Exists(e.Package))
{
ExecuteInstall(e.Package);
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_InstallPackage, e.Package);
}
else
{
ExecuteInstall(e.Package);
}
}
};
@ -1520,8 +1528,9 @@ namespace NuGet.VisualStudio
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGet.Resources.NuGetResources.Log_PackageOperation,
operation.Action,
Logger.Log(
MessageLevel.Info,
NuGet.Resources.NuGetResources.Log_UninstallPackage,
operation.Package);
}
else
@ -1550,9 +1559,11 @@ namespace NuGet.VisualStudio
foreach (var project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
var oldWhatIfValue = projectManager.WhatIf;
try
{
InitializeLogger(logger, projectManager);
projectManager.WhatIf = WhatIf;
if (projectManager.LocalRepository.Exists(packageId))
{
@ -1574,6 +1585,7 @@ namespace NuGet.VisualStudio
}
finally
{
projectManager.WhatIf = oldWhatIfValue;
ClearLogger(projectManager);
}
}

Просмотреть файл

@ -315,4 +315,4 @@
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
</Project>

Просмотреть файл

@ -132,7 +132,7 @@ namespace NuGet.VisualStudio
repository = CreateFallbackRepository(repository);
}
RepositoryInfo info = GetRepositoryInfo();
return new VsPackageManager(_solutionManager,
var packageManager = new VsPackageManager(_solutionManager,
repository,
_fileSystemProvider,
info.FileSystem,
@ -142,6 +142,8 @@ namespace NuGet.VisualStudio
new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)),
_packageEvents,
_frameworkMultiTargeting);
packageManager.DependencyVersion = GetDependencyVersion();
return packageManager;
}
public IVsPackageManager CreatePackageManagerWithAllPackageSources()
@ -227,6 +229,30 @@ namespace NuGet.VisualStudio
return _repositoryInfo;
}
/// <summary>
/// Returns the user specified DependencyVersion in nuget.config.
/// </summary>
/// <returns>The user specified DependencyVersion value in nuget.config.</returns>
private DependencyVersion GetDependencyVersion()
{
string configFolderPath = _repositorySettings.ConfigFolderPath;
IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath);
var settings = Settings.LoadDefaultSettings(
configSettingsFileSystem,
configFileName: null,
machineWideSettings: _machineWideSettings);
string dependencyVersionValue = settings.GetConfigValue("DependencyVersion");
DependencyVersion dependencyVersion;
if (Enum.TryParse(dependencyVersionValue, ignoreCase: true, result:out dependencyVersion))
{
return dependencyVersion;
}
else
{
return DependencyVersion.Lowest;
}
}
private PackageSaveModes CalculatePackageSaveMode(ISettings settings)
{
PackageSaveModes retValue = PackageSaveModes.None;

Просмотреть файл

@ -49,29 +49,50 @@ namespace NuGet.VisualStudio
return Path.GetDirectoryName(projectFileFullPath);
}
// Attempt to determine the project path using the available EnvDTE.Project properties.
// Project systems using async load such as CPS may not have all properties populated
// for start up scenarios such as VS Templates. In these cases we need to fallback
// until we can find one containing the full path.
// FullPath
string fullPath = GetPropertyValue<string>(project, "FullPath");
if (!String.IsNullOrEmpty(fullPath))
{
// Some Project System implementations (JS metro app) return the project
// file as FullPath. We only need the parent directory
if (File.Exists(fullPath))
{
fullPath = Path.GetDirectoryName(fullPath);
return Path.GetDirectoryName(fullPath);
}
}
else
{
// C++ projects do not have FullPath property, but do have ProjectDirectory one.
fullPath = GetPropertyValue<string>(project, "ProjectDirectory");
return fullPath;
}
return fullPath;
// C++ projects do not have FullPath property, but do have ProjectDirectory one.
string projectDirectory = GetPropertyValue<string>(project, "ProjectDirectory");
if (!String.IsNullOrEmpty(projectDirectory))
{
return projectDirectory;
}
// FullName
if (!String.IsNullOrEmpty(project.FullName))
{
return Path.GetDirectoryName(project.FullName);
}
Debug.Fail("Unable to find the project path");
return null;
}
public static bool IsSupported(Project project)
{
Debug.Assert(project != null);
return project.Kind != null && _supportedProjectTypes.Contains(project.Kind);
return project.Kind != null && _supportedProjectTypes.Contains(project.Kind) && !project.IsSharedProject();
}
public static T GetPropertyValue<T>(Project project, string propertyName)

Просмотреть файл

@ -1,36 +1,52 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell.Interop;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using EnvDTE;
#if VS12
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.Designers;
using NuGet;
using System.Threading;
#endif
using Microsoft.VisualStudio.Shell.Interop;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
namespace NuGet.VisualStudio12
{
public static class ProjectHelper
{
#if VS12
public static async void DoWorkInWriterLock(EnvDTE.Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
/// <summary>
/// Performs an action inside a VS internal writer lock. If called from the UI thread this method will
/// run async to avoid deadlocks.
/// </summary>
public static void DoWorkInWriterLock(Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
{
await DoWorkInWriterLock((IVsProject)hierarchy, action);
var fileSystem = new PhysicalFileSystem(@"c:\");
fileSystem.MakeFileWritable(project.FullName);
project.Save();
// Perform this work on a new thread to avoid moving our current thread, and so it can be done async if needed.
var task = Task.Run(() => DoWorkInWriterLockInternal(project, hierarchy, action));
// Check if we are running on the UI thread. If we are we cannot risk blocking and holding the lock.
// Ideally all calls involving the lock should be done on a background thread from the start to
// keep the call as synchronous as possible within NuGet.
if (!Microsoft.VisualStudio.Shell.ThreadHelper.CheckAccess())
{
// If we are on a background thread we can safely run synchronously.
task.Wait();
}
}
private static async Task DoWorkInWriterLock(IVsProject project, Action<MsBuildProject> action)
private static async Task DoWorkInWriterLockInternal(Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
{
UnconfiguredProject unconfiguredProject = GetUnconfiguredProject(project);
UnconfiguredProject unconfiguredProject = GetUnconfiguredProject((IVsProject)hierarchy);
if (unconfiguredProject != null)
{
var service = unconfiguredProject.ProjectService.Services.ProjectLockService;
if (service != null)
{
// WriteLockAsync will move us to a background thread.
using (ProjectWriteLockReleaser x = await service.WriteLockAsync())
{
await x.CheckoutAsync(unconfiguredProject.FullPath);
@ -45,7 +61,17 @@ namespace NuGet.VisualStudio12
await x.ReleaseAsync();
}
await unconfiguredProject.ProjectService.Services.ThreadingPolicy.SwitchToUIThread();
// perform the save synchronously
await Task.Run(() =>
{
// move to the UI thread for the rest of this method
unconfiguredProject.ProjectService.Services.ThreadingPolicy.SwitchToUIThread();
var fileSystem = new PhysicalFileSystem(@"c:\");
fileSystem.MakeFileWritable(project.FullName);
project.Save();
}
);
}
}
}
@ -61,7 +87,7 @@ namespace NuGet.VisualStudio12
object extObject;
if (ErrorHandler.Succeeded(hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extObject)))
{
EnvDTE.Project dteProject = extObject as EnvDTE.Project;
Project dteProject = extObject as Project;
if (dteProject != null)
{
context = dteProject.Object as IVsBrowseObjectContext;
@ -73,7 +99,7 @@ namespace NuGet.VisualStudio12
return context != null ? context.UnconfiguredProject : null;
}
#else
public static void DoWorkInWriterLock(EnvDTE.Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
public static void DoWorkInWriterLock(Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
{
}
#endif

Просмотреть файл

@ -53,6 +53,12 @@
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>DependencyVersion</maml:name>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
@ -107,12 +113,24 @@
<maml:para>Indicates whether this command will consider prerelease packages. If omitted, only stable packages are considered.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
<maml:description>
<maml:para>Indicates what this command should do if a file from the package's content folder already exists in the project.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
<maml:description>
<maml:para>Indicates what this command should do if a file from the package's content folder already exists in the project.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>DependencyVersion</maml:name>
<maml:description>
<maml:para>Specifies which dependency package version to install. If omitted, this defaults to the lowest required version.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
<maml:description>
<maml:para>Displays the actions that would be taken and the effect of the command, instead of executing the command.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<!-- Examples section -->
@ -420,6 +438,9 @@
<maml:name>Version</maml:name>
<command:parameterValue required="true">string</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
@ -465,6 +486,12 @@
string
</command:parameterValue>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
<maml:description>
<maml:para>Displays the actions that would be taken and the effect of the command, instead of executing the command.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>
@ -580,6 +607,9 @@
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
</command:parameter>
</command:syntaxItem>
</command:syntax>
@ -646,12 +676,18 @@
<maml:para>Reinstall packages with the existing versions.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
<maml:description>
<maml:para>Indicates what this command should do if a file from the package's content folder already exists in the project.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>FileConflictAction</maml:name>
<maml:description>
<maml:para>Indicates what this command should do if a file from the package's content folder already exists in the project.</maml:para>
</maml:description>
</command:parameter>
<command:parameter required="false" position="named">
<maml:name>WhatIf</maml:name>
<maml:description>
<maml:para>Displays the actions that would be taken and the effect of the command, instead of executing the command.</maml:para>
</maml:description>
</command:parameter>
</command:parameters>
<command:examples>

Просмотреть файл

@ -47,8 +47,7 @@ namespace NuGet.PowerShell.Commands
_productUpdateService = productUpdateService;
_repositoryFactory = repositoryFactory;
_packageSourceProvider = packageSourceProvider;
DependencyVersion = DependencyVersion.Lowest;
if (networkAvailable)
{
_isNetworkAvailable = isNetworkAvailable();
@ -85,7 +84,7 @@ namespace NuGet.PowerShell.Commands
public SwitchParameter WhatIf { get; set; }
[Parameter]
public DependencyVersion DependencyVersion { get; set; }
public DependencyVersion? DependencyVersion { get; set; }
private string _fallbackToLocalCacheMessge = Resources.Cmdlet_FallbackToCache;
private string _localCacheFailureMessage = Resources.Cmdlet_LocalCacheFailure;
@ -173,17 +172,23 @@ namespace NuGet.PowerShell.Commands
{
return;
}
PackageManager.WhatIf = WhatIf;
if (DependencyVersion.HasValue)
{
PackageManager.DependencyVersion = DependencyVersion.Value;
}
if (ProjectManager != null)
{
ProjectManager.DependencyVersion = DependencyVersion;
ProjectManager.DependencyVersion = PackageManager.DependencyVersion;
ProjectManager.WhatIf = WhatIf;
}
if (!String.IsNullOrEmpty(_cacheStatusMessage))
{
this.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, _cacheStatusMessage, _packageSourceProvider.ActivePackageSource, Source));
}
}
if (IsDowngradePackage())
{
PackageManager.UpdatePackage(ProjectManager, Id, Version, !IgnoreDependencies, IncludePrerelease.IsPresent, logger: this);
@ -272,8 +277,6 @@ namespace NuGet.PowerShell.Commands
return;
}
packageManager.DependencyVersion = DependencyVersion;
packageManager.WhatIf = WhatIf;
packageManager.InstallPackage(ProjectManager, Id, Version, IgnoreDependencies, IncludePrerelease.IsPresent, logger: this);
}
}

Просмотреть файл

@ -60,6 +60,12 @@ Register-TabExpansion 'Install-Package' @{
'Source' = {
GetPackageSources
}
'DependencyVersion' = {
GetEnumNames 'NuGet.DependencyVersion'
}
'FileConflictAction' = {
GetEnumNames 'NuGet.PowerShell.Commands.FileConflictAction'
}
}
Register-TabExpansion 'Uninstall-Package' @{
@ -107,6 +113,9 @@ Register-TabExpansion 'Update-Package' @{
'Source' = {
GetPackageSources
}
'FileConflictAction' = {
GetEnumNames 'NuGet.PowerShell.Commands.FileConflictAction'
}
}
Register-TabExpansion 'Open-PackagePage' @{
@ -187,6 +196,11 @@ function GetPackageSources() {
$allSources | Select-Object -ExpandProperty Name
}
function GetEnumNames($typeName) {
# Sort the enumerations in alphabetical order to make it consistent with TabExpansion2
return [System.Enum]::GetNames($typeName) | Sort-Object
}
function GetInstalledPackageVersions($context) {
$parameters = @{}
if ($context.id) { $parameters.filter = $context.id }

Просмотреть файл

@ -90,6 +90,11 @@ namespace NuGet.VsEvents
{
_errorListProvider.Tasks.Clear();
if (Action == vsBuildAction.vsBuildActionClean)
{
return;
}
if (UsingOldPackageRestore(_dte.Solution))
{
return;
@ -347,11 +352,11 @@ namespace NuGet.VsEvents
{
WriteLine(VerbosityLevel.Normal, Resources.RestoringPackage, package);
// during package restore, use local cache as the primary source, other active sources
// as secondary source.
var activePackageSourceRepository = ServiceLocator.GetInstance<IPackageRepository>();
var repository = new PriorityPackageRepository(NuGet.MachineCache.Default, activePackageSourceRepository);
// during package restore, use local cache as the primary source, other sources
// as secondary source.
IVsPackageManagerFactory packageManagerFactory = ServiceLocator.GetInstance<IVsPackageManagerFactory>();
var allSources = packageManagerFactory.CreatePackageManagerWithAllPackageSources().SourceRepository;
var repository = new PriorityPackageRepository(NuGet.MachineCache.Default, allSources);
var packageManager = packageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: false);
using (packageManager.SourceRepository.StartOperation(RepositoryOperationNames.Restore, package.Id, package.Version.ToString()))
{

4
src/VsEvents/Resources.Designer.cs сгенерированный
Просмотреть файл

@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@ -181,7 +181,7 @@ namespace NuGet.VsEvents {
}
/// <summary>
/// Looks up a localized string similar to Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. For more information, visit http://docs.nuget.org/docs/workflows/reinstalling-packages. Packages affected: {0}.
/// Looks up a localized string similar to Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Visit http://docs.nuget.org/docs/workflows/reinstalling-packages for more information. Packages affected: {0}.
/// </summary>
internal static string ProjectUpgradeAndRetargetErrorMessage {
get {

Просмотреть файл

@ -162,7 +162,7 @@ Missing packages: {0}</value>
<value>Error occurred while restoring NuGet packages: {0}</value>
</data>
<data name="ProjectUpgradeAndRetargetErrorMessage" xml:space="preserve">
<value>Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. For more information, visit http://docs.nuget.org/docs/workflows/reinstalling-packages. Packages affected: {0}</value>
<value>Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Visit http://docs.nuget.org/docs/workflows/reinstalling-packages for more information. Packages affected: {0}</value>
</data>
<data name="PackageRestoreCanceled" xml:space="preserve">
<value>NuGet package restore canceled.</value>

Просмотреть файл

@ -15,6 +15,7 @@ using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.PlatformUI;
@ -208,7 +209,17 @@ namespace NuGet.Tools
// the <Import> element added.
if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
{
PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
if (VsVersionHelper.IsVisualStudio2013)
{
// Run on a background thread in VS2013 to avoid CPS hangs. The modal loading dialog will block
// until this completes.
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false)));
}
else
{
PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
}
}
// when NuGet loads, if the current solution has some package
@ -433,7 +444,17 @@ namespace NuGet.Tools
private void EnablePackagesRestore(object sender, EventArgs args)
{
_packageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: true);
if (VsVersionHelper.IsVisualStudio2013)
{
// This method is called by the UI thread when the user clicks the menu item. To avoid
// hangs on CPS project systems this needs to be done on a background thread.
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
_packageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: true)));
}
else
{
_packageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: true);
}
}
private void QueryStatusEnablePackagesRestore(object sender, EventArgs args)

Просмотреть файл

@ -71,6 +71,7 @@
<Compile Include="PackCommandTest.cs" />
<Compile Include="ProgramTest.cs" />
<Compile Include="ProjectFactoryTest.cs" />
<Compile Include="ProjectHelperTest.cs" />
<Compile Include="PushCommandTest.cs" />
<Compile Include="ResourceHelperTests.cs" />
<Compile Include="RestoreCommandTest.cs" />

Просмотреть файл

@ -430,6 +430,8 @@ namespace NuGet.Test.NuGetCommandLine.Commands
Assert.Equal(@"Baz.0.7\Baz.0.7.nupkg", fileSystem.Paths.Single().Key);
}
// Test that when installing a specific version, if NoCache is false, then
// local cache will be used to locate the package.
[Fact]
public void InstallCommandUsesLocalCacheIfNoCacheIsFalse()
{
@ -439,7 +441,8 @@ namespace NuGet.Test.NuGetCommandLine.Commands
localCache.Setup(c => c.GetPackages()).Returns(new[] { PackageUtility.CreatePackage("Gamma") }.AsQueryable()).Verifiable();
var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem, machineCacheRepository: localCache.Object)
{
NoCache = false
NoCache = false,
Version = "1.0"
};
installCommand.Arguments.Add("Gamma");
installCommand.Source.Add("Some Source name");
@ -453,6 +456,30 @@ namespace NuGet.Test.NuGetCommandLine.Commands
localCache.Verify();
}
// Test that if version is not specified, then local cache will not be used
// even if NoCache if false.
[Fact]
public void InstallCommandNotUseLocalCacheIfVersionNotSpecified()
{
// Arrange
var fileSystem = new MockFileSystem();
var localCache = new Mock<IPackageRepository>(MockBehavior.Strict);
var installCommand = new TestInstallCommand(GetFactory(), GetSourceProvider(), fileSystem, machineCacheRepository: localCache.Object)
{
NoCache = false
};
installCommand.Arguments.Add("Baz");
installCommand.Source.Add("Some Source name");
installCommand.Source.Add("Some other Source");
// Act
installCommand.ExecuteCommand();
// Assert
Assert.Equal(@"Baz.0.7\Baz.0.7.nupkg", fileSystem.Paths.Single().Key);
localCache.Verify(c => c.GetPackages(), Times.Never());
}
[Fact]
public void InstallCommandDoesNotUseLocalCacheIfNoCacheIsTrue()
{

Просмотреть файл

@ -0,0 +1,21 @@
using System;
using NuGet.Common;
using Xunit;
using Xunit.Extensions;
namespace NuGet.Test.NuGetCommandLine
{
public class ProjectHelperTest
{
[Theory]
[InlineData(".csproj")]
[InlineData(".vbproj")]
[InlineData(".fsproj")]
[InlineData(".vcxproj")]
[InlineData(".jsproj")]
public void ProjectHelperSupportedExtensions(string fileExtension)
{
Assert.True(ProjectHelper.SupportedProjectExtensions.Contains(fileExtension));
}
}
}

Просмотреть файл

@ -60,7 +60,8 @@ namespace NuGet.Test
new MockPackageRepository(),
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'.");
@ -87,7 +88,8 @@ namespace NuGet.Test
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
@ -122,7 +124,8 @@ namespace NuGet.Test
repository.Object,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
@ -163,7 +166,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'.");
@ -212,7 +216,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var packages = resolver.ResolveOperations(packageA).ToList();
@ -278,7 +283,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var operations = resolver.ResolveOperations(packageA).ToList();
@ -436,7 +442,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
@ -526,7 +533,8 @@ namespace NuGet.Test
null,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo.");
@ -551,7 +559,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'.");
@ -578,7 +587,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'.");
@ -625,7 +635,8 @@ namespace NuGet.Test
sourceRepository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act & Assert
var packages = resolver.ResolveOperations(packageA).ToList();
@ -1118,10 +1129,8 @@ namespace NuGet.Test
repository,
NullLogger.Instance,
ignoreDependencies: false,
allowPrereleaseVersions: false)
{
DependencyVersion = DependencyVersion.HighestPatch
};
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.HighestPatch);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
@ -1171,10 +1180,8 @@ namespace NuGet.Test
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false)
{
DependencyVersion = DependencyVersion.Lowest
};
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
@ -1220,10 +1227,8 @@ namespace NuGet.Test
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false)
{
DependencyVersion = DependencyVersion.HighestPatch
};
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.HighestPatch);
// Act
var packages = resolver.ResolveOperations(A10).ToList();
@ -1280,7 +1285,8 @@ namespace NuGet.Test
logger: NullLogger.Instance,
targetFramework: null,
ignoreDependencies: false,
allowPrereleaseVersions: false);
allowPrereleaseVersions: false,
dependencyVersion: DependencyVersion.Lowest);
var updatePackages = new List<IPackage> { A20, B20, C20 };
IList<IPackage> allUpdatePackagesByDependencyOrder;

Просмотреть файл

@ -28,28 +28,6 @@ namespace NuGet.Test
Assert.Equal("test token value", mockProjectSystem.Object.OpenFile("foo.bar").ReadToEnd());
}
// Tests that the generated file contains byte order mark for UTF-8.
[Fact]
public void TransformFileGeneratedFileContainsBom()
{
// Arrange
var processor = new Preprocessor();
var mockProjectSystem = new Mock<MockProjectSystem>() { CallBase = true };
mockProjectSystem.Setup(m => m.GetPropertyValue("token")).Returns("token value");
var mockFile = new Mock<IPackageFile>();
mockFile.Setup(m => m.Path).Returns("foo.bar.pp");
mockFile.Setup(m => m.GetStream()).Returns(() => GetStream("test $token$"));
// Act
processor.TransformFile(mockFile.Object, "foo.bar", mockProjectSystem.Object);
// Assert
var bytes = mockProjectSystem.Object.OpenFile("foo.bar").ReadAllBytes();
Assert.Equal(0xEF, bytes[0]);
Assert.Equal(0xBB, bytes[1]);
Assert.Equal(0xBF, bytes[2]);
}
[Fact]
public void TransformFileDoesNothingIfFileExists()
{

Просмотреть файл

@ -208,6 +208,24 @@ namespace NuGet.Test
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedWindowsPhoneAppNames()
{
// Arrange
var knownNameFormats = new[] { "WindowsPhoneApp", "wpa" };
Version defaultVersion = new Version("0.0");
// Act
var frameworkNames = knownNameFormats.Select(fmt => VersionUtility.ParseFrameworkName(fmt));
// Assert
foreach (var frameworkName in frameworkNames)
{
Assert.Equal("WindowsPhoneApp", frameworkName.Identifier);
Assert.Equal(defaultVersion, frameworkName.Version);
}
}
[Fact]
public void ParseFrameworkNameNormalizesSupportedWinRTFrameworkNames()
{
@ -904,6 +922,8 @@ namespace NuGet.Test
FrameworkName wp7 = VersionUtility.ParseFrameworkName("sl3-wp");
FrameworkName wp7Mango = VersionUtility.ParseFrameworkName("sl4-wp71");
FrameworkName wp8 = new FrameworkName("WindowsPhone, Version=v8.0");
FrameworkName wp81 = new FrameworkName("WindowsPhone, Version=v8.1");
FrameworkName wpa81 = VersionUtility.ParseFrameworkName("wpa81");
// Act
bool wp7MangoCompatibleWithwp7 = VersionUtility.IsCompatible(wp7, wp7Mango);
@ -915,6 +935,10 @@ namespace NuGet.Test
bool wp8CompatibleWithwp7 = VersionUtility.IsCompatible(wp7, wp8);
bool wp8CompatbielWithwp7Mango = VersionUtility.IsCompatible(wp7Mango, wp8);
bool wp81CompatibleWithwp8 = VersionUtility.IsCompatible(wp81, wp8);
bool wpa81CompatibleWithwp81 = VersionUtility.IsCompatible(wpa81, wp81);
// Assert
Assert.False(wp7MangoCompatibleWithwp7);
Assert.True(wp7CompatibleWithwp7Mango);
@ -924,6 +948,10 @@ namespace NuGet.Test
Assert.False(wp8CompatibleWithwp7);
Assert.False(wp8CompatbielWithwp7Mango);
Assert.True(wp81CompatibleWithwp8);
Assert.False(wpa81CompatibleWithwp81);
}
[Theory]
@ -1298,15 +1326,17 @@ namespace NuGet.Test
Assert.Equal("wp71", shortName);
}
[Fact]
public void IsCompatibleReturnsTrueForPortableFrameworkAndNormalFramework()
[Theory]
[InlineData("portable-netcore45+sl4", "silverlight45")]
[InlineData("portable-net40+win8+sl4+wp71+wpa81", "wp81")]
public void IsCompatibleReturnsTrueForPortableFrameworkAndNormalFramework(string packageFramework, string projectFramework)
{
// Arrange
var portableFramework = VersionUtility.ParseFrameworkName("portable-netcore45+sl4");
var normalFramework = VersionUtility.ParseFrameworkName("silverlight45");
var packagePortableFramework = VersionUtility.ParseFrameworkName(packageFramework);
var projectPortableFramework = VersionUtility.ParseFrameworkName(projectFramework);
// Act
bool isCompatible = VersionUtility.IsCompatible(normalFramework, portableFramework);
bool isCompatible = VersionUtility.IsCompatible(projectPortableFramework, packagePortableFramework);
// Assert
Assert.True(isCompatible);
@ -1363,6 +1393,10 @@ namespace NuGet.Test
[InlineData("portable-netcore45+sl4+wp", "portable-netcore45+sl4")]
[InlineData("portable-netcore45+sl4+wp", "portable-netcore5+wp7")]
[InlineData("portable-netcore45+sl4+wp+net", "portable-wp7")]
[InlineData("portable-net40+win8+sl4+wp71+wpa81", "portable-wpa81+wp81")]
[InlineData("portable-wp8+wpa81", "portable-wpa81+wp81")]
[InlineData("portable-wp81+wpa81", "portable-wpa81+wp81")]
[InlineData("portable-wpa81+wp81", "portable-wpa81+wp81")]
public void IsCompatibleReturnsTrueForPortableFrameworkAndPortableFramework(string packageFramework, string projectFramework)
{
// Arrange
@ -1381,6 +1415,7 @@ namespace NuGet.Test
[InlineData("portable-netcore45+sl4+wp", "portable-netcore5+wp7+net")]
[InlineData("portable-netcore45+sl4+wp+net", "portable-wp7+netcore4")]
[InlineData("portable-netcore45+sl4", "portable-net4+wp7")]
[InlineData("portable-net40+win8+sl4+wp71", "portable-wpa81+wp81")]
public void IsCompatibleReturnsFalseForPortableFrameworkAndPortableFramework(string packageFramework, string projectFramework)
{
// Arrange

Просмотреть файл

@ -66,6 +66,41 @@ namespace NuGet.Test
", mockProjectSystem.OpenFile("web.config").ReadToEnd());
}
// Regression test for the bug that XDT won't work when xml nodes have
// attributes.
[Fact]
public void XdtTransformOnXmlNodeWithAttributes()
{
// Arrange
var mockProjectSystem = new MockProjectSystem();
var mockRepository = new MockPackageRepository();
mockProjectSystem.AddFile("test.xml",
@"<a attrib=""b""/>".AsStream());
var projectManager = new ProjectManager(mockRepository, new DefaultPackagePathResolver(new MockProjectSystem()), mockProjectSystem, new MockPackageRepository());
var package = new Mock<IPackage>();
package.Setup(m => m.Id).Returns("A");
package.Setup(m => m.Version).Returns(new SemanticVersion("1.0"));
package.Setup(m => m.Listed).Returns(true);
var file = new Mock<IPackageFile>();
file.Setup(m => m.Path).Returns(@"content\test.xml.install.xdt");
file.Setup(m => m.EffectivePath).Returns("test.xml.install.xdt");
file.Setup(m => m.GetStream()).Returns(() =>
@"<a xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform""><test xdt:Transform=""InsertIfMissing""/></a>".AsStream());
package.Setup(m => m.GetFiles()).Returns(new[] { file.Object });
mockRepository.AddPackage(package.Object);
// Act
projectManager.AddPackageReference("A");
// Assert
Assert.True(mockProjectSystem.FileExists("test.xml"));
var actual = mockProjectSystem.OpenFile("test.xml").ReadToEnd();
Assert.Equal("<a attrib=\"b\">\t<test/></a>", actual);
}
[Fact]
public void ReThrowWithMeaningfulErrorMessageWhenXdtFileHasSyntaxError()
{

Просмотреть файл

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>Java</id>
<version>1.0.0</version>
<authors>juste</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Contains content files for both WindowsPhoneApp 8.1 and Windows 8.1 projects.</description>
</metadata>
<files>
<file src="content\windowsphoneapp81\phone.txt" target="content\windowsphoneapp81\phone.txt" />
<file src="content\wpa81\phone2.txt" target="content\wpa81\phone2.txt" />
<file src="content\windows81\store.txt" target="content\windows81\store.txt" />
</files>
</package>

Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="A:1.0" Label="A:1.0" />
<Node Id="B:1.0.0" Label="B:1.0.0" />
<Node Id="B:1.0.1" Label="B:1.0.1" />
<Node Id="B:1.2.0" Label="B:1.2.0" />
<Node Id="B:1.2.1" Label="B:1.2.1" />
<Node Id="B:2.0.0" Label="B:2.0.0" />
<Node Id="B:2.0.1" Label="B:2.0.1" />
</Nodes>
<Links>
<Link Source="A:1.0" Target="B:1.0.0" />
</Links>
</DirectedGraph>

Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="A:1.0" Label="A:1.0" />
<Node Id="B:1.0.0" Label="B:1.0.0" />
<Node Id="B:1.0.1" Label="B:1.0.1" />
<Node Id="B:1.2.0" Label="B:1.2.0" />
<Node Id="B:1.2.1" Label="B:1.2.1" />
<Node Id="B:2.0.0" Label="B:2.0.0" />
<Node Id="B:2.0.1" Label="B:2.0.1" />
</Nodes>
<Links>
<Link Source="A:1.0" Target="B:1.0.0" />
</Links>
</DirectedGraph>

Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="A:1.0" Label="A:1.0" />
<Node Id="B:1.0.0" Label="B:1.0.0" />
<Node Id="B:1.0.1" Label="B:1.0.1" />
<Node Id="B:1.2.0" Label="B:1.2.0" />
<Node Id="B:1.2.1" Label="B:1.2.1" />
<Node Id="B:2.0.0" Label="B:2.0.0" />
<Node Id="B:2.0.1" Label="B:2.0.1" />
</Nodes>
<Links>
<Link Source="A:1.0" Target="B:1.0.0" />
</Links>
</DirectedGraph>

Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="A:1.0" Label="A:1.0" />
<Node Id="B:1.0.0" Label="B:1.0.0" />
<Node Id="B:1.0.1" Label="B:1.0.1" />
<Node Id="B:1.2.0" Label="B:1.2.0" />
<Node Id="B:1.2.1" Label="B:1.2.1" />
<Node Id="B:2.0.0" Label="B:2.0.0" />
<Node Id="B:2.0.1" Label="B:2.0.1" />
</Nodes>
<Links>
<Link Source="A:1.0" Target="B:1.0.0" />
</Links>
</DirectedGraph>

Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="A:1.0" Label="A:1.0" />
<Node Id="B:1.0.0" Label="B:1.0.0" />
<Node Id="B:1.0.1" Label="B:1.0.1" />
<Node Id="B:1.2.0" Label="B:1.2.0" />
<Node Id="B:1.2.1" Label="B:1.2.1" />
<Node Id="B:2.0.0" Label="B:2.0.0" />
<Node Id="B:2.0.1" Label="B:2.0.1" />
</Nodes>
<Links>
<Link Source="A:1.0" Target="B:1.0.0" />
</Links>
</DirectedGraph>

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
$if$ ($targetframeworkversion$ >= 4.0)<supportedRuntime version="v4.0" sku=".NETFramework,Version=v$targetframeworkversion$,Profile=Client" />$endif$$if$ ($targetframeworkversion$ < 4.0)<supportedRuntime version="v2.0.50727" />$endif$
</startup>
</configuration>

Просмотреть файл

@ -0,0 +1,7 @@
Module $safeitemname$
Sub Main()
End Sub
End Module

Просмотреть файл

@ -0,0 +1,13 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:$clrversion$
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On

Просмотреть файл

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>2</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>

Просмотреть файл

@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:$clrversion$
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("$safeprojectname$.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace

Просмотреть файл

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

Просмотреть файл

@ -0,0 +1,73 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:$clrversion$
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.$safeprojectname$.My.MySettings
Get
Return Global.$safeprojectname$.My.MySettings.Default
End Get
End Property
End Module
End Namespace

Просмотреть файл

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

Просмотреть файл

@ -0,0 +1,35 @@
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("$projectname$")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("$registeredorganization$")>
<Assembly: AssemblyProduct("$projectname$")>
<Assembly: AssemblyCopyright("Copyright © $registeredorganization$ $year$")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("$guid1$")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

Просмотреть файл

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>
</SchemaVersion>
<ProjectGuid>{$guid2$}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>$safeprojectname$.Module1</StartupObject>
<RootNamespace>$safeprojectname$</RootNamespace>
<AssemblyName>$safeprojectname$</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v$targetframeworkversion$</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>$safeprojectname$.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>$safeprojectname$.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
$if$ ($targetframeworkversion$ >= 3.5)
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
$endif$
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
$if$ ($targetframeworkversion$ >= 3.5)
<Import Include="System.Linq" />
<Import Include="System.Xml.Linq" />
$endif$
</ItemGroup>
<ItemGroup>
<Compile Include="Module1.vb"/>
<Compile Include="My Project\AssemblyInfo.vb"/>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
$if$ ($targetframeworkversion$ > 4.0)
<None Include="App.config" />
$endif$
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,28 @@
<VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name Package="{164B10B9-B200-11D0-8C61-00A0C91E29D5}" ID="3002" />
<Description Package="{164B10B9-B200-11D0-8C61-00A0C91E29D5}" ID="3003" />
<Icon Package="{164B10B9-B200-11D0-8C61-00A0C91E29D5}" ID="4501" />
<ProjectType>VisualBasic</ProjectType>
<TemplateID>Microsoft.VisualBasic.Windows.ConsoleApplication</TemplateID>
<SortOrder>12</SortOrder>
<NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
<CreateNewFolder>true</CreateNewFolder>
<DefaultName>ConsoleApplication</DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
<RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
</TemplateData>
<TemplateContent>
<Project File="ConsoleApplication.vbproj" ReplaceParameters="true">
<ProjectItem ReplaceParameters="true" OpenInEditor="true" OpenOrder="10">Module1.vb</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
<ProjectItem ReplaceParameters="false" TargetFileName="My Project\Application.myapp">MyApplication.myapp</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="My Project\Application.Designer.vb">MyApplication.Designer.vb</ProjectItem>
<ProjectItem ReplaceParameters="false" TargetFileName="My Project\Resources.resx">Resources.resx</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="My Project\Resources.Designer.vb">Resources.Designer.vb</ProjectItem>
<ProjectItem ReplaceParameters="false" TargetFileName="My Project\Settings.settings">Settings.settings</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="My Project\Settings.Designer.vb">Settings.Designer.vb</ProjectItem>
<ProjectItem ReplaceParameters="true">App.config</ProjectItem>
</Project>
</TemplateContent>
</VSTemplate>

Просмотреть файл

@ -0,0 +1,23 @@
<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
<TemplateData>
<Name>WindowsPhoneAppJS81</Name>
<Description>windows phone app </Description>
<ProjectType>JavaScript</ProjectType>
<ProjectSubType>
</ProjectSubType>
<SortOrder>1000</SortOrder>
<CreateNewFolder>true</CreateNewFolder>
<DefaultName>WindowsPhoneAppJS81</DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
<LocationField>Enabled</LocationField>
<EnableLocationBrowseButton>true</EnableLocationBrowseButton>
<Icon>__TemplateIcon.ico</Icon>
</TemplateData>
<TemplateContent>
<Project TargetFileName="WindowsPhoneAppJS81.jsproj" File="WindowsPhoneAppJS81.jsproj" ReplaceParameters="true">
<ProjectItem ReplaceParameters="true" TargetFileName="default.html">default.html</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="default.js">default.js</ProjectItem>
<ProjectItem ReplaceParameters="false" TargetFileName="package.appxmanifest">package.appxmanifest</ProjectItem>
</Project>
</TemplateContent>
</VSTemplate>

Просмотреть файл

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|AnyCPU">
<Configuration>Debug</Configuration>
<Platform>AnyCPU</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x86">
<Configuration>Debug</Configuration>
<Platform>x86</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|AnyCPU">
<Configuration>Release</Configuration>
<Platform>AnyCPU</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x86">
<Configuration>Release</Configuration>
<Platform>x86</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>d4c6567d-aca4-4bdd-9584-6f01d1edf9b1</ProjectGuid>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup Condition="'$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0'">
<VisualStudioVersion>12.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).Default.props" />
<PropertyGroup Label="Configuration">
<TargetPlatformIdentifier>WindowsPhoneApp</TargetPlatformIdentifier>
<TargetPlatformVersion>8.1</TargetPlatformVersion>
<RequiredPlatformVersion>8.1</RequiredPlatformVersion>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).props" />
<PropertyGroup>
<DefaultLanguage>en-US</DefaultLanguage>
</PropertyGroup>
<ItemGroup>
<AppxManifest Include="package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<Content Include="default.html" />
<Content Include="default.js" />
</ItemGroup>
<ItemGroup>
<SDKReference Include="Microsoft.Phone.WinJS.2.1, Version=1.0" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).targets" />
<!-- To modify your build process, add your task inside one of the targets below then uncomment
that target and the DisableFastUpToDateCheck PropertyGroup.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
<PropertyGroup>
<DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
</PropertyGroup>
-->
</Project>

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.9 KiB

Просмотреть файл

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>$safeprojectname$</title>
<!-- WinJS references -->
<link href="/css/ui-themed.css" rel="stylesheet" />
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<!-- $safeprojectname$ references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<p>Content goes here</p>
</body>
</html>

Просмотреть файл

@ -0,0 +1,32 @@
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=329104
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
app.start();
})();

Просмотреть файл

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest" xmlns:m3="http://schemas.microsoft.com/appx/2014/manifest" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest">
<Identity
Name="$guid1$"
Version="1.0.0.0"
Publisher="$XmlEscapedPublisherDistinguishedName$" />
<mp:PhoneIdentity PhoneProductId="ddb21aea-a1f8-4aa4-9ffd-0312ddaae7c2" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>$projectname$</DisplayName>
<PublisherDisplayName>$XmlEscapedPublisher$</PublisherDisplayName>
<Logo>images\storelogo.png</Logo>
</Properties>
<Prerequisites>
<OSMinVersion>6.3.1</OSMinVersion>
<OSMaxVersionTested>6.3.1</OSMaxVersionTested>
</Prerequisites>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application
Id="App"
StartPage="default.html">
<m3:VisualElements
DisplayName="$projectname$"
Square150x150Logo="images\Logo.png"
Square44x44Logo="images\SmallLogo.png"
Description="$projectname$"
ForegroundText="light"
BackgroundColor="transparent">
<m3:DefaultTile Wide310x150Logo="images\WideLogo.png" Square71x71Logo="images\Square71x71Logo.png" />
<m3:SplashScreen Image="images\SplashScreen.png" />
<m3:ApplicationView MinWidth="width320"/>
<!--Used in XAML Designer. DO NOT REMOVE-->
</m3:VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
</Capabilities>
</Package>

Просмотреть файл

@ -254,6 +254,94 @@ function Test-PackageRestore-IsAutomaticIsFalse {
}
}
# Test that during package restore, all sources are used.
function Test-PackageRestore-AllSourcesAreUsed {
param($context)
$tempDirectory = $Env:temp
$source1 = Join-Path $tempDirectory ([System.IO.Path]::GetRandomFileName())
$source2 = Join-Path $tempDirectory ([System.IO.Path]::GetRandomFileName())
try {
# Arrange
New-Item $source1 -ItemType directory
New-Item $source2 -ItemType directory
[NuGet.VisualStudio.SettingsHelper]::AddSource('testSource1', $source1);
[NuGet.VisualStudio.SettingsHelper]::AddSource('testSource2', $source2);
CreateTestPackage 'p1' '1.0' $source1
CreateTestPackage 'p2' '1.0' $source2
# Arrange
# create project and install packages
$proj = New-ClassLibrary
$proj | Install-Package p1 -source testSource1
$proj | Install-Package p2 -source testSource2
Assert-Package $proj p1
Assert-Package $proj p2
# Arrange
# delete the packages folder
$packagesDir = Get-PackagesDir
RemoveDirectory $packagesDir
Assert-False (Test-Path $packagesDir)
# Act
Build-Solution
# Assert
# both p1 and p2 are restored
Assert-True (Test-Path (Join-Path $packagesDir 'p1.1.0' ))
Assert-True (Test-Path (Join-Path $packagesDir 'p2.1.0' ))
}
finally
{
[NuGet.VisualStudio.SettingsHelper]::RemoveSource('testSource1')
[NuGet.VisualStudio.SettingsHelper]::RemoveSource('testSource2')
RemoveDirectory $source1
RemoveDirectory $source2
# change active package source to "All"
$componentService = Get-VSComponentModel
$packageSourceProvider = $componentService.GetService([NuGet.VisualStudio.IVsPackageSourceProvider])
$packageSourceProvider.ActivePackageSource = [NuGet.VisualStudio.AggregatePackageSource]::Instance
}
}
# Create a test package
function CreateTestPackage {
param(
[string]$id,
[string]$version,
[string]$outputDirectory
)
$builder = New-Object NuGet.PackageBuilder
$builder.Authors.Add("test_author")
$builder.Id = $id
$builder.Version = New-Object NuGet.SemanticVersion($version)
$builder.Description = "description"
# add one content file
$tempFile = [IO.Path]::GetTempFileName()
"test" >> $tempFile
$packageFile = New-Object NuGet.PhysicalPackageFile
$packageFile.SourcePath = $tempFile
$packageFile.TargetPath = "content\$id-test1.txt"
$builder.Files.Add($packageFile)
# create the package file
$outputFileName = Join-Path $outputDirectory "$id.$version.nupkg"
$outputStream = New-Object IO.FileStream($outputFileName, [System.IO.FileMode]::Create)
try {
$builder.Save($outputStream)
}
finally
{
$outputStream.Dispose()
Remove-Item $tempFile
}
}
function GetBuildOutput {
$dte2 = Get-Interface $dte ([EnvDTE80.DTE2])
$buildPane = $dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Build")
@ -272,7 +360,7 @@ function RemoveDirectory {
{
if (Test-Path $dir)
{
Remove-Item -Recurse -Force $packagesDir -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force $dir -ErrorAction SilentlyContinue
}
else
{

Просмотреть файл

@ -63,7 +63,7 @@ function Test-EnablePackageRestoreModifyProjectThatInstallNewPackages
Assert-AreEqual "true" (Get-MsBuildPropertyValue $p "RestorePackages")
}
function NoTest-EnablePackageRestoreOnCspProjects
function Test-EnablePackageRestoreOnCpsProjects
{
if ($dte.Version -eq "10.0")
{
@ -85,4 +85,39 @@ function NoTest-EnablePackageRestoreOnCspProjects
# Assert
Assert-AreEqual "true" (Get-MsBuildPropertyValue $p1 "RestorePackages")
Assert-AreEqual "true" (Get-MsBuildPropertyValue $p2 "RestorePackages")
}
# Tests that package restore works correctly with Visual Basic projects
function Test-PackageRestoreVisualBasicProject
{
param($context)
# Arrange
$p1 = New-VBConsoleApplication
$p1 | Install-Package ninject
$p1.Save()
Enable-PackageRestore
$packagesDir = Get-PackagesDir
Assert-True (Test-Path $packagesDir)
$solutionDir = $dte.Solution.FullName
$dte.Solution.SaveAs($solutionDir)
Close-Solution
# delete the packages folder
Remove-Item -Recurse -Force $packagesDir
Assert-False (Test-Path $packagesDir)
# reopen the solution.
Open-Solution $solutionDir
# Act
Build-Solution
# Assert
# the packages folder is restored
Assert-True (Test-Path $packagesDir)
}

Просмотреть файл

@ -21,7 +21,7 @@ function ProjectRetargeting-ShowErrorUponRetargeting {
$error = $errorlist[$errorlist.Count-1]
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. For more information, visit http://docs.nuget.org/docs/workflows/reinstalling-packages. Packages affected: PackageTargetingNet40AndNet40Client' $error.Description
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Visit http://docs.nuget.org/docs/workflows/reinstalling-packages for more information. Packages affected: PackageTargetingNet40AndNet40Client' $error.Description
}
function ProjectRetargeting-ClearErrorUponCleanProject {
@ -152,7 +152,7 @@ function ProjectRetargeting-ConvertBuildErrorToBuildWarningUponBuild {
$warning = $warnings[$warnings.Count - 1]
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. For more information, visit http://docs.nuget.org/docs/workflows/reinstalling-packages. Packages affected: PackageTargetingNet40AndNet40Client' $warning.Description
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Visit http://docs.nuget.org/docs/workflows/reinstalling-packages for more information. Packages affected: PackageTargetingNet40AndNet40Client' $warning.Description
}
function ProjectRetargeting-ShowWarningOnCleanBuild
@ -186,7 +186,7 @@ function ProjectRetargeting-ShowWarningOnCleanBuild
$warning = $warnings[$warnings.Count - 1]
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. For more information, visit http://docs.nuget.org/docs/workflows/reinstalling-packages. Packages affected: PackageTargetingNet40AndNet40Client' $warning.Description
Assert-AreEqual 'Some NuGet packages were installed using a target framework different from the current target framework and may need to be reinstalled. Visit http://docs.nuget.org/docs/workflows/reinstalling-packages for more information. Packages affected: PackageTargetingNet40AndNet40Client' $warning.Description
}
function ProjectRetargeting-ClearWarningUponCleanProject

Просмотреть файл

@ -419,4 +419,39 @@ function Test-InstallPackageCommandShowTabExpansionForPreReleasePackagesIfPreRel
Assert-AreEqual 1 $suggestions.Count
Assert-AreEqual 'MyPackage' $suggestions[0]
}
}
function Test-InstallPackageCommandShowTabExpansionForDependencyVersion {
# Act
$suggestions = @(TabExpansion 'Install-Package -DependencyVersion ')
# Assert
Assert-AreEqual 4 $suggestions.Count
Assert-AreEqual 'Highest' $suggestions[0]
Assert-AreEqual 'HighestMinor' $suggestions[1]
Assert-AreEqual 'HighestPatch' $suggestions[2]
Assert-AreEqual 'Lowest' $suggestions[3]
}
function Test-InstallPackageCommandShowTabExpansionForFileConflictAction {
# Act
$suggestions = @(TabExpansion 'Install-Package -FileConflictAction ')
# Assert
Assert-AreEqual 3 $suggestions.Count
Assert-AreEqual 'Ignore' $suggestions[0]
Assert-AreEqual 'None' $suggestions[1]
Assert-AreEqual 'Overwrite' $suggestions[2]
}
function Test-UpdatePackageCommandShowTabExpansionForFileConflictAction {
# Act
$suggestions = @(TabExpansion 'Update-Package -FileConflictAction ')
# Assert
Assert-AreEqual 3 $suggestions.Count
Assert-AreEqual 'Ignore' $suggestions[0]
Assert-AreEqual 'None' $suggestions[1]
Assert-AreEqual 'Overwrite' $suggestions[2]
}

Просмотреть файл

@ -25,6 +25,22 @@ function Test-PackageInstallWhatIf {
Assert-Null (Get-ProjectPackage $project FakeItEasy)
}
# Test install-package -WhatIf to downgrade an installed package.
function Test-PackageInstallDowngradeWhatIf {
# Arrange
$project = New-ConsoleApplication
Install-Package TestUpdatePackage -Version 2.0.0.0 -Source $context.RepositoryRoot
Assert-Package $project TestUpdatePackage '2.0.0.0'
# Act
Install-Package TestUpdatePackage -Version 1.0.0.0 -Source $context.RepositoryRoot -WhatIf
# Assert
# that the installed package is not touched.
Assert-Package $project TestUpdatePackage '2.0.0.0'
}
function Test-WebsiteSimpleInstall {
param(
$context
@ -2264,7 +2280,7 @@ function Test-NonFrameworkAssemblyReferenceShouldHaveABindingRedirect
Assert-BindingRedirect $p app.config System.Web.Razor '0.0.0.0-3.0.0.0' '3.0.0.0'
}
function Test-InstallPackageIntoJavascriptApplication
function Test-InstallPackageIntoJavaScriptApplication
{
if ($dte.Version -eq "10.0")
{
@ -2281,6 +2297,24 @@ function Test-InstallPackageIntoJavascriptApplication
Assert-Package $p "jQuery"
}
function Test-InstallPackageIntoJavaScriptWindowsPhoneApp
{
# this test is only applicable to VS 2013 on Windows 8.1
if ($dte.Version -eq "10.0" -or $dte.Version -eq "11.0" -or [System.Environment]::OSVersion.Version -lt 6.3)
{
return;
}
# Arrange
$p = New-JavaScriptWindowsPhoneApp81
# Act
Install-Package jQuery -ProjectName $p.Name
# Assert
Assert-Package $p "jQuery"
}
function Test-InstallPackageIntoNativeWinStoreApplication
{
if ($dte.Version -eq "10.0")
@ -2321,6 +2355,31 @@ function Test-InstallPackageIntoJSAppOnWin81UseTheCorrectFxFolder
Assert-Null (Get-ProjectItem $p 'windows8.txt')
}
function Test-InstallPackageIntoJSWindowsPhoneAppOnWin81UseTheCorrectFxFolder
{
param($context)
# this test is only applicable to VS 2013 on Windows 8.1
if ($dte.Version -eq "10.0" -or $dte.Version -eq "11.0" -or [System.Environment]::OSVersion.Version -lt 6.3)
{
return
}
# Arrange
$p = New-JavaScriptWindowsPhoneApp81
# Act
Install-Package Java -ProjectName $p.Name -source $context.RepositoryPath
# Assert
Assert-Package $p Java
Assert-NotNull (Get-ProjectItem $p 'phone.txt')
Assert-NotNull (Get-ProjectItem $p 'phone2.txt')
Assert-Null (Get-ProjectItem $p 'store.txt')
}
function Test-SpecifyDifferentVersionThenServerVersion
{
# In this test, we explicitly set the version as "2.0",
@ -2558,21 +2617,107 @@ function Test-InstallPackageAddMoreEntriesToProjectConfigFile
Assert-Null (Get-ProjectItem $p 'packages.config')
}
# Tests that when -DependencyVersion HighestPath is specified, the dependency with
# Tests that when -DependencyVersion HighestPatch is specified, the dependency with
# the largest patch number is installed
function Test-InstallPackageWithDependencyVersionHighest
function Test-InstallPackageWithDependencyVersionHighestPatch
{
param($context)
# A depends on B >= 1.0.0
# Available versions of B are: 1.0.0, 1.0.1, 1.2.0, 1.2.1, 2.0.0, 2.0.1
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package jquery.validation -version 1.10 -DependencyVersion HighestPatch
$p | Install-Package A -Source $context.RepositoryPath -DependencyVersion HighestPatch
# Assert
Assert-Package $p jquery.validation 1.10
Assert-Package $p jquery 1.4.4
Assert-Package $p A 1.0
Assert-Package $p B 1.0.1
}
# Tests that when -DependencyVersion HighestPatch is specified, the dependency with
# the lowest major, highest minor, highest patch is installed
function Test-InstallPackageWithDependencyVersionHighestMinor
{
param($context)
# A depends on B >= 1.0.0
# Available versions of B are: 1.0.0, 1.0.1, 1.2.0, 1.2.1, 2.0.0, 2.0.1
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package A -Source $context.RepositoryPath -DependencyVersion HighestMinor
# Assert
Assert-Package $p A 1.0
Assert-Package $p B 1.2.1
}
# Tests that when -DependencyVersion Highest is specified, the dependency with
# the highest version installed
function Test-InstallPackageWithDependencyVersionHighest
{
param($context)
# A depends on B >= 1.0.0
# Available versions of B are: 1.0.0, 1.0.1, 1.2.0, 1.2.1, 2.0.0, 2.0.1
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package A -Source $context.RepositoryPath -DependencyVersion Highest
# Assert
Assert-Package $p A 1.0
Assert-Package $p B 2.0.1
}
# Tests that when -DependencyVersion is lowest, the dependency with
# the smallest patch number is installed
function Test-InstallPackageWithDependencyVersionLowest
{
param($context)
# A depends on B >= 1.0.0
# Available versions of B are: 1.0.0, 1.0.1, 1.2.0, 1.2.1, 2.0.0, 2.0.1
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package A -Source $context.RepositoryPath -DependencyVersion Lowest
# Assert
Assert-Package $p A 1.0
Assert-Package $p B 1.0.0
}
# Tests the case when DependencyVersion is specified in nuget.config
function Test-InstallPackageWithDependencyVersionHighestInNuGetConfig
{
param($context)
try {
[NuGet.VisualStudio.SettingsHelper]::Set('DependencyVersion', 'HighestPatch')
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package jquery.validation -version 1.10
# Assert
Assert-Package $p jquery.validation 1.10
Assert-Package $p jquery 1.4.4
}
finally {
[NuGet.VisualStudio.SettingsHelper]::Set('DependencyVersion', $null)
}
}
# Tests that when -DependencyVersion is not specified, the dependency with
@ -2581,13 +2726,16 @@ function Test-InstallPackageWithoutDependencyVersion
{
param($context)
# A depends on B >= 1.0.0
# Available versions of B are: 1.0.0, 1.0.1, 1.2.0, 1.2.1, 2.0.0, 2.0.1
# Arrange
$p = New-ClassLibrary
# Act
$p | Install-Package jquery.validation -version 1.10
$p | Install-Package A -Source $context.RepositoryPath
# Assert
Assert-Package $p jquery.validation 1.10
Assert-Package $p jquery 1.4.1
Assert-Package $p A 1.0
Assert-Package $p B 1.0.0
}

Просмотреть файл

@ -33,20 +33,20 @@ function Test-UpdatingPackageInProjectDoesntRemoveFromSolutionIfInUse {
}
function Test-UpdatingPackageWithPackageSaveModeNuspec {
# Arrange
try {
[NuGet.VisualStudio.SettingsHelper]::Set('PackageSaveMode', 'nuspec')
$p = New-ClassLibrary
Install-Package Castle.Core -Version 1.2.0 -Project $p.Name
Assert-Package $p Castle.Core 1.2.0
# Arrange
try {
[NuGet.VisualStudio.SettingsHelper]::Set('PackageSaveMode', 'nuspec')
$p = New-ClassLibrary
Install-Package Castle.Core -Version 1.2.0 -Project $p.Name
Assert-Package $p Castle.Core 1.2.0
# Act
Update-Package Castle.Core
# Act
Update-Package Castle.Core
# Assert
# Assert-Package $p Castle.Core 2.5.1
}
# Assert
# Assert-Package $p Castle.Core 2.5.1
}
finally {
[NuGet.VisualStudio.SettingsHelper]::Set('PackageSaveMode', $null)
}
@ -61,7 +61,7 @@ function Test-UpdatingPackageWithSharedDependency {
$p = New-ClassLibrary
# Act
Install-Package D -Version 1.0 -Source $context.RepositoryPath
Install-Package D -Version 1.0 -Source $context.RepositoryPath
Assert-Package $p D 1.0
Assert-Package $p B 1.0
Assert-Package $p C 1.0
@ -104,15 +104,15 @@ function Test-UpdatingPackageDependentPackageVersion {
# Arrange
$p = New-ClassLibrary
Install-Package jquery.validation -Version 1.8
Install-Package jquery.validation -Version 1.8
Assert-Package $p jquery.validation 1.8
Assert-Package $p jquery 1.4.1
# Act
Update-Package jquery -version 2.0.3
# Act
Update-Package jquery -version 2.0.3
# Assert: jquery.validation is updated to 1.8.0.1
Assert-Package $p jquery 2.0.3
# Assert: jquery.validation is updated to 1.8.0.1
Assert-Package $p jquery 2.0.3
Assert-Package $p jquery.validation 1.8.0.1
}
@ -124,17 +124,17 @@ function Test-UpdatingPackageWhatIf {
# Arrange
$p = New-ClassLibrary
Install-Package D -Version 1.0 -Source $context.RepositoryPath
Install-Package D -Version 1.0 -Source $context.RepositoryPath
Assert-Package $p D 1.0
Assert-Package $p B 1.0
Assert-Package $p C 1.0
Assert-Package $p A 2.0
# Act
Update-Package D -Source $context.RepositoryPath -WhatIf
# Act
Update-Package D -Source $context.RepositoryPath -WhatIf
# Assert: no packages are touched
Assert-Package $p D 1.0
# Assert: no packages are touched
Assert-Package $p D 1.0
Assert-Package $p B 1.0
Assert-Package $p C 1.0
Assert-Package $p A 2.0
@ -147,11 +147,11 @@ function Test-UpdatingPackageWhatIfCannotBeUsedWithReinstall {
# Arrange
$p = New-ClassLibrary
Install-Package Castle.Core -Version 1.2.0 -Project $p.Name
Install-Package Castle.Core -Version 1.2.0 -Project $p.Name
Assert-Package $p Castle.Core 1.2.0
# Act & Assert
Assert-Throws { Update-Package Castle.Core -Reinstall -WhatIf } "Specifying both -Reinstall and -WhatIf is not supported for now."
# Act & Assert
Assert-Throws { Update-Package Castle.Core -Reinstall -WhatIf } "Specifying both -Reinstall and -WhatIf is not supported for now."
}
function Test-UpdatingPackageWithSharedDependencySimple {
@ -540,11 +540,11 @@ function Test-UpdatePackageInAllProjects {
Update-Package Ninject
# Assert
Assert-SolutionPackage Ninject 3.0.1.10
Assert-Package $p1 Ninject 3.0.1.10
Assert-Package $p2 Ninject 3.0.1.10
Assert-Package $p3 Ninject 3.0.1.10
Assert-Package $p4 Ninject 3.0.1.10
Assert-SolutionPackage Ninject 3.2.2.0
Assert-Package $p1 Ninject 3.2.2.0
Assert-Package $p2 Ninject 3.2.2.0
Assert-Package $p3 Ninject 3.2.2.0
Assert-Package $p4 Ninject 3.2.2.0
Assert-Null (Get-SolutionPackage Ninject 2.0.1.0)
Assert-Null (Get-SolutionPackage Ninject 2.1.0.76)
Assert-Null (Get-SolutionPackage Ninject 2.2.0.0)
@ -1000,7 +1000,7 @@ function Test-UpdatePackageDowngradesIfNewVersionLessThanInstalledPrereleaseVers
$p | Install-Package -Source $context.RepositoryRoot -Id PreReleaseTestPackage -Version 1.0.1-a -Prerelease
Assert-Package $p 'PreReleaseTestPackage' 1.0.1-a
$p | Update-Package -Source $context.RepositoryRoot -Id PreReleaseTestPackage -Version 1.0
$p | Update-Package -Source $context.RepositoryRoot -Id PreReleaseTestPackage -Version 1.0
Assert-Package $p 'PreReleaseTestPackage' 1.0
}
@ -1518,59 +1518,95 @@ function Test-UpdatePackageThrowsWhenOnlyUnusedVersionsOfAPackageIsPresentInPack
function Test-UpdatePackageWithContentInLicenseBlocks
{
param($context)
param($context)
# Arrange
$p = New-ClassLibrary
# Arrange
$p = New-ClassLibrary
$name = 'PackageWithTextFile'
$name = 'PackageWithTextFile'
Install-Package $name -Version 1.0 -Source $context.RepositoryRoot
$packages = Get-PackagesDir
$fooFilePath = Join-Path $packages "$name.1.0\content\text"
Install-Package $name -Version 1.0 -Source $context.RepositoryRoot
$packages = Get-PackagesDir
$fooFilePath = Join-Path $packages "$name.1.0\content\text"
Assert-True (Test-Path $fooFilePath)
Assert-True (Test-Path $fooFilePath)
'***************NUget: Begin License Text ---------dsafdsafdas
'***************NUget: Begin License Text ---------dsafdsafdas
sdaflkjdsal;fj;ldsafdsa
dsaflkjdsa;lkfj;ldsafas
dsafdsafdsafsdaNuGet: End License Text-------------
This is a text file 1.0' > $fooFilePath
# Act
Update-Package $name -Source $context.RepositoryRoot
# Act
Update-Package $name -Source $context.RepositoryRoot
# Assert
Assert-Package $p $name '2.0'
$textFilePathInProject = Join-Path (Get-ProjectDir $p) 'text'
Assert-True (Test-Path $textFilePathInProject)
# Assert
Assert-Package $p $name '2.0'
$textFilePathInProject = Join-Path (Get-ProjectDir $p) 'text'
Assert-True (Test-Path $textFilePathInProject)
Assert-AreEqual 'This is a text file 2.0' (Get-Content $textFilePathInProject)
Assert-AreEqual 'This is a text file 2.0' (Get-Content $textFilePathInProject)
}
function Test-UpdatePackagePreservesProjectConfigFile
{
param($context)
# Arrange
$p = New-ClassLibrary "CoolProject"
$p | Install-Package TestUpdatePackage -version 1.0 -source $context.RepositoryRoot
$file = Get-ProjectItem $p 'packages.config'
Assert-NotNull $file
# rename it
$file.Name = 'packages.CoolProject.config'
# Act
$p | Update-Package TestUpdatePackage -source $context.RepositoryRoot
# Assert
Assert-Package $p TestUpdatePackage '2.0'
Assert-NotNull (Get-ProjectItem $p 'packages.CoolProject.config')
Assert-Null (Get-ProjectItem $p 'packages.config')
function Test-UpdatePackagePreservesProjectConfigFile
{
param($context)
# Arrange
$p = New-ClassLibrary "CoolProject"
$p | Install-Package TestUpdatePackage -version 1.0 -source $context.RepositoryRoot
$file = Get-ProjectItem $p 'packages.config'
Assert-NotNull $file
# rename it
$file.Name = 'packages.CoolProject.config'
# Act
$p | Update-Package TestUpdatePackage -source $context.RepositoryRoot
# Assert
Assert-Package $p TestUpdatePackage '2.0'
Assert-NotNull (Get-ProjectItem $p 'packages.CoolProject.config')
Assert-Null (Get-ProjectItem $p 'packages.config')
}
# Test update-package -WhatIf to downgrade an installed package.
function Test-UpdatePackageDowngradeWhatIf {
# Arrange
$project = New-ConsoleApplication
Install-Package TestUpdatePackage -Version 2.0.0.0 -Source $context.RepositoryRoot
Assert-Package $project TestUpdatePackage '2.0.0.0'
# Act
Update-Package TestUpdatePackage -Version 1.0.0.0 -Source $context.RepositoryRoot -WhatIf
# Assert
# that the installed package is not touched.
Assert-Package $project TestUpdatePackage '2.0.0.0'
}
# Test update-package -WhatIf when there are multiple projects
function Test-UpdatePackageWhatIfMultipleProjects {
# Arrange
$p1 = New-ConsoleApplication
$p2 = New-ConsoleApplication
$p1 | Install-Package TestUpdatePackage -Version 1.0.0.0 -Source $context.RepositoryRoot
$p2 | Install-Package TestUpdatePackage -Version 1.0.0.0 -Source $context.RepositoryRoot
Assert-Package $p1 TestUpdatePackage '1.0.0.0'
Assert-Package $p2 TestUpdatePackage '1.0.0.0'
# Act
Update-Package TestUpdatePackage -Source $context.RepositoryRoot -WhatIf
# Assert
# that the installed packages are not touched in either projects
Assert-Package $p1 TestUpdatePackage '1.0.0.0'
Assert-Package $p2 TestUpdatePackage '1.0.0.0'
}

Просмотреть файл

@ -87,7 +87,7 @@ function New-Project {
if (!$ProjectName) {
$ProjectName = $TemplateName + "_$id"
}
# Make sure there is a solution
Ensure-Solution
@ -287,6 +287,24 @@ function New-JavaScriptApplication81
}
}
function New-JavaScriptWindowsPhoneApp81
{
param(
[string]$ProjectName,
[parameter(ValueFromPipeline = $true)]$SolutionFolder
)
try
{
$SolutionFolder | New-Project WindowsPhoneApp81JS $ProjectName
}
catch {
# If we're unable to create the project that means we probably don't have some SDK installed
# Signal to the runner that we want to skip this test
throw "SKIP: $($_)"
}
}
function New-NativeWinStoreApplication
{
param(
@ -330,6 +348,15 @@ function New-WebApplication {
$SolutionFolder | New-Project EmptyWebApplicationProject40 $ProjectName
}
function New-VBConsoleApplication {
param(
[string]$ProjectName,
[parameter(ValueFromPipeline = $true)]$SolutionFolder
)
$SolutionFolder | New-Project VBConsoleApplication $ProjectName
}
function New-MvcApplication {
param(
[string]$ProjectName,
@ -729,6 +756,11 @@ function Enable-PackageRestore {
}
$componentService = Get-VSComponentModel
# change active package source to "All"
$packageSourceProvider = $componentService.GetService([NuGet.VisualStudio.IVsPackageSourceProvider])
$packageSourceProvider.ActivePackageSource = [NuGet.VisualStudio.AggregatePackageSource]::Instance
$packageRestoreManager = $componentService.GetService([NuGet.VisualStudio.IPackageRestoreManager])
$packageRestoreManager.EnableCurrentSolutionForRestore($false)
}

Просмотреть файл

@ -6,9 +6,7 @@ namespace NuGet.Test.Integration
{
public class CommandRunner
{
private static readonly int Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
public static Tuple<int, string> Run(string process, string workingDirectory, string arguments, bool waitForExit)
public static Tuple<int, string> Run(string process, string workingDirectory, string arguments, bool waitForExit, int timeOutInMilliseconds = 60000)
{
string result = String.Empty;
@ -32,16 +30,21 @@ namespace NuGet.Test.Integration
standardOutput = p.StandardOutput;
errorOutput = p.StandardError;
if (waitForExit)
{
bool processExited = p.WaitForExit(timeOutInMilliseconds);
if (!processExited)
{
p.Kill();
}
}
result = standardOutput.ReadToEnd();
if (string.IsNullOrEmpty(result))
{
result = errorOutput.ReadToEnd();
}
if (waitForExit)
{
p.WaitForExit(Timeout);
}
if (p.HasExited)
{
exitCode = p.ExitCode;

Просмотреть файл

@ -0,0 +1,366 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace NuGet.Test.Integration
{
/// <summary>
/// A Mock Server that is used to mimic a NuGet Server.
/// </summary>
class MockServer
{
HttpListener _listener;
RouteTable _get, _put, _delete;
string _endPoint;
Task _listenerTask;
/// <summary>
/// Initializes an instance of MockServer.
/// </summary>
/// <param name="endPoint">The endpoint of the server.</param>
public MockServer(string endPoint)
{
_endPoint = endPoint;
_listener = new HttpListener();
_listener.Prefixes.Add(endPoint);
_get = new RouteTable();
_put = new RouteTable();
_delete = new RouteTable();
}
public RouteTable Get
{
get { return _get; }
}
public RouteTable Put
{
get { return _put; }
}
public RouteTable Delete
{
get { return _delete; }
}
/// <summary>
/// Starts the mock server.
/// </summary>
public void Start()
{
_listener.Start();
_listenerTask = Task.Factory.StartNew(() => HandleRequest());
}
/// <summary>
/// Stops the mock server.
/// </summary>
public void Stop()
{
_listener.Abort();
_listenerTask.Wait();
}
/// <summary>
/// Gets the pushed package from a nuget push request.
/// </summary>
/// <param name="r">The request generated by nuget push command.</param>
/// <returns>The content of the package that is pushed.</returns>
public static byte[] GetPushedPackage(HttpListenerRequest r)
{
byte[] buffer;
using (var memoryStream = new MemoryStream())
{
r.InputStream.CopyTo(memoryStream);
buffer = memoryStream.ToArray();
}
byte[] result = new byte[] { };
var multipartContentType = "multipart/form-data; boundary=";
if (!r.ContentType.StartsWith(multipartContentType, StringComparison.Ordinal))
{
return result;
}
var boundary = r.ContentType.Substring(multipartContentType.Length);
byte[] delimiter = Encoding.UTF8.GetBytes("\r\n--" + boundary);
int bodyStartIndex = Find(buffer, 0, new byte[] { 0x0d, 0x0a, 0x0d, 0x0a });
if (bodyStartIndex == -1)
{
return result;
}
else
{
bodyStartIndex += 4;
}
int bodyEndIndex = Find(buffer, 0, delimiter);
if (bodyEndIndex == -1)
{
return result;
}
result = buffer.Skip(bodyStartIndex).Take(bodyEndIndex - bodyStartIndex).ToArray();
return result;
}
/// <summary>
/// Returns the index of the first occurrence of <paramref name="pattern"/> in
/// <paramref name="buffer"/>. The search starts at a specified position.
/// </summary>
/// <param name="buffer">The buffer to search.</param>
/// <param name="startIndex">The search start position.</param>
/// <param name="pattern">The pattern to search.</param>
/// <returns>The index position of <paramref name="pattern"/> if it is found in buffer, or -1
/// if not.</returns>
private static int Find(byte[] buffer, int startIndex, byte[] pattern)
{
for (int s = startIndex; s + pattern.Length <= buffer.Length; ++s)
{
if (StartsWith(buffer, s, pattern))
{
return s;
}
}
return -1;
}
/// <summary>
/// Determines if the subset of <paramref name="buffer"/> starting at
/// <paramref name="startIndex"/> starts with <paramref name="pattern"/>.
/// </summary>
/// <param name="buffer">The buffer to check.</param>
/// <param name="startIndex">The start index of the subset to check.</param>
/// <param name="pattern">The pattern to search.</param>
/// <returns>True if the subset starts with the pattern; otherwise, false.</returns>
private static bool StartsWith(byte[] buffer, int startIndex, byte[] pattern)
{
if (startIndex + pattern.Length > buffer.Length)
{
return false;
}
for (int i = 0; i < pattern.Length; ++i)
{
if (buffer[startIndex + i] != pattern[i])
{
return false;
}
}
return true;
}
public static void SetResponseContent(HttpListenerResponse response, byte[] content)
{
response.ContentLength64 = content.Length;
response.OutputStream.Write(content, 0, content.Length);
}
public static void SetResponseContent(HttpListenerResponse response, string text)
{
SetResponseContent(response, System.Text.Encoding.UTF8.GetBytes(text));
}
void SetResponseNotFound(HttpListenerResponse response)
{
response.StatusCode = (int)HttpStatusCode.NotFound;
SetResponseContent(response, "404 not found");
}
void GenerateResponse(HttpListenerContext context)
{
var request = context.Request;
HttpListenerResponse response = context.Response;
try
{
RouteTable m = null;
if (request.HttpMethod == "GET")
{
m = _get;
}
else if (request.HttpMethod == "PUT")
{
m = _put;
}
else if (request.HttpMethod == "DELETE")
{
m = _delete;
}
if (m == null)
{
SetResponseNotFound(response);
}
else
{
var f = m.Match(request);
if (f != null)
{
var r = f(request);
if (r is string)
{
SetResponseContent(response, (string)r);
}
else if (r is Action<HttpListenerResponse>)
{
var action = (Action<HttpListenerResponse>)r;
action(response);
}
else if (r is int || r is HttpStatusCode)
{
response.StatusCode = (int)r;
}
}
else
{
SetResponseNotFound(response);
}
}
}
finally
{
response.OutputStream.Close();
}
}
void HandleRequest()
{
const int ERROR_OPERATION_ABORTED = 995;
const int ERROR_INVALID_HANDLE = 6;
const int ERROR_INVALID_FUNCTION = 1;
while (true)
{
try
{
var context = _listener.GetContext();
GenerateResponse(context);
}
catch (HttpListenerException ex)
{
if (ex.ErrorCode == ERROR_OPERATION_ABORTED ||
ex.ErrorCode == ERROR_INVALID_HANDLE ||
ex.ErrorCode == ERROR_INVALID_FUNCTION)
{
return;
}
else
{
Console.WriteLine("Unexpected error code: {0}. Ex: {1}", ex.ErrorCode, ex);
throw;
}
}
}
}
/// <summary>
/// Creates OData feed from the list of packages.
/// </summary>
/// <param name="packages">The list of packages.</param>
/// <param name="title">The title of the feed.</param>
/// <returns>The string representation of the created OData feed.</returns>
public string ToODataFeed(IEnumerable<IPackage> packages, string title)
{
string nsAtom = "http://www.w3.org/2005/Atom";
var id = string.Format(CultureInfo.InvariantCulture, "{0}{1}", _endPoint, title);
XDocument doc = new XDocument(
new XElement(XName.Get("feed", nsAtom),
new XElement(XName.Get("id", nsAtom), id),
new XElement(XName.Get("title", nsAtom), title)));
foreach (var p in packages)
{
doc.Root.Add(ToODataEntryXElement(p));
}
return doc.ToString();
}
/// <summary>
/// Creates an OData entry XElement representation of the package.
/// </summary>
/// <param name="package">The package.</param>
/// <returns>The OData entry XElement.</returns>
private XElement ToODataEntryXElement(IPackage package)
{
string nsAtom = "http://www.w3.org/2005/Atom";
XNamespace nsDataService = "http://schemas.microsoft.com/ado/2007/08/dataservices";
string nsMetadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
string downloadUrl = string.Format(
CultureInfo.InvariantCulture,
"{0}package/{1}/{2}", _endPoint, package.Id, package.Version);
string entryId = string.Format(
CultureInfo.InvariantCulture,
"{0}Packages(Id='{1}',Version='{2}')",
_endPoint, package.Id, package.Version);
var entry = new XElement(XName.Get("entry", nsAtom),
new XAttribute(XNamespace.Xmlns + "d", nsDataService.ToString()),
new XAttribute(XNamespace.Xmlns + "m", nsMetadata.ToString()),
new XElement(XName.Get("id", nsAtom), entryId),
new XElement(XName.Get("title", nsAtom), package.Id),
new XElement(XName.Get("content", nsAtom),
new XAttribute("type", "application/zip"),
new XAttribute("src", downloadUrl)),
new XElement(XName.Get("properties", nsMetadata),
new XElement(nsDataService + "Version", package.Version),
new XElement(nsDataService + "PackageHash", package.GetHash("SHA512")),
new XElement(nsDataService + "PackageHashAlgorithm", "SHA512"),
new XElement(nsDataService + "Description", package.Description),
new XElement(nsDataService + "Listed", package.Listed)));
return entry;
}
public string ToOData(IPackage package)
{
XDocument doc = new XDocument(ToODataEntryXElement(package));
return doc.ToString();
}
}
/// <summary>
/// Represents the route table of the mock server.
/// </summary>
/// <remarks>
/// The return type of a request handler could be:
/// - string: the string will be sent back as the response content, and the response
/// status code is OK.
/// - HttpStatusCode: the value is returned as the response status code.
/// - Action&lt;HttpListenerResponse&gt;: The action will be called to construct the response.
/// </remarks>
class RouteTable
{
List<Tuple<string, Func<HttpListenerRequest, object>>> _mappings;
public RouteTable()
{
_mappings = new List<Tuple<string, Func<HttpListenerRequest, object>>>();
}
public void Add(string pattern, Func<HttpListenerRequest, object> f)
{
_mappings.Add(new Tuple<string, Func<HttpListenerRequest, object>>(pattern, f));
}
public Func<HttpListenerRequest, object> Match(HttpListenerRequest r)
{
foreach (var m in _mappings)
{
if (r.Url.AbsolutePath.StartsWith(m.Item1, StringComparison.Ordinal))
{
return m.Item2;
}
}
return null;
}
}
}

78
test/Test.Integration/MockServerResource.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,78 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NuGet.Test.Integration {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class MockServerResource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal MockServerResource() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NuGet.Test.Integration.MockServerResource", typeof(MockServerResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;edmx:Edmx Version=&quot;1.0&quot; xmlns:edmx=&quot;http://schemas.microsoft.com/ado/2007/06/edmx&quot;&gt;
/// &lt;edmx:DataServices m:DataServiceVersion=&quot;2.0&quot; m:MaxDataServiceVersion=&quot;2.0&quot; xmlns:m=&quot;http://schemas.microsoft.com/ado/2007/08/dataservices/metadata&quot;&gt;
/// &lt;Schema Namespace=&quot;NuGetGallery&quot; xmlns=&quot;http://schemas.microsoft.com/ado/2006/04/edm&quot;&gt;
/// &lt;EntityType Name=&quot;V2FeedPackage&quot; m:HasStream=&quot;true&quot;&gt;
/// &lt;Key&gt;
/// &lt;PropertyRef Name=&quot;Id&quot; /&gt;
/// [rest of string was truncated]&quot;;.
/// </summary>
internal static string NuGetV2APIMetadata {
get {
return ResourceManager.GetString("NuGetV2APIMetadata", resourceCulture);
}
}
}
}

Просмотреть файл

@ -0,0 +1,186 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="NuGetV2APIMetadata" xml:space="preserve">
<value>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"&gt;
&lt;edmx:DataServices m:DataServiceVersion="2.0" m:MaxDataServiceVersion="2.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"&gt;
&lt;Schema Namespace="NuGetGallery" xmlns="http://schemas.microsoft.com/ado/2006/04/edm"&gt;
&lt;EntityType Name="V2FeedPackage" m:HasStream="true"&gt;
&lt;Key&gt;
&lt;PropertyRef Name="Id" /&gt;
&lt;PropertyRef Name="Version" /&gt;
&lt;/Key&gt;
&lt;Property Name="Id" Type="Edm.String" Nullable="false" m:FC_TargetPath="SyndicationTitle" m:FC_ContentKind="text" m:FC_KeepInContent="false" /&gt;
&lt;Property Name="Version" Type="Edm.String" Nullable="false" /&gt;
&lt;Property Name="NormalizedVersion" Type="Edm.String" /&gt;
&lt;Property Name="Authors" Type="Edm.String" m:FC_TargetPath="SyndicationAuthorName" m:FC_ContentKind="text" m:FC_KeepInContent="false" /&gt;
&lt;Property Name="Copyright" Type="Edm.String" /&gt;
&lt;Property Name="Created" Type="Edm.DateTime" Nullable="false" /&gt;
&lt;Property Name="Dependencies" Type="Edm.String" /&gt;
&lt;Property Name="Description" Type="Edm.String" /&gt;
&lt;Property Name="DownloadCount" Type="Edm.Int32" Nullable="false" /&gt;
&lt;Property Name="GalleryDetailsUrl" Type="Edm.String" /&gt;
&lt;Property Name="IconUrl" Type="Edm.String" /&gt;
&lt;Property Name="IsLatestVersion" Type="Edm.Boolean" Nullable="false" /&gt;
&lt;Property Name="IsAbsoluteLatestVersion" Type="Edm.Boolean" Nullable="false" /&gt;
&lt;Property Name="IsPrerelease" Type="Edm.Boolean" Nullable="false" /&gt;
&lt;Property Name="Language" Type="Edm.String" /&gt;
&lt;Property Name="LastUpdated" Type="Edm.DateTime" Nullable="false" m:FC_TargetPath="SyndicationUpdated" m:FC_ContentKind="text" m:FC_KeepInContent="false" /&gt;
&lt;Property Name="Published" Type="Edm.DateTime" Nullable="false" /&gt;
&lt;Property Name="PackageHash" Type="Edm.String" /&gt;
&lt;Property Name="PackageHashAlgorithm" Type="Edm.String" /&gt;
&lt;Property Name="PackageSize" Type="Edm.Int64" Nullable="false" /&gt;
&lt;Property Name="ProjectUrl" Type="Edm.String" /&gt;
&lt;Property Name="ReportAbuseUrl" Type="Edm.String" /&gt;
&lt;Property Name="ReleaseNotes" Type="Edm.String" /&gt;
&lt;Property Name="RequireLicenseAcceptance" Type="Edm.Boolean" Nullable="false" /&gt;
&lt;Property Name="Summary" Type="Edm.String" m:FC_TargetPath="SyndicationSummary" m:FC_ContentKind="text" m:FC_KeepInContent="false" /&gt;
&lt;Property Name="Tags" Type="Edm.String" /&gt;
&lt;Property Name="Title" Type="Edm.String" /&gt;
&lt;Property Name="VersionDownloadCount" Type="Edm.Int32" Nullable="false" /&gt;
&lt;Property Name="MinClientVersion" Type="Edm.String" /&gt;
&lt;Property Name="LastEdited" Type="Edm.DateTime" /&gt;
&lt;Property Name="LicenseUrl" Type="Edm.String" /&gt;
&lt;Property Name="LicenseNames" Type="Edm.String" /&gt;
&lt;Property Name="LicenseReportUrl" Type="Edm.String" /&gt;
&lt;/EntityType&gt;
&lt;EntityContainer Name="V2FeedContext" m:IsDefaultEntityContainer="true"&gt;
&lt;EntitySet Name="Packages" EntityType="NuGetGallery.V2FeedPackage" /&gt;
&lt;FunctionImport Name="Search" ReturnType="Collection(NuGetGallery.V2FeedPackage)" EntitySet="Packages" m:HttpMethod="GET"&gt;
&lt;Parameter Name="searchTerm" Type="Edm.String" /&gt;
&lt;Parameter Name="targetFramework" Type="Edm.String" /&gt;
&lt;Parameter Name="includePrerelease" Type="Edm.Boolean" /&gt;
&lt;/FunctionImport&gt;
&lt;FunctionImport Name="FindPackagesById" ReturnType="Collection(NuGetGallery.V2FeedPackage)" EntitySet="Packages" m:HttpMethod="GET"&gt;
&lt;Parameter Name="id" Type="Edm.String" /&gt;
&lt;/FunctionImport&gt;
&lt;FunctionImport Name="GetUpdates" ReturnType="Collection(NuGetGallery.V2FeedPackage)" EntitySet="Packages" m:HttpMethod="GET"&gt;
&lt;Parameter Name="packageIds" Type="Edm.String" /&gt;
&lt;Parameter Name="versions" Type="Edm.String" /&gt;
&lt;Parameter Name="includePrerelease" Type="Edm.Boolean" /&gt;
&lt;Parameter Name="includeAllVersions" Type="Edm.Boolean" /&gt;
&lt;Parameter Name="targetFrameworks" Type="Edm.String" /&gt;
&lt;Parameter Name="versionConstraints" Type="Edm.String" /&gt;
&lt;/FunctionImport&gt;
&lt;/EntityContainer&gt;
&lt;/Schema&gt;
&lt;/edmx:DataServices&gt;
&lt;/edmx:Edmx&gt;</value>
</data>
</root>

Просмотреть файл

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Xunit;
using Xunit.Extensions;
@ -71,5 +72,34 @@ namespace NuGet.Test.Integration.NuGetCommandLine
Util.DeleteDirectory(source);
}
}
[Fact]
public void DeleteCommand_DeleteFromHttpSource()
{
var tempPath = Path.GetTempPath();
var mockServerEndPoint = "http://localhost:1234/";
// Arrange
var server = new MockServer(mockServerEndPoint);
server.Start();
bool deleteRequestIsCalled = false;
server.Delete.Add("/nuget/testPackage1/1.1", request =>
{
deleteRequestIsCalled = true;
return HttpStatusCode.OK;
});
// Act
string[] args = new string[] {
"delete", "testPackage1", "1.1.0",
"-Source", mockServerEndPoint + "nuget", "-NonInteractive" };
int r = Program.Main(args);
server.Stop();
// Assert
Assert.Equal(0, r);
Assert.True(deleteRequestIsCalled);
}
}
}

Просмотреть файл

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Xunit;
using Xunit.Extensions;
@ -382,5 +384,472 @@ namespace NuGet.Test.Integration.NuGetCommandLine
Util.DeleteDirectory(workingPath);
}
}
// Tests that when no version is specified, nuget will query the server to get
// the latest version number first.
[Fact]
public void InstallCommand_GetLastestReleaseVersion()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
var server = new MockServer(mockServerEndPoint);
string findPackagesByIdRequest = string.Empty;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/FindPackagesById()", r =>
new Action<HttpListenerResponse>(response =>
{
findPackagesByIdRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var p1 = server.ToOData(package);
MockServer.SetResponseContent(response, p1);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
// Tests that when no version is specified, and -Prerelease is specified,
// nuget will query the server to get the latest prerelease version number first.
[Fact]
public void InstallCommand_GetLastestPrereleaseVersion()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
var server = new MockServer(mockServerEndPoint);
string findPackagesByIdRequest = string.Empty;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/FindPackagesById()", r =>
new Action<HttpListenerResponse>(response =>
{
findPackagesByIdRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var p1 = server.ToOData(package);
MockServer.SetResponseContent(response, p1);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Prerelease -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.Contains("$filter=IsAbsoluteLatestVersion", findPackagesByIdRequest);
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
// Tests that when -Version is specified, nuget will use request
// Packages(Id='id',Version='version') to get the specified version
[Fact]
public void InstallCommand_WithVersionSpecified()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
var server = new MockServer(mockServerEndPoint);
bool getPackageByVersionIsCalled = false;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
getPackageByVersionIsCalled = true;
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var p1 = server.ToOData(package);
MockServer.SetResponseContent(response, p1);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Version 1.1.0 -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.True(getPackageByVersionIsCalled);
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
// Tests that when -Version is specified, if the specified version cannot be found,
// nuget will retry with new version numbers by appending 0's to the specified version.
[Fact]
public void InstallCommand_WillTryNewVersionsByAppendingZeros()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(workingDirectory);
// deleting testPackage1 from machine cache
var packages = MachineCache.Default.FindPackagesById("testPackage1");
foreach (var p in packages)
{
MachineCache.Default.RemovePackage(p);
}
var server = new MockServer(mockServerEndPoint);
List<string> requests = new List<string>();
server.Get.Add("/nuget/Packages", r =>
{
requests.Add(r.Url.ToString());
return HttpStatusCode.NotFound;
});
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Version 1.1 -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(1, r1.Item1);
Assert.Equal(3, requests.Count);
Assert.True(requests[0].EndsWith("Packages(Id='testPackage1',Version='1.1')"));
Assert.True(requests[1].EndsWith("Packages(Id='testPackage1',Version='1.1.0')"));
Assert.True(requests[2].EndsWith("Packages(Id='testPackage1',Version='1.1.0.0')"));
}
finally
{
// Cleanup
Util.DeleteDirectory(workingDirectory);
}
}
// Tests that nuget will NOT download package from http source if the package on the server
// has the same hash value as the cached version.
[Fact]
public void InstallCommand_WillUseCachedFile()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
// add the package to machine cache
MachineCache.Default.AddPackage(package);
var server = new MockServer(mockServerEndPoint);
string findPackagesByIdRequest = string.Empty;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/FindPackagesById()", r =>
new Action<HttpListenerResponse>(response =>
{
findPackagesByIdRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var p1 = server.ToOData(package);
MockServer.SetResponseContent(response, p1);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);
// verifies that package is NOT downloaded from server since nuget uses
// the file in machine cache.
Assert.False(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
// Tests that nuget will download package from http source if the package on the server
// has a different hash value from the cached version.
[Fact]
public void InstallCommand_DownloadPackageWhenHashChanges()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
// add the package to machine cache
MachineCache.Default.AddPackage(package);
// create a new package. Now this package has different hash value from the package in
// the machine cache.
packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
package = new ZipPackage(packageFileName);
var server = new MockServer(mockServerEndPoint);
string findPackagesByIdRequest = string.Empty;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/FindPackagesById()", r =>
new Action<HttpListenerResponse>(response =>
{
findPackagesByIdRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var p1 = server.ToOData(package);
MockServer.SetResponseContent(response, p1);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);
// verifies that package is downloaded from server since the cached version has
// a different hash from the package on the server.
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
}
}

Просмотреть файл

@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Xunit;
using Xunit.Extensions;
@ -61,7 +63,7 @@ namespace NuGet.Test.Integration.NuGetCommandLine
Assert.Equal(4, lines.Length);
Assert.Equal("testPackage1", lines[0]);
Assert.Equal(" 1.1.0", lines[1]);
Assert.Equal(" Test desc", lines[2]);
Assert.Equal(" desc of testPackage1 1.1.0", lines[2]);
Assert.Equal(" License url: http://kaka", lines[3]);
}
@ -107,5 +109,390 @@ namespace NuGet.Test.Integration.NuGetCommandLine
var output = Encoding.Default.GetString(memoryStream.ToArray());
Assert.Equal("testPackage1 1.1.0\r\ntestPackage2 2.0.0\r\n", output);
}
// Tests list command, with no other switches
[Fact]
public void ListCommand_Simple()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that only package id & version is displayed
var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
"testPackage2 2.1" + Environment.NewLine;
Assert.Equal(expectedOutput, r1.Item2);
Assert.Contains("$filter=IsLatestVersion", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=false", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that list command only show listed packages
[Fact]
public void ListCommand_OnlyShowListed()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
package1.Listed = false;
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that only testPackage2 is listed since the package testPackage1
// is not listed.
var expectedOutput = "testPackage2 2.1" + Environment.NewLine;
Assert.Equal(expectedOutput, r1.Item2);
Assert.Contains("$filter=IsLatestVersion", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=false", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that list command displays detailed package info when -Verbosity is detailed.
[Fact]
public void ListCommand_VerboseOutput()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -Verbosity detailed -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that the output is detailed
Assert.Contains(package1.Description, r1.Item2);
Assert.Contains(package2.Description, r1.Item2);
Assert.Contains("$filter=IsLatestVersion", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=false", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that when -AllVersions is specified, list command sends request
// without $filter
[Fact]
public void ListCommand_AllVersions()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -AllVersions -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that the output is detailed
var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
"testPackage2 2.1" + Environment.NewLine;
Assert.Equal(expectedOutput, r1.Item2);
Assert.DoesNotContain("$filter", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=false", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Test case when switch -Prerelease is specified
[Fact]
public void ListCommand_Prerelease()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -Prerelease -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that the output is detailed
var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
"testPackage2 2.1" + Environment.NewLine;
Assert.Equal(expectedOutput, r1.Item2);
Assert.Contains("$filter=IsAbsoluteLatestVersion", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=true", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Test case when both switches -Prerelease and -AllVersions are specified
[Fact]
public void ListCommand_AllVersionsPrerelease()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
var package1 = new ZipPackage(packageFileName1);
var package2 = new ZipPackage(packageFileName2);
var server = new MockServer(mockServerEndPoint);
string searchRequest = string.Empty;
server.Get.Add("/nuget/$metadata", r =>
MockServerResource.NuGetV2APIMetadata);
server.Get.Add("/nuget/Search()", r =>
new Action<HttpListenerResponse>(response =>
{
searchRequest = r.Url.ToString();
response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
string feed = server.ToODataFeed(new[] { package1, package2 }, "Search");
MockServer.SetResponseContent(response, feed);
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "list test -AllVersions -Prerelease -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
tempPath,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
// verify that the output is detailed
var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
"testPackage2 2.1" + Environment.NewLine;
Assert.Equal(expectedOutput, r1.Item2);
Assert.DoesNotContain("$filter", searchRequest);
Assert.Contains("searchTerm='test", searchRequest);
Assert.Contains("includePrerelease=true", searchRequest);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
}
}

Просмотреть файл

@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Xunit;
using Xunit.Extensions;
namespace NuGet.Test.Integration.NuGetCommandLine
{
@ -116,5 +115,271 @@ namespace NuGet.Test.Integration.NuGetCommandLine
Util.DeleteDirectory(source);
}
}
// Tests pushing to an http source
[Fact]
public void PushCommand_PushToServer()
{
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
Console.SetOut(writer);
string outputFileName = Path.Combine(packageDirectory, "t1.nupkg");
var server = new MockServer(mockServerEndPoint);
server.Get.Add("/push", r => "OK");
server.Put.Add("/push", r =>
{
byte[] buffer = MockServer.GetPushedPackage(r);
using (var of = new FileStream(outputFileName, FileMode.Create))
{
of.Write(buffer, 0, buffer.Length);
}
return HttpStatusCode.Created;
});
server.Start();
// Act
string[] args = new string[] { "push", packageFileName, "-Source", mockServerEndPoint + "push" };
int ret = Program.Main(args);
writer.Close();
server.Stop();
// Assert
Assert.Equal(0, ret);
var output = Encoding.Default.GetString(memoryStream.ToArray());
Assert.Contains("Your package was pushed.", output);
AssertFileEqual(packageFileName, outputFileName);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that push command can follow redirection correctly.
[Fact]
public void PushCommand_PushToServerFollowRedirection()
{
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
Console.SetOut(writer);
string outputFileName = Path.Combine(packageDirectory, "t1.nupkg");
var server = new MockServer(mockServerEndPoint);
server.Get.Add("/redirect", r => "OK");
server.Put.Add("/redirect", r =>
new Action<HttpListenerResponse>(
res =>
{
res.Redirect(mockServerEndPoint + "nuget");
}));
server.Put.Add("/nuget", r =>
{
byte[] buffer = MockServer.GetPushedPackage(r);
using (var of = new FileStream(outputFileName, FileMode.Create))
{
of.Write(buffer, 0, buffer.Length);
}
return HttpStatusCode.Created;
});
server.Start();
// Act
string[] args = new string[] { "push", packageFileName, "-Source", mockServerEndPoint + "redirect" };
int ret = Program.Main(args);
writer.Close();
server.Stop();
// Assert
var output = Encoding.Default.GetString(memoryStream.ToArray());
Assert.Equal(0, ret);
Assert.Contains("Your package was pushed.", output);
AssertFileEqual(packageFileName, outputFileName);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that push command will terminate even when there is an infinite
// redirection loop.
[Fact]
public void PushCommand_PushToServerWithInfiniteRedirectionLoop()
{
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
Console.SetOut(writer);
Console.SetError(writer);
var server = new MockServer(mockServerEndPoint);
server.Get.Add("/redirect", r => "OK");
server.Put.Add("/redirect", r =>
new Action<HttpListenerResponse>(
res =>
{
res.Redirect(mockServerEndPoint + "redirect");
}));
server.Start();
// Act
string[] args = new string[] { "push", packageFileName, "-Source", mockServerEndPoint + "redirect" };
int ret = Program.Main(args);
writer.Close();
server.Stop();
// Assert
var output = Encoding.Default.GetString(memoryStream.ToArray());
Assert.NotEqual(0, ret);
Assert.Contains("Too many automatic redirections were attempted.", output);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Tests that push command generates error when it detects invalid redirection location.
[Fact]
public void PushCommand_PushToServerWithInvalidRedirectionLocation()
{
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
Console.SetOut(writer);
Console.SetError(writer);
var server = new MockServer(mockServerEndPoint);
server.Get.Add("/redirect", r => "OK");
server.Put.Add("/redirect", r => HttpStatusCode.Redirect);
server.Start();
// Act
string[] args = new string[] { "push", packageFileName, "-Source", mockServerEndPoint + "redirect" };
int ret = Program.Main(args);
writer.Close();
server.Stop();
// Assert
var output = Encoding.Default.GetString(memoryStream.ToArray());
Assert.NotEqual(0, ret);
Assert.Contains("The remote server returned an error: (302)", output);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Regression test for the bug that "nuget.exe push" will retry forever instead of asking for
// user's password when NuGet.Server uses Windows Authentication.
[Fact]
public void PushCommand_PushToServerWontRetryForever()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
Console.SetOut(writer);
string outputFileName = Path.Combine(packageDirectory, "t1.nupkg");
var server = new MockServer(mockServerEndPoint);
server.Get.Add("/push", r => "OK");
server.Put.Add("/push", r => new Action<HttpListenerResponse>(
response =>
{
response.AddHeader("WWW-Authenticate", "NTLM");
response.StatusCode = (int)HttpStatusCode.Unauthorized;
}));
server.Start();
// Act
var args = "push " + packageFileName +
" -Source " + mockServerEndPoint + "push -NonInteractive";
var r1 = CommandRunner.Run(
nugetexe,
packageDirectory,
args,
waitForExit: true,
timeOutInMilliseconds: 10000);
server.Stop();
// Assert
Assert.NotEqual(0, r1.Item1);
Assert.Contains("Please provide credentials for:", r1.Item2);
Assert.Contains("UserName:", r1.Item2);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
}
}
// Asserts that the contents of two files are equal.
void AssertFileEqual(string fileName1, string fileName2)
{
byte[] content1, content2;
using (var r1 = new FileStream(fileName1, FileMode.Open))
{
content1 = r1.ReadAllBytes();
}
using (var r1 = new FileStream(fileName2, FileMode.Open))
{
content2 = r1.ReadAllBytes();
}
Assert.Equal(content1, content2);
}
}
}

Просмотреть файл

@ -4,6 +4,7 @@ using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
@ -902,5 +903,84 @@ EndProject");
Util.DeleteDirectory(workingPath);
}
}
// Tests restore from an http source.
[Fact]
public void RestoreCommand_FromHttpSource()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
Util.CreateFile(
workingDirectory,
"packages.config",
@"
<packages>
<package id=""testPackage1"" version=""1.1.0"" />
</packages>");
var server = new MockServer(mockServerEndPoint);
bool getPackageByVersionIsCalled = false;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
getPackageByVersionIsCalled = true;
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var odata = server.ToOData(package);
MockServer.SetResponseContent(response, odata);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "restore packages.config -PackagesDirectory . -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.True(getPackageByVersionIsCalled);
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
}
}

Просмотреть файл

@ -2,6 +2,7 @@
using System.IO;
using Moq;
using Xunit;
using System.Globalization;
namespace NuGet.Test.Integration.NuGetCommandLine
{
@ -19,9 +20,12 @@ namespace NuGet.Test.Integration.NuGetCommandLine
var packageBuilder = new PackageBuilder
{
Id = packageId,
Version = new SemanticVersion(version),
Description = "Test desc"
Version = new SemanticVersion(version)
};
packageBuilder.Description = string.Format(
CultureInfo.InvariantCulture,
"desc of {0} {1}",
packageId, version);
if (licenseUrl != null)
{

Просмотреть файл

@ -27,6 +27,7 @@
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq" />
<Reference Include="xunit, Version=1.9.2.1705, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\packages\xunit.1.9.2\lib\net20\xunit.dll</HintPath>
@ -47,6 +48,12 @@
</Compile>
<Compile Include="CommandRunner.cs" />
<Compile Include="Core\LocalPackageRepositoryTest.cs" />
<Compile Include="MockServer.cs" />
<Compile Include="MockServerResource.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>MockServerResource.resx</DependentUpon>
</Compile>
<Compile Include="NuGetCommandLine\DefaultConfigurationFilePreserver.cs" />
<Compile Include="NuGetCommandLine\NuGetConfigCommandTest.cs" />
<Compile Include="NuGetCommandLine\NuGetDeleteCommandTest.cs" />
@ -83,6 +90,12 @@
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="MockServerResource.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>MockServerResource.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\Build\NuGet.Test.targets" />
</Project>

Просмотреть файл

@ -23,21 +23,32 @@ namespace NuGet.VisualStudio.Test
}
[Theory]
[InlineData("", "Windows, Version=0.0")]
[InlineData(null, "Windows, Version=0.0")]
[InlineData("8.0", "Windows, Version=8.0")]
[InlineData("8.1", "Windows, Version=8.1")]
public void GetTargetFrameworkForJSProjectReturnsCorrectPlatformVersion(string platformVersion, string exptectedTargetFramework)
[InlineData("", "", "Windows, Version=0.0")]
[InlineData(null, null, "Windows, Version=0.0")]
[InlineData("", "Windows", "Windows, Version=0.0")]
[InlineData(null, "Windows", "Windows, Version=0.0")]
[InlineData("8.0", "Windows", "Windows, Version=8.0")]
[InlineData("8.1", "Windows", "Windows, Version=8.1")]
[InlineData("", "WindowsPhoneApp", "WindowsPhoneApp, Version=0.0")]
[InlineData("8.1", "WindowsPhoneApp", "WindowsPhoneApp, Version=8.1")]
[InlineData("10", "vNextJSApp", "vNextJSApp, Version=10")]
public void GetTargetFrameworkForJSProjectReturnsCorrectPlatformVersion(string platformVersion, string platformIdentifier, string exptectedTargetFramework)
{
// Arrange
var project = new Mock<Project>();
project.Setup(p => p.Kind).Returns(VsConstants.JsProjectTypeGuid);
var fxProperty = new Mock<Property>();
fxProperty.Setup(x => x.Value).Returns(platformVersion);
var verProp = new Mock<Property>();
verProp.Setup(x => x.Value).Returns(platformVersion);
var idProp = new Mock<Property>();
idProp.Setup(x => x.Value).Returns(platformIdentifier);
project.Setup(p => p.Properties.Item(It.Is<object>(v => "TargetPlatformVersion".Equals(v))))
.Returns(fxProperty.Object);
.Returns(verProp.Object);
project.Setup(p => p.Properties.Item(It.Is<object>(v => "TargetPlatformIdentifier".Equals(v))))
.Returns(idProp.Object);
// Act
string targetFramework = ProjectExtensions.GetTargetFramework(project.Object);

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше