The attribute "Include" in element <PackageReference> is unrecognized - c#

I created a Directory.Build.props file by right clicking the Solution on Solution Explorer, creating an XML file, and named it so. I then input this XML and tried building but was met with errors:
<Project>
<PropertyGroup>
<Version>1.2.3</Version>
<Authors>John Doe</Authors>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</PropertyGroup>
</Project>
The errors say:
The attribute "Include" in element <PackageReference> is unrecognized. and
Project "C:\redacted\Directory.Build.props" was not imported by "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Microsoft.Common.props" at (33,3), due to the file being invalid. ProjectName C:\Users\me\source\redacted\ProjectName\Directory.Build.props 33
I am so confused here. The other articles said to locate the MSBuild and I know that its on my machine. The build was working just fine prior to me adding the XML too. Any guidance would be very appreciated! I am currently on Visual Studio 2022 by the way.

The PackageReference element needs to be in an ItemGroup - you've got it in a PropertyGroup. It should look like this:
<Project>
<PropertyGroup>
<Version>1.2.3</Version>
<Authors>John Doe</Authors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

I had the same kind of problem one time and I found out it was caused by ‘\xef\xbb\xbf#’ which is a ‘Unicode BOM(Byte Order Mark)’ and consists of invisible characters added by certain text editors like Notepad++, for instance. The BOM often functions as a magic number used to pass along information to the program reading the file, such as the Unicode character encoding or endianess but it's presence can interfere with software that does not expect it.
The way I found it by fluke was I had my csproj file on github and when I clicked 'edit', the BOM stuck out like a red dot. I simply backspaced on it and then everything went well.

I came accross the same kind of problem, for me it was due to invalid XML structure :
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.2.32">
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.3">
</PackageReference>
</ItemGroup>
As you can see, the first PackageReference tag was not closed, leading to the exact same error The attribute "Include" in element <PackageReference> is unrecognized. on the second PackageReference tag.
Valid XML structure :
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.2.32"/>
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.3"/>
</ItemGroup>
I hope that can help somebody else !

Related

Configuring assets for analyzers packages

My solution consists of multiple projects. In the root we have Directory.Build.props
<Project>
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SonarAnalyzer.CSharp" Version="8.51.0.59060" Condition="$(MSBuildProjectExtension) == '.csproj'">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" Condition="$(MSBuildProjectExtension) == '.csproj'">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
These static code analyzers are using only during development. I see that I can configure assets and prevent exposing these packages. My solution structure:
ServiceA.Api.csproj
ServiceA.Core.csproj
ServiceA.Domain.csproj
ServiceA.Infrastructure.csproj
ServiceA.SDK.csproj
What are the implications for setting PrivateAssets and IncludeAssets in certain ways? What practice for the values of these makes sense in the context of analyzer packages?
If the analyzers are only used for development on the developer's machines, I recommend accepting the package references however NuGet adds them, and then conditionally only including them using the parent <ItemGroup> in your DevOps pipeline. This usually means only include them for Debug but not Release.
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
...
</ItemGroup>
If that is not granular enough (e.g. when you want to build both Debug and Release locally and/or in the pipeline, or you want the analyzers to run during DevOps pipeline exection always), you can take the advice in Controlling dependency assets.
There is no one best practice for this because requirements vary. The defaults are most likely what you should start with because the defaults are chosen for a reason.
The defaults, as mentioned in the content for the above link, are
IncludeAssets --> all
ExcludeAssets --> none
PrivateAssets --> contentfiles;analyzers;build
Unless you are optimizing the size of your final solution, trying to prevent exposure of analyzers to prevent some sort of security issue or misuse, or otherwise trying to avoid some sort of problem, I would say, "just use them as they are, assets set to the values NuGet used when adding the analyzer package".

Is there a way to suppress MSBuild warnings in a specific subdirectory with .NET Core?

