Cannot copy folder with nuget package in .net core - visual-studio

I Create a NuGet package and install into another project. but don't copy a file into the location project. only my file reference to NuGet package and I change the code, The package also changes! I want to copy the package to the target project.
<?xml version="1.0"?>
<package>
<metadata minClientVersion="3.3.0">
<id>MyPackage</id>
<version>1.0.0</version>
<authors>Meysam</authors>
<owners>Meysam</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Package description</description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2018</copyright>
<tags>Tag1 Tag2</tags>
<contentFiles>
<files include="cs/*.*/**" buildAction="Compile" />
</contentFiles>
</metadata>
<files>
<file src="ConsoleApp1\CustomClass\CustomClass.cs" target="contentFiles\cs\any\CustomClass" />
</files>
</package>

Copying files into the project that uses a nuget package is only supported when using packages.config, which isn't supported by SDK-style projects, which are required for .NET Core projects. As your screenshots show, contentFiles in PackageReferences projects are included at build time. The little arrow icon in the bottom right corner of the C# and folder icons you pointed to in your screenshot are visual indicators that the file and folder are different to the other files and folders in your project. In fact, that little icon overlay is similar to what Windows adds for shortcuts, so if you understand a shortcut is a file that "points to" another file, it should make sense that these are shortcuts to files outside your project, but are included as part of your project.
Anyway, it's working as designed.
You'll need to find another way to do whatever you want, but you didn't describe why you're trying to include a file in the project that references your package, so I can't give direct advice. My best advice, if you are experienced with ASP.NET and ASP.NET Core is think about how ASP.NET used to read a lot of settings directly from web.config, but ASP.NET Core instead uses a builder pattern, so that users are not forced to store settings in web.config and can store settings anywhere they want. If what you're doing is similar, your package users will have a better experience if you provide them with a configuration builder that they can override, rather than having a file in their project that they must edit and gets overwritten every time they upgrade to a new version of your package.

Cannot copy folder with nuget package in .net core
Yes, just like zivkan said:
Copying files into the project that uses a nuget package is only
supported when using packages.config
But, we could use a workaround to resolve this issue. We could add a copy task in the xx.targets file, and set this file in the \build folder in the .nuspec file.
The content of mypackage.targets file:
<Target Name="CopyFile" AfterTargets="AfterBuild">
<ItemGroup>
<CopyFiles Include="$(NuGetPackageRoot)\mypackage\4.0.0\cs\*.*\**" />
</ItemGroup>
<Copy
SourceFiles="#(CopyFiles)"
DestinationFolder="$(ProjectDir)"
/>
</Target>
And the .nuspec file:
<file src="xxx\xxx\mypackage.targets" target="build" />
Hope this helps.

Related

NuGet to copy files into the project directory

