Azure devops Cant connect Nuget Restore и VSBuild для пакетов Nuget - PullRequest
1 голос
/ 10 января 2020

Пока у меня очень простой c конвейер сборки

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- testing-build-yml-1

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'
    # packagesDirectory: '..\packages'
    restoreDirectory: '..\new_packages'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    #msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)" /p:ReferencePath="d:\a\1\new_packages"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

Я пытаюсь выполнить задачу Nuget Restore, чтобы восстановить пакеты в каталог ..\new_packages, а затем надеюсь, что задача VSBuild получит оттуда и построим решение.

Восстановление Nuget выполняет следующую команду (все в одной строке)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\bin\msbuild.exe 
  "C:\Users\VssAdministrator\AppData\Local\Temp\NuGetScratch\jgtjjpe0.nac.nugetinputs.targets" 
  /t:GenerateRestoreGraphFile 
   /nologo 
   /nr:false 
   /v:q 
  /p:NuGetRestoreTargets="C:\Users\VssAdministrator\AppData\Local\Temp\NuGetScratch\whba0xm4.c0f.nugetrestore.targets" 
  /p:RestoreUseCustomAfterTargets="True" /p:RestoreTaskAssemblyFile="C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe" 
  /p:RestoreSolutionDirectory="D:\a\1\s\\" 
  /p:RestoreConfigFile="D:\a\1\Nuget\tempNuGet_105.config" 
  /p:RestorePackagesPath="..\new_packages" 
  /p:SolutionDir="D:\a\1\s\\" 
  /p:SolutionName="XYZ"

Затем VSBuild Task запускает msbuild (все в одной строке)

##[command]"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\msbuild.exe" 
 "D:\a\1\s\XYZ.sln" 
   /nologo 
   /nr:false 
   /dl:CentralLogger,
 "D:\a\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.161.2\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";
 "RootDetailId=e5869970-8e7b-4a06-a8fd-f0662f639a6d|SolutionDir=D:\a\1\s"*ForwardingLogger,"D:\a\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.161.2\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"
 /p:DeployOnBuild=true 
 /p:WebPublishMethod=Package 
 /p:PackageAsSingleFile=true 
 /p:SkipInvalidConfigurations=true 
 /p:PackageLocation="D:\a\1\a" 
 /p:ReferencePath="d:\a\1\new_packages" 
 /p:platform="Any CPU" 
 /p:configuration="Release" 
 /p:VisualStudioVersion="16.0" 
 /p:_MSDeployUserAgent="VSTS_607486bc-2d64-463d-9a7f-0cf06fe82263_build_16_0"

Решение ищет соответствующий каталог, указанный в /p:ReferencePath="d:\a\1\new_packages.

Но он по-прежнему не может найти dll для пакетов Nuget, и в конечном итоге сборка завершается неудачей.

    Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
Build started 1/9/2020 10:11:18 PM.
Project "D:\a\1\s\XYZ.sln" on node 1 (default targets).
ValidateSolutionConfiguration:
  Building solution configuration "Release|Any CPU".
Project "D:\a\1\s\XYZ.sln" (1) is building "D:\a\1\s\ServiceLayer\InputOutputServiceLayer.csproj" (2) on node 1 (default targets).
PrepareForBuild:
  Creating directory "bin\Release\".
  Creating directory "obj\Release\".
ResolveAssemblyReferences:
  Primary reference "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\1\s\ServiceLayer\InputOutputServiceLayer.csproj]
          For SearchPath "d:\a\1\new_packages".
          Considered "d:\a\1\new_packages\EPPlus.winmd", but it didn't exist.
          Considered "d:\a\1\new_packages\EPPlus.dll", but it didn't exist.
          Considered "d:\a\1\new_packages\EPPlus.exe", but it didn't exist.
          For SearchPath "{HintPathFromItem}".
          Considered "D:\a\1\s\packages\EPPlus.4.5.3.2\lib\net40\EPPlus.dll", but it didn't exist.