I am gettings warnings from compiling my ASP.Net 6 Razor project, errors that are mainly linked to the lack of <summary> comments in my migrations folder.
I have tried to add the following Directory.Build.props file to my .\Data\Migrations folder as I had found somewhere that I could suppress warnings in that folder.
<Project>
<PropertyGroup>
<DisabledWarnings>CS1591;IDE0161</DisabledWarnings>
</PropertyGroup>
</Project>
Yet, I keep getting the same errors:
1591: Missing XML comment for publicly visible type or member 'CorrectedSpellingOf2FAEnabled' [<redacted>\3moons.csproj]
<redacted>\Data\Migrations\20220526151631_CorrectedSpellingOf2FAEnabled.cs(9,33): warning CS
1591: Missing XML comment for publicly visible type or member 'CorrectedSpellingOf2FAEnabled.Up(MigrationBuilder)' [<redacted>\3moons.csproj]
...
I have also tried to redact the warning labels:
<PropertyGroup>
<DisabledWarnings>1591;161</DisabledWarnings>
</PropertyGroup>
Alas, this doesn't work. The warnings are still present.
For reference my .csproj file is as follows:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>Minustar.Website</RootNamespace>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
<PackageReference Include="Westwind.AspNetCore.Markdown" Version="3.8.0" />
</ItemGroup>
</Project>
My intuition is that there could be a way to suppress those warning, or any other, directly from the .csproj file but I am unsure how and where.
In advance, thank you.
PS:
I have also tried this, on #Ryan Wilson's suggestion, to read on the warning suppression page.
[assembly: SuppressMessage("Compiler", "CS1591", Target="N:Minustar.Website.Data:migrations", Scope="namespaceanddescendants")]
To no avail, I still get the messages in the compiler output, and both VSCode and VS2022 still list the issues as a warning. It did however seem to work for [SuppressMessage("Compiler", "IDE0161")] (this one suggests the use file-scoped namespace declaration instead of what the EF Core migrations tool emmits.)
I am still convinced that it is possible to achieve the desired result out-of-the box, so to speak, without any 3rd party tools; however, the solution evades me entirely. 😔
PPS: Disabling the GenerateDocumenationFile option is preferably not an option.

After clean project regenerating c# files from .proto in another project

I have two projects:
Project hosts the code of the gRPC server and also the .proto files.
Project acts as the client but has also a lot of other different functionality
I want to be able to clean and build my client project, that depends on auto generated .cs files. To generate the .cs files from .proto files Google.Protobuf and Grpc.Net.ClientFactory is used.
So far I've done:
I added a service reference to my 2. project.
My 2.project.csproj looks like (for an Example.proto):
<ItemGroup Condition=" '$(TargetFramework)' == 'net48' ">
<PackageReference Include="Grpc.Core" Version="2.32.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Grpc.AspNetCore" Version="2.32.0" />
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.32.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0-windows'">
<PackageReference Include="Grpc.AspNetCore" Version="2.32.0" />
<PackageReference Include="Grpc.Net.ClientFactory" Version="2.32.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.13.0" />
<PackageReference Include="Grpc.Tools" Version="2.32.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<Protobuf Include="..\Project_A\Protos\Example.proto" GrpcServices="Client">
<Link>Protos\Example.proto</Link>
</Protobuf>
</ItemGroup>
When I am now changing the .protofile the client .cs files get generated in the path:
...\2.project\obj\$(ConfigurationName)\$(FrameworkName)\
This all fine when simply building the second project. But whenever the second project gets a clean rebuild the .cs files are not generated again leaving me with missing dependencies.
I would guess somewhere is a option to trigger the generation of .proto files before the build starts?
Or Should I exclude the generated files from the cleanup?
Or is there some other way to achieve this that I'm not seeing?
UPDATE:
I now moved the proto files in a seperate project and import them now using this statement:
<ItemGroup>
<Protobuf Include="..\Proto_Project\Protos\Example.proto" GrpcServices="Client" OutputDir="Protos" CompileOutputs="false">
<Link>Protos\Example.proto</Link>
</Protobuf>
</ItemGroup>
This works in that way, that everytime I change the proto, it gets reconverted in .cs.
But here is the source of my current (and also previous, as I know think) problem. Every time I rebuild the solution the protofiles get reconvertet to .cs. The problem is that this happens after the compilation of the project. This leads to missing dependencies, since the files are not present at compile time. When simply building the solution the files are not retranslated and everything works.
How can I either stop the protobuf compiler from running on rebuild, or let him run earlier?
I would advice you to decouple the two projects by moving all the .proto files to a separate code repository. Next use that repository in your other projects and generate the proto code for that project specifically. This way you can also use the backwards compatibility properties of Protobuf.
With git you can do that with git submodules. You can track the version of the proto file repo in your server and client project.

Using ANTLR4 in .NET Core without the use of external Java library?