I've created a .nuspec file which packages a bunch of .proto files for sharing between projects. This is great. Unfortunately, for the .proto files to be built, they need to be actually copied over to the project directory, not just referenced. Note that this is a .NET Core project.
Right now my definition creates a package that, when used, references the files in the project, but these files still reside in the original .Nuget folder, and that's not really what I need.
Here's the .nuspec definition that I've got right now:
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>GRPCProtoFiles</id>
<version>1.0.0</version>
<authors>Author</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>.proto files NuGet package.</description>
<dependencies>
<dependency id="Google.Protobuf" version="3.14.0"/>
<dependency id="Grpc" version="2.35.0"/>
</dependencies>
<contentFiles>
<files include="any/any/Protos/**/*.proto" buildAction="None" copyToOutput="false" />
</contentFiles>
</metadata>
<files>
<file src="**\*.proto" target="contentFiles\any\any\Protos" exclude="google\**" />
</files>
</package>
I know that "build action" is currently set to "none", but I can get that fixed once the files land in the correct folder upon package installation. As is, if I try to set the build action for the proto files to the correct one (which is Protobuf Compiler) then I get an error, because the files aren't where they're supposed to be.
What am I doing wrong?
EDIT:
OK, I've read up a bit on what might be happening and why. Specifically this answer gave me a lot of insight. However I'm left wondering how I can actually do what I need to do. Right now it seems that what I want to do is impossible with NuGet and I'm using the wrong tool for the job. But besides this one limitation NuGet seems ideal - it's able to pick just the .proto files from the source project and just publish that rather then pre-built libraries for various target systems.
I could, possibly, add a pre-build action to copy the files to the project dir, but I've no idea how to reference the source NuGet package folder (especially if the version changes). Any idea if this problem even has a solution?
I really know your ideas. First, make these proto files be packed into nupkg with Build Action None. And then use pre-build event under the main project to handle the files from the nupkg. The question is that how to use msbuild property to get files from nupkg since Net Core projects use Link properties to references the files under the main project rather than copy the real nuget files into the main project folder.
And under the Link properties, you could not change the Build Action of that file because it actually does not exist under the main project folder and the main project has no duty to handle the file.
There are two functions to solve it:
=============================================
Function one
You could did this directly under nupkg itself and after that, the proto files will be copied automatically during build process with the nuget package. Try the following steps and you should not add any copy task from another main project which install the nuget package.
You have to use <packages_id>.props/targets file into nupkg to get what you want. Refer to this official document.
1) create a file called <packages_id>.props file. In your side, it should be named as GRPCProtoFiles.props so that it will work.
2) add these on the GRPCProtoFiles.props file:
<Project>
<Target Name="CopyFiles" BeforeTargets="Build">
<ItemGroup>
<File Include="$(MSBuildThisFileDirectory)..\contentFiles\**\*.*"></File>
</ItemGroup>
<Copy SourceFiles="#(File)" DestinationFolder="$(ProjectDir)\Protos"></Copy>
</Target>
</Project>
3) add these on the GRPCProtoFiles.nuspec file to include the props file into nupkg:
<file src="build\*.props" target="build" />
The whole GRPCProtoFiles.nuspec file should be like this:
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>GRPCProtoFiles</id>
<version>1.0.0</version>
<authors>Author</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>.proto files NuGet package.</description>
<dependencies>
<dependency id="Google.Protobuf" version="3.14.0"/>
<dependency id="Grpc" version="2.35.0"/>
</dependencies>
<contentFiles>
<files include="any/any/Protos/**/*.proto" buildAction="None" copyToOutput="false" />
</contentFiles>
</metadata>
<files>
<file src="xxx.proto" target="contentFiles\any\any\Protos" exclude="google\**" />
<file src="build\*.props" target="build" />
</files>
</package>
4) then re-pack the new version of nuget project. Before you install the new release version, please clean nuget caches first or just delete all files under C:\Users\xxx\.nuget\packages
After the installation of the nuget package, please click Build button to execute the target.
More similar to this issue.
====================================================
Function Two
You could not do any internal steps for nupkg itself. You could directly copy the file from the external main project.
1) do not do any steps under Function One for your nuget package. Use your old nuget package.
Modify the Project A's csproj file which has installed GRPCProtoFiles nuget package.
Add <GeneratePathProperty>true</GeneratePathProperty> for PackageReference GRPCProtoFiles to generate an exclusive property as $(PkgGRPCProtoFiles) to get the path of the nupkg's content.
The whole is like this:
<ItemGroup>
<PackageReference Include="GRPCProtoFiles" Version="1.0.0">
<GeneratePathProperty>true</GeneratePathProperty>
</PackageReference>
</ItemGroup>
Then, right-click on the Project A-->Properties-->Build Events-->add these under Pre-build event Command Line:
xcopy /s /e /y /i $(PkgGRPCProtoFiles)\contentFiles\any\any\Protos $(ProjectDir)\Protos
Or, add this target into ProjectA.csproj file:
<Target Name="CopyFiles" BeforeTargets="PrepareForBuild">
<ItemGroup>
<File Include="$(PkgGRPCProtoFiles)\contentFiles\**\*.*"></File>
</ItemGroup>
<Copy SourceFiles="#(File)" DestinationFolder="$(ProjectDir)\Protos"></Copy>
</Target>

Internally distribute a Visual Studio Template using Nuget and SVN