Технически я знаю, что мы не должны жестко кодировать /p:ReferencePath=.. do это, но я просто пытаюсь заставить его работать.

Без этого VSBuild Task, похоже, не знает, где вообще искать.

Это выглядит как

 ResolveAssemblyReferences:
  Primary reference "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "EPPlus, Version=4.5.3.2, Culture=neutral, PublicKeyToken=ea159fdaa78159a1, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [d:\a\1\s\ServiceLayer\InputOutputServiceLayer.csproj]
          For SearchPath "..\d:\a\1\a".
          Considered "..\d:\a\1\a\EPPlus.winmd", but it didn't exist.
          Considered "..\d:\a\1\a\EPPlus.dll", but it didn't exist.
          Considered "..\d:\a\1\a\EPPlus.exe", but it didn't exist.
          For SearchPath "{HintPathFromItem}".
          Considered "d:\a\1\s\packages\EPPlus.4.5.3.2\lib\net40\EPPlus.dll", but it didn't exist.
          For SearchPath "{TargetFrameworkDirectory}".
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\EPPlus.winmd", but it didn't exist.

Есть похожий вопрос, использующий старый способ использования конвейера

MsBuild не находит восстановленные пакеты NuGet на Visual Studio Online

Их решение (хотя и хакерское) у меня тоже не работает.

Если я удалю пакет EPPlus, следующий пакет Entity Framework выдаст те же ошибки.
Если я удалю Entity Framework, следующий пакет выдаст те же ошибки.

Я просто пытаюсь найти реальное решение для этого, которое не включает в себя эти хакерские программы (..и работает, очевидно)

РЕДАКТИРОВАТЬ:

Работает, со странностями благодаря Leo Liu-MSFT.
Мой ответ ниже этого.

Ответы [ 2 ]

2 голосов
/ 10 января 2020

Azure devops Не могу подключиться Nuget Restore и VSBuild для пакетов Nuget

Боюсь, вы не сможете заставить его работать, если вы не измените HintPath в файле проекта.

При изменении пакетов nuget, восстановленных в каталог ..\new_packages, после восстановления пакет в новом каталоге должен иметь следующие структурные уровни:

d:\a\1\new_packages\EPPlus.4.5.3.2\lib\net40\EPPlus.dll

Файл dll сохраняется в вашем новом каталоге в форме пакета nuget, а не непосредственно в новом каталоге.

Итак, когда вы указываете /p:ReferencePath="d:\a\1\new_packages" во время сборки проекта, VS найдет dll файл прямо из ReferencePath. Вот причина, по которой вы получаете сообщение об ошибке:

Считается "d: \ a \ 1 \ new_packages \ EPPlus.dll"

На самом деле, dll путь должен быть d:\a\1\new_packages\EPPlus.4.5.3.2\lib\net40. Поскольку этот путь связан как с именем, так и с версией пакета, мы не можем использовать один параметр для указания пути для нескольких dlls.

В этом случае мы должны изменить HintPath в файле проекта.

Правильный процесс состоит в том, что измените repositoryPath в файле nuget.config, чтобы изменить каталог пакетов nuget на локальный:

Можно ли изменить расположение пакетов для NuGet ?

затем используйте командную строку Update-Package -reinstall в консоли диспетчера пакетов, чтобы принудительно переустановить ссылки на пакеты в проект в локальном , он обновит HintPath для всех пакетов , затем отправьте изменения в систему контроля версий. Тогда мы могли бы использовать задачу восстановления Nuget для восстановления пакетов в ..\new_packages каталоге

Надеюсь, это поможет.

0 голосов
/ 13 января 2020

Я получил его на работу, но с несколькими причудами (и особенностями?) И несколькими нерешенными вопросами.

Пожалуйста, см. /users/7460777/leo-liu-msft выше, чтобы получить некоторый контекст относительно того, почему некоторые из этих шагов предпринимаются.

Как упоминал Лео, это связано с тем, что HintPath не обновляется должным образом в проектах, использующих packages.config