I've followed through these instructions but I get a ton of compilation errors after the files have been compiled.
What I have done:
Created a new Console project in .NET Core 3.1.
Installed NuGet package Antlr4.
Added a new text file named example.g4 to the project, and saved it in encoding UTF-8 without signature.
Populated the grammar with some demo features.
Build Solution.
Ton of errors after successful compilation of lexer/visitor/parser/etc.
Some of those errors include the following:
The name '_interp' does not exist in the current context AntlrDemo C:\AntlrDemo\obj\Debug\netcoreapp3.1\exampleLexer.cs 45 Active
'ParserATNSimulator' does not contain a constructor that takes 2 arguments AntlrDemo C:\AntlrDemo\obj\Debug\netcoreapp3.1\exampleParser.cs 95 Active
'exampleParser.TokenNames': no suitable method found to override AntlrDemo C:\AntlrDemo\obj\Debug\netcoreapp3.1\exampleParser.cs 69 Active
What's going on?
The issue is not from the grammar - it successfully compiles in .NET Framework.
If you don't mind working with the official Antlr4 code generator and runtime, but don't want to actually download and install Java and the Antlr Tool .jar by hand, try this instead:
Install the latest NET 5, or use old NET Core.
dotnet new -i Antlr4BuildTasks.Templates
mkdir Foo
cd Foo
dotnet new antlr
dotnet build
dotnet run
This does use the Antlr4 Java tool, but it's completely hidden. You don't download the runtime, nor Java. It's all contained in the Antlr4BuildTasks tool that you just reference in your .csproj. If you want to work with an older Antlr4 version, like 4.8 or 4.7, Antlr4BuildTasks will download the tool and runtime from Maven Central and NuGet.org; you just set the versions in the .csproj file then "dotnet build".
I have another tool that generates a driver for grammar and support code for C# (both official and Harwell's version), Java, and JavaScript targets. It is now being used for CI in github.com/antlr/grammars-v4.
If you try swapping between Antlr4 (the official Antlr4) and Antlr4cs (Harwell's tool/runtime), you will find the tools and runtime are quite different. There is no shim to allow code written for one runtime to be used in the other, but I am working on one.
As far as the <PrivateAssets> code in the .csproj file, getting rid of the lines as you suggest is fine. The reason it is included is to not propagate the dependent assemblies of the build tool directly into your code. But, while the tool is only useful in building the app, not running it, <PrivateAssets> doesn't prevent the assembly for the tool itself is still being included.
--Ken
After you install Antlr4 NuGet package, the following code is added to your .csproj file:
<ItemGroup>
<PackageReference Include="Antlr4" Version="4.6.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
The fix was to change the above to the following:
<ItemGroup>
<PackageReference Include="Antlr4" Version="4.6.6">
<!--<PrivateAssets>all</PrivateAssets>-->
</PackageReference>
</ItemGroup>
It also seems to work by uncommenting the PrivateAssets element. But I have no idea what the actual problem is here, and if I'm doing something wrong. Can someone shine some light about it?
EDIT: Another alternative solution is to instead install the two NuGet Packages Antlr4.CodeGenerator and Antlr4.Runtime.
Hopefully, this won't cause more confusion. I just moved my C# parser library from NET Framework 4.8 to NET 5 and was able to build it without errors with this .csproj file.
I changed the target framework from net5.0 to net5.0-windows7.0 in the example below to avoid compiler warning CA1416 which protested that I was using debug print methods (based on Console.Writeline calls with param[] arguments) in my code. I wanted to keep my debugging messages so I switched from the net5.0 target.
But the plain 'net5.0' compiled okay for me (except for the warnings I just described). My simple test cases ran fine with net5.0.
Here is an excerpt from my class library file, showing that I could leave the PrivateAssets and IncludeAssets lines alone.
<PropertyGroup>
<!-- use net5.0-windows7.0 to avoid CA1416 warnings about Console Writeline calls only available in win7 and later-->
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Antlr4" Version="4.6.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Antlr4.Runtime" Version="4.6.6" />
</ItemGroup>
Here is an excerpt from my unit test project, showing the inclusion of Antlr4(4.6.6) and the Antlr4.Runtime(4.6.6).
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Antlr4" Version="4.6.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Antlr4.Runtime" Version="4.6.6" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.8" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.8" />
<PackageReference Include="coverlet.collector" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

Illegal characters in path : Visual Studio 2019

I'm not sure why but I simply just can't run my VS 2019 project(Azure Functions v3 proj) all of a sudden; it shows
Illegal characters in path
This is not an issue with the current branch that I'm working with; it's an issue with projects in all the branches. This is also the same path where the project was running successfully all this time. Rebuild , Restart of VS, Re-clone of the project, deleting the contents of the bin and the obj folders and then running again - I have tried everything, but nothing helped. I have also tried repairing and even re-installing VS but it was of no help.
The .csproj file looks completely fine to me at least:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.13.1" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.10" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.2" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.6" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
This post also didn't help: Visual Studio- Illegal characters in path
Any help whatsoever would be very helpful.
Firstly, thanks to all of you for your suggestions to resolve this issue. After spending hours for a fix on this issue(which even included re-installing VS!), I finally chanced upon this life-saver of an article: Visual Studio 2017/2019 fails when I create an Azure Functions project.
The remedy is pretty simple, we just need to remove %localappdata%\AzureFunctionsTools and this would do the magic.
I hope this answer is helpful for all those who would stumble upon this later.

Categories