Suppose we have a Visual Studio template that we would like to distribute within our organization. This template is hosted on an SVN server. I would like users to be able to point Nuget to the SVN location and get the template installed in the proper location just like any other package. Is this possible?
Is this possible?
We can do it but individuals do NOT recommend it.
How
According to the NuGet document:
Put simply, a NuGet package is a single ZIP file with the .nupkg
extension that contains compiled code (DLLs), other files related to
that code, and a descriptive manifest that includes information like
the package's version number. Developers with code to share create
packages and publish them to a public or private host. Package
consumers obtain those packages from suitable hosts, add them to their
projects, and then call a package's functionality in their project
code. NuGet itself then handles all of the intermediate details.
However, the Visual Studio Template is a file with the .zip extension, which could not be recognized by NuGet. Even if we point NuGet to the SVN location, NuGet still can not recognize it.
To resolve this issue, we have to create a NuGet package to include this Visual Studio Template .zip file, like:
<files>
<file src="TestDemo.zip" target="Tools\TestDemo.zip" />
</files>
Besides, there is another question, when we install this nuget package to the project, this Visual Studio Template .zip file would be downloaded to the \packages folder in the solution folder. We have to move it to the Visual Studio Templates folder.
So, we have to add .targets with copy task in that nuget package to copy zip file to the Visual Studio Templates folder.
The content of .targets file:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="CopyTemplate" BeforeTargets="Build">
<Message Text="Copy Template to template folder."></Message>
<Copy
SourceFiles="$(SolutionDir)packages\MyTemplatePackage.1.0.0\Tools\TestDemo.zip"
DestinationFolder="$(USERPROFILE)\Documents\Visual Studio 2017\Templates\ProjectTemplates"
/>
</Target>
</Project>
Finally, the .nuspec file like following:
<?xml version="1.0"?>
<package >
<metadata>
<id>MyTemplatePackage</id>
<version>1.0.0</version>
<authors>Tester</authors>
<owners>Tester</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Package description</description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2018</copyright>
<tags>Tag1 Tag2</tags>
</metadata>
<files>
<file src="TestDemo.zip" target="Tools\TestDemo.zip" />
<file src="MyTemplatePackage.targets" target="Build\MyTemplatePackage.targets" />
</files>
</package>
Then pack this .nuspec file, add this nuget package to the SVN location, add the SVN location to the nuget package source, you can install this nuget package to the project, and build the project, Visual Studio will download that nuget package and copy .zip file to the Visual Studio Templates folder.
I have created a sample test nuget package and it work fine on my side with Visual Studio 2017, you can test it on VS2017: https://1drv.ms/u/s!Ai1sp_yvodHf2Vax7TzuC6HQUD5w
Why not recommend
Just as you can see above, it is not easy and simple to do this, we have to do a lot of things to create that nuget package. What`s more, in order to get the template we have to create a project and install that package and build the project. It pulls in too many extra operations. Besides, when you change anything in the template, you have to re-create this package and install it.
Since this template is hosted on an SVN server, you can just check it to the Visual Studio template folder, this will be more effective.
Hope this complicated answer helps.

Is there a way to add an 'Import' to a project in a VS extension?

I want to add a new <Import> to a project when I detect that a particular type of file has been added to the project. (the <Import> adds a task to the build process that takes the file and performs work during a build).
(Detection of a file having been added to the project is done using IVsSolutionEvents.HandleItemAdded).
I currently have code that uses Microsoft.Build.Evaluation.Project to add an Import element to the project. However this is an edit to a project file on disk. If I use this code to add an Import after detecting the addition of a new item to the project I create a conflict between a change on disk (the new Import) and an in-memory change (the addition of the new file). The user is then presented with a dialog where they must choose which change to throw away.
My question is this:
Is there a way to add a new <Import> to a project via the visual studio extensibility API in such a way that the modification to the project would be "in-memory", avoiding a conflict between the addition of the new project item, and the addition of the Import?
For existing project types, I've found the easiest way is leveraging NuGet. You can define a NuGet package which contains the .targets file in a special build/ folder, and NuGet will automatically add the <Import> when it is added to a project within Visual Studio. It will also update the references if you upgrade the package in the future. A full example is the packaging of the Antlr4BuildTasks package, which currently uses the following .nuspec file to create the package. The key here is the section following the <!-- Build Configuration --> comment.
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata minClientVersion="2.7">
<id>Antlr4</id>
<version>0.0.0</version>
<authors>Sam Harwell, Terence Parr</authors>
<owners>Sam Harwell</owners>
<description>The C# target of the ANTLR 4 parser generator for Visual Studio 2010+ projects. This package supports projects targeting .NET 2.0 or newer, and built using Visual Studio 2010 or newer.</description>
<language>en-us</language>
<projectUrl>https://github.com/sharwell/antlr4cs</projectUrl>
<licenseUrl>https://raw.github.com/sharwell/antlr4cs/master/LICENSE.txt</licenseUrl>
<iconUrl>https://raw.github.com/antlr/website-antlr4/master/images/icons/antlr.png</iconUrl>
<copyright>Copyright © Sam Harwell 2014</copyright>
<releaseNotes>https://github.com/sharwell/antlr4cs/releases/v$version$</releaseNotes>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<developmentDependency>true</developmentDependency>
<tags>antlr antlr4 parsing</tags>
<title>ANTLR 4</title>
<summary>The C# target of the ANTLR 4 parser generator for Visual Studio 2010+ projects.</summary>
<dependencies>
<dependency id="Antlr4.Runtime" version="$version$" />
</dependencies>
</metadata>
<files>
<!-- Tools -->
<file src="..\tool\target\antlr4-csharp-$CSharpToolVersion$-complete.jar" target="tools"/>
<!-- Build Configuration -->
<file src="..\runtime\CSharp\Antlr4BuildTasks\bin\net40\$Configuration$\Antlr4.net40.props" target="build\Antlr4.props"/>
<file src="..\runtime\CSharp\Antlr4BuildTasks\bin\net40\$Configuration$\Antlr4.net40.targets" target="build\Antlr4.targets"/>
<file src="..\runtime\CSharp\Antlr4BuildTasks\bin\net40\$Configuration$\Antlr4BuildTasks.net40.dll" target="build"/>
</files>
</package>

Is it possible to get NuGet.exe running disconnected from Visual Studio?

I've been wrestling with NuGet for a few days now and I'm turning to StackOverflow in frustration - hopefully someone here can be kind enough to point me in the right direction.
I've used NuGet several times for simple one-man pet projects, but this is the first time I've used it for something I really care about and want to have fully continuous builds, etc. I'm trying to create a simple NAnt build script to get the source for Git, ensure the external dependencies have been brought down, compile, and run tests - vanilla CI.
I originally went down the path of trying to get solution restore working, but it just didn't work or I didn't how it worked. Visual Studio is not on the build server and will not be installed there - that is not an option. As an aside, I couldn't get solution restore to work just with two developers (one trying to bring down the source fresh and build cleanly). I'm assuming it's because "allow solution restore" must be turned on everywhere (and is not by default). I punted on that approach before I got to the bottom of it - frankly, having my package manager so tightly coupled to the IDE makes me uncomfortable and was hoping I could do it another way. The package managers I'm used to using are simple command line tools - the CI build script invokes it on build, and developers do it on demand. I've spent the last two hours trying to get this working with the last 30 minutes in the NuGet source code. I feel like I'm fighting the tool and need to reboot.
Does anyone have any examples of the best to use NuGet in a multi-developer + CI scenario? This is what I want:
Any and all developers can get the source and run the tests in 3 or
less clicks (preferably 1). If the binaries are not present locally, that will be JIT fetched. If they are there, they will be updated if necessary, etc. This would ideally not even require NuGet to be installed (i.e. NuGet.exe would need to be in my repo).
Do #1 via a CI server like Jenkins, TeamCity, etc. (preferably using the same script)
If its not overly fighting the tool, I would like to have all this disconnected from Visual Studio with a single packages.config file and all binaries dumped into a single Lib folder in the root of the repo.
Any pointers would be very much appreciated.
Below, how I think you can achieve each your requisites:
You need to "Enable NuGet Package Restore" in your solution: http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages
As #alexander-doroshenko mentioned for TeamCity you can use Nuget Installer: http://confluence.jetbrains.com/display/TCD7/NuGet+Installer, but if you want a script to run in Jenkins, try this (works at TC too, as a command line step) for each project:
nuget.exe install "[Project folder]/packages.config" -source "" -solutionDir "" -OutputDirectory "packages"
This requisite will be done by item 1 and 2.
TeamCity has a build step for that, called "NuGet Installer", it fetch required packages from .sln file and download the locally. It does not require Visual Studio to run.
Read more about it here: http://confluence.jetbrains.com/display/TCD7/NuGet+Installer
There are several different solutions for integrating NuGet into your build process depending on how much integration you require. In our case we wanted to use NuGet as package manager and allow developers to build their solutions even if they haven't got NuGet installed on their machine. For that to work we enabled package restore which adds the NuGet binaries to your solution folder and updates the project files. Note that NuGet doesn't always do the update of the project files correctly. In our case we found that some project files got updated but others didn't. To verify that the project was updated you will need to open the project file as XML file. To achieve this load the solution and right click the project in question and select unload project. Then right click the project again and select edit [PROJECT_NAME]. In the project file you should see
A RestorePackages property in the first propertygroup. This property should have the value true
An import statement at the very end of the project file. This import statement should point to the 'NuGet.targets file that accompanies the NuGet binary.
Below is an example of one of our project files (heavily edited)
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="'$(SolutionDir)' == '' or '$(SolutionDir)' == '*undefined*'">$(MSBuildProjectDirectory)\..</SolutionDir>
<ProjectGuid>{8B467882-7574-41B2-B3A8-2F34DA84BE82}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>MyCompany.MyNamespace</RootNamespace>
<AssemblyName>MyCompany.MyNamespace</AssemblyName>
<!-- Allow NuGet to restore the packages if they are missing -->
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<Import Project="$(SolutionDir)\BaseConfiguration.targets" />
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="MyClass.cs" />
<!--
.... MANY MORE FILES HERE
-->
</ItemGroup>
<!-- Import the Nuget.targets file which integrates NuGet in the build process -->
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.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>
The next step you'll need to take is to provide a solution level NuGet configuration file in which you'll indicate where the packages need to be 'installed' and what the URL of the package repository is. In our case the solution directory structure looks like:
(D) root
(D) build
(D) packages
(D) source
(D) .nuget
NuGet.config
NuGet.exe
NuGet.targets
(D) MyCoolProject
MyCoolProject.csproj
MyCoolProject.sln
(D) templates
NuGet.Config
Where (D) indicates a directory.
The NuGet.config file contains the following configuration settings.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageRestore>
<add key="enabled" value="True" />
</packageRestore>
<config>
<add key="repositorypath" value="packages" />
</config>
<packageSources>
<add key="OurPackageServer" value="PACKAGE_SERVER_ADDRESS" />
</packageSources>
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
This configuration file indicates that package restore is enabled, that the repository path (where the packages are placed) is the packages directory and which package sources are active.
By placing a NuGet.config file in the root directory we can use the hierarchical configuration option with NuGet. This allows the individual solutions to override computer specific configurations. The other benefit is that this way we don't need to have NuGet installed on the build server (because the executable and the configurations are in the repository).
With this setup developers can build the solution from Visual Studio. The build should work fine on developers machines even if they don't have NuGet installed. Note however that they won't be able to add packages to a project without having NuGet installed in visual studio.
On the build server you can simply use MsBuild to build the solution which will automatically download the packages from your package repository. Visual Studio is not required to be installed on the build machine for that (just the .NET framework of your choice).

How to create NuGet package that includes XML intellisense data

This link How do I create an XML Intellisense file for my DLL? explains how to build your dlls so that an XML file is included containing all your documentation headers so that they are available in those IntelliSense popups.
In my company we frequently distribute our own dlls using an internal NuGet package source. When I create NuGet packages for the package source, how do I ensure that someone else gets the dll from the package source, IntelliSense displays the documentation headers for them?
If you distribute your XML files with your NuGet package in the same folder as your Dlls then Visual Studio will then find these XML files and show IntelliSense for your assemblies.
To distribute the IntelliSense XML files you will need to add them to your .nuspec file, for example:
<files>
<file src="bin\IronPython.dll" target="lib\Net40" />
<file src="bin\IronPython.xml" target="lib\Net40" />
</files>
tl;dr documentation files need to be .xml not .XML
I was able to get the XML files included by first enabling the production using the Build tab, checking XML Documentation File in the Output section. Note: for some reason I had to manually change the extension from .XML to lowercase .xml. YMMV. This is the same as the question you referenced, How do I create an XML Intellisense file for my DLL?.
Once done, I created the Nuspec file in the project directory. Here's a sample, you can also generate it with nuget spec MyAssembly.dll - but make sure to edit it and set the values appropriately.
<?xml version="1.0"?>
<package >
<metadata>
<id>$id$</id>
<version>1.0.0</version>
<title>Title for your package</title>
<authors>Package Author</authors>
<owners>Package Owner</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A description of your library</description>
<releaseNotes>Release notes for this version.</releaseNotes>
<copyright>Copyright 2013</copyright>
<tags>tag1 tag2</tags>
</metadata>
</package>
Once that was done, I used Nuget to package. Note I had to specify the platform because I'm using a 64-bit OS, but I don't have any targets in the project for x64, only AnyCPU
nuget pack MyAssembly.csproj -Prop Configuration=Release;Platform=AnyCPU -build
The assembly and it's associated documentation were automatically included in the package. In addition any packages that you've used in your project are added to the dependency list.
See http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package for more information.

Resources