. Чтобы вообще избежать этой проблемы,
переносит столько проектов, сколько возможно на <PackageReference /> вместо использования packages.config. Чтобы сделать это, щелкните правой кнопкой мыши на References внутри каждого проекта, должна быть возможность сделать это.
Некоторые проекты (например, -> в моем случае, мой asp. net (. net). Framework) MVC веб-клиент) не может быть перенесен.
(..Я добавлю подробности, которые я нашел по этому вопросу позже)
ОБНОВЛЕНИЕ:
( https://devblogs.microsoft.com/nuget/migrate-packages-config-to-package-reference/)
(https://github.com/NuGet/Home/issues/5877)


Следующие шаги: -

1) В папке верхнего уровня, где я у меня есть файл .sln, я создал следующий файл nuget.config.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <add key="repositoryPath" value=".\packages" />
  </config>
</configuration>

Так как мой каталог packages находится здесь.

2) Ниже обновлен build.yml.

# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

trigger:
- testing-build-yml

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'
    packagesdirectory: '.\packages'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

3) Следующий шаг заставил все работать, но я все еще не уверен, почему именно.
Я удалил все в папке packages и в основном просто нажал эти удаления вверх по течению. Задача восстановления Nuget выполнила восстановление, и задача VSBuild была успешно выполнена.


Вещи, в которых я до сих пор не уверен -

1) Почему временный файл Nuget.config создан, хотя я Четко сказано, где он существует?

Saving NuGet.config to a temporary config file.
[command]C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe sources Add -NonInteractive -Name NuGetOrg -Source https://api.nuget.org/v3/index.json -ConfigFile d:\a\1\Nuget\tempNuGet_140.config
Package source with Name: NuGetOrg added successfully.
[command]C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe restore d:\a\1\s\XYZ.sln -PackagesDirectory .\packages -Verbosity Detailed -NonInteractive -ConfigFile d:\a\1\Nuget\tempNuGet_140.config
NuGet Version: 5.4.0.6315
MSBuild auto-detection: using msbuild version '16.4.0.56107' from 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\bin'. Use option -MSBuildVersion to force nuget to use a specific version of MSBuild.
MSBuild P2P timeout [ms]: 120000
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\bin\msbuild.exe 
"C:\Users\VssAdministrator\AppData\Local\Temp\NuGetScratch\0eie04ka.4ch.nugetinputs.targets" /t:GenerateRestoreGraphFile /nologo /nr:false /v:q /p:NuGetRestoreTargets="C:\Users\VssAdministrator\AppData\Local\Temp\NuGetScratch\y3ui4hhz.gfr.nugetrestore.targets" /p:RestoreUseCustomAfterTargets="True" /p:RestoreTaskAssemblyFile="C:\hostedtoolcache\windows\NuGet\5.4.0\x64\nuget.exe" /p:RestoreSolutionDirectory="d:\a\1\s\\" /p:RestoreConfigFile="d:\a\1\Nuget\tempNuGet_140.config" /p:RestorePackagesPath=".\packages" /p:SolutionDir="d:\a\1\s\\" /p:SolutionName="XYZ"

2) Почему удаление пакетов заставляет его работать, а фиксация пакетов делает невозможным поиск файлов DLL, даже если он смотрит в правильные места?

Primary reference "NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL".
##[warning]C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): Warning MSB3245: Could not resolve this reference. Could not locate the assembly "NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. [D:\a\1\s\XYZ_WebClient\XYZ_WebClient.csproj]
          For SearchPath "{HintPathFromItem}".
          Considered "D:\a\1\s\packages\NLog.4.6.7\lib\net45\NLog.dll", but it didn't exist.
          For SearchPath "{TargetFrameworkDirectory}".
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\NLog.winmd", but it didn't exist.
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\NLog.dll", but it didn't exist.
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\NLog.exe", but it didn't exist.
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\Facades\NLog.winmd", but it didn't exist.
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\Facades\NLog.dll", but it didn't exist.
          Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\Facades\NLog.exe", but it didn't exist.
...