Target framework not effective in VS2019 - c#

I have a test harness in a project that was created in VS2013 (Framework 4.5). To test things out for VS2019, I added a local function (from C# 7). The project still targets 4.5, yet it compiles and runs without any errors. This isn't good - I want people to be able to go and edit in VS2013 if that's the version they got. Tell me I'm missing something simple here.
static void Main(string[] args)
{
string LocalFunction()
{
return "yeah, im local, dude.";
}
Console.WriteLine(LocalFunction());
Console.ReadKey();
}

Do you want to force to use the same language features? In that case, set the LangVersion property in your csproj file (or build property file) that MSBuild will recognize. For example, this will limit the language feature to C# 6 (even for .NET 5 projects):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>6</LangVersion>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Then, you will see the compile time error:
Refer to official doc for all values you could put there.

Related

error CS8773: "Feature 'global using directive' is not available in C# 9.0" after downgrade from net6.0 to net5.0

I have a project that was initially created for .NET 6 but then I needed to downgrade it to .NET 5.
I changed Target framework in Project Properties and tried to compile. As a result I received a bunch of the errors:
GlobalUsings.g.cs(2,1,2,29): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater.
File GlobalUsings.g.cs is created automatically and it reappears every time after compilation.
Finally I found that the reason is an extra property ImplicitUsings in the project file that is not supported by .net 5.0.
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
I needed to remove ImplicitUsings from the file.
remove <ImplicitUsings>enable</ImplicitUsings> in the csproj project file, then can build success
find this solution from here
Remove the tag indeed work.
But just change the value of it did the trick as well!
<ImplicitUsings>disable</ImplicitUsings>
To get rid of this error which is caused by downgrading below net6.0.
Remove the following items from the .csproj file:
<ImplicitUsings>
<Using Include="..." />
If you don't want to remove the ImplicitUsings or made changes to the project file. You can tell the build cli to disable it during build process by
dotnet build --configuration "Release" --framework "net5.0" /p:ImplicitUsings=false /p:PublishReadyToRun=false

C# Visual Studio 2019, Meta Numeric, Error: Could not load file or assembly

Visual Studio 2019
C#
Project 1:
Dependencies: Meta.Numerics 4.1.4. I added Meta Numerics via the Manage NuGet Packages for Solution
Project 1 is a Class Library
Will be compiled and .dll will be shared with an associate who will use it in the main application
Project 1 builds just fine using Debug.
using System;
using Meta.Numerics;
namespace LeakDetection
{
public class LeakDetectionOperations
{
public LeakDetectionOperations(int co = 24)
{ }
public int leakCheck()
{
double result = ComplexMath.Abs(10);
return 0;
}
}
}
Project 2
Dependencies: Project 1. Imported via Add references, browser, and selected the .dll from project 1
Project 2 is just a simple test project that I'm using to test the .dll object.
It runs, but throws an exception when it attempts to call the ABS function of Meta.Numerics.
using System;
using LeakDetection;
namespace LeakTest
{
class Program
{
static void Main(string[] args)
{
LeakDetectionOperations obj = new LeakDetectionOperations();
int ret;
ret = obj.leakCheck();
Console.WriteLine("Hello World!");
}
}
}
I've followed the instructions from the Meta.Numeric gitrepo regarding installation. The installation was done as they suggested to install the package. I've also cleaned build, and rebuilt fresh. I also changed from debug to release to see if there was anything related to the debug that was causing the error. As you can see at the above code, its fairly minimum, as this is not my actual code. Its a bit more elaborate, but rather than posting the full code, this is the minimum usable code that replicates the issue I'm having. Nothing from the Meta.numeric library is usable.
I usually work in Python, have some experience in C and C++, but I have used make files to compile in linux. Using C#, visual studio is fresh for me.
Any suggestions as to where I should look would be much appreciated.
UPDATE:
Per the suggestion by #kit, I've included the .csproj file for project 1 below
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>Leak_Detection</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Meta.Numerics" Version="4.1.4" />
</ItemGroup>
</Project>
.csproj for project 2
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="Leak Detection">
<HintPath>..\..\Leak Detection\Leak Detection\bin\Debug\netcoreapp3.1\Leak Detection.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
I was able to kind of replicate your issue (not exactly but I got the same kind of error). I believe your test project is in .NET framework. If I do not reference any nuget package in test project, failure occurs. But, if I install any nuget package and later on uninstall it, program runs successfully. For testing, I installed and uninstalled Newtonsoft.Json package. So, there is a bug in initialization of nuget package engine for .NET framework where in absence of any nuget packages, it is not able to resolve transitive nuget dependencies. If I create test project in .NET core, test project runs without any issue.
I have also put code in github
https://github.com/dheerajjain11/MissingDLLIssue/
MetaNumerics is .NET Standard library
MetaNumericsTest is .NET Framework Test project where I installed and uninstalled nuget package. Now, it runs successfully
MetaNumerics2 is .NET Framework Test project which fails
MetaCore is dotnet core project which runs without any issue and no workarounds
I don't know if this is normal or not, but what resolved the issue for me was installing the package via the Nuget package manager on both the Library and the Console application. Both builds need a reference.
What I was doing previously, was only installing the package for the library build. Seeing how the console application was then compiling with the .dll being referenced and called, the calling application also needed the package installed.

IAsyncEnumerable<> broken in VS 2019 preview 2 (Core 3.0 preview 1)

After installing VS 2019 preview 2 i get a great number of errors. Error demo code:
public class Class1 {
public static async IAsyncEnumerable<int> Get()
{
for( int i = 0; i < 10; i++ ) {
await Task.Delay( 100 );
yield return i;
}
}
}
and nothig more (a new dll project)!
With preview 1 was ok.
The project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
</Project>
The error message is:
Error CS0656 Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator'
Object Browser shows the member in Collections.Generic.
Any ideas? Waiting for Core 3.0 preview 2?
Something like in IAsyncEnumerable not working in C# 8.0 preview
?
Another problem with VS 2019 P2 (another project):
Nullabilty warnings though NullableReferenceTypes line is there (in vs 19, preview 1 was ok):
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>8.0</LangVersion>
**<NullableReferenceTypes>true</NullableReferenceTypes>**
The warning:
Warning CS8632 The annotation for nullable reference types should only be used in code within a '#nullable' context.
Is project setting not enough? not global any more?
Problem 1
Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator'
Solution
Install .NET Core v3.0.100-preview-010177
https://github.com/dotnet/core-sdk#installers-and-binaries
Explanation
There was a breaking change to IAsyncEnumerable from .NET Core 3 Preview 1 to .NET Core Preview 2
Async streams
We changed the shape of the IAsyncEnumerable interface the compiler expects! This brings the compiler out of sync with the interface provided in .NET Core 3.0 Preview 1, which can cause you some amount of trouble. However, .NET Core 3.0 Preview 2 is due out shortly, and that brings the interfaces back in sync.
Source: https://blogs.msdn.microsoft.com/dotnet/2019/01/24/do-more-with-patterns-in-c-8-0/
Problem 2
The annotation for nullable reference types should only be used in code within a '#nullable' context
Solution
Change<NullableReferenceTypes>true</NullableReferenceTypes>
to
<NullableContextOptions>enable</NullableContextOptions>
Explanation
This is a breaking change from VS2019 Preview 1 to VS2019 Preview 2.
Nullable reference types
We’ve added more options to control nullable warnings both in source (through #nullable and #pragma warning directives) and at the project level. We also changed the project file opt-in to enable.
Source: https://blogs.msdn.microsoft.com/dotnet/2019/01/24/do-more-with-patterns-in-c-8-0/
Replacing
<NullableReferenceTypes>true</NullableReferenceTypes>
With
<NullableContextOptions>enable</NullableContextOptions>
Fixed my issues with nullable reference types.
EDIT:
It may be worth having both options in the .csproj file as the dotnet Docker images has not yet been updated and will fail as it does not recognize the new nullable reference type tag
In Visual Studio 16.2 the property name changed to Nullable which is simpler and aligns with the command line argument.
<PropertyGroup>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

Custom .NET Standard Nuget package not installing correctly

I have a .NET Standard class library project with a number of POCO's. This project is built using TeamCity and published as a Nuget package using the built-in Nuget server.
The problem I'm having is when it's installed into my solution with a number of .NET Framework class library projects and ASP.NET MVC and Web API projects (set to .NET Framework 4.7.1), it seems to be stuck on an older version and is not recognising any new classes or methods I add to the project - e.g. NewMethod1()
Project File for Nuget package
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;net462;net47</TargetFrameworks>
<Version>1.0.0</Version>
</PropertyGroup>
<PropertyGroup>
<NetStandardImplicitPackageVersion>2.0.0</NetStandardImplicitPackageVersion>
<Description>Standard entities used within our systems</Description>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<Authors>Company X</Authors>
<Company>Company X</Company>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<OutputPath>bin\Release</OutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<OutputPath>bin\Debug</OutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
</Project>
TeamCity is using the 'dotnet' restore, build & pack options.
The package is stored in my Nuget cache located in C:\Users\antho.nuget\packages. When I use Object Browser to inspect the dll, it contains the new classes and methods (e.g. NewMethod1()).
When I install this package into my .NET Framework solution, no errors occur during the installation. If I try and use the new method - NewMethod1() - the code doesn't compile.
If I create a brand new solution and ASP.NET MVC project and install the package, the new method can be used in code and it compiles successfully.
What could be causing the new version not to be installed correctly? It's tricky to provide a sample reproducing the issue because it seems to work in a new project.
Update
If I add a new project to the solution and install the Nuget package, it gets the latest version.
Project A
<PackageReference Include="AutoGuru.Shared.Utilities" Version="1.0.369" />
public class Class1
{
public void Test()
{
"dfdfdfdf".SanitizeVehicleRego();
}
}
Project B
<PackageReference Include="AutoGuru.Shared.Utilities">
<Version>1.0.369</Version>
</PackageReference>
public class Class1
{
public void Test()
{
"fdfdf".SanitizeVehicleRego();
}
}
Project B compiles successfully and Project A doesn't. SanitizeVehicleRego() is a string extension method in the AutoGuru.Shared.Utilities package.
My answer it quite big, so I add an answer instead of comment.
Step 1
Check the output when you restore the package, sometimes dotnet restore resolve an other version automatically ( you should have a warning for this kind of things in your console ).
Step 2
If any information was found in Step 1. Try to clean all your local nuget cache.
dotnet nuget locals all --clear
I'm not sure if local nuget packages are under cache stategy. But if they are, it should resolve the correct version of your package.

How to reference csproj from kproj

I was playing around with VS2015 and ASP.NET vNext, and got stuck on trying to add a reference from vNext class library (kproj) to a regular class library (csproj) in the same solution. Visual Studio 2015 shows the following error message:
"The following projects are not supported as references".
Is it possible at all to add references to csproj from vNext class libraries?
Note: The kpm command has been replaced by dnu.
Visual Studio 2015 Preview (as of writing this) comes with the ASP.NET 5 stable release beta1. In this version there is no way to reference a csproj project from an ASP.NET 5 project.
However, on the development feed of ASP.NET 5 the command kpm wrap was introduced to support referencing csproj-projects from ASP.NET 5 projects. See the github issue #827 in the aspnet/KRuntime repository and pull request #875 which closes the issue.
Here is an example how you would use kpm wrap:
Make sure the newest version of the KRuntime is installed (check this with the kvm list command) (I tested this with version 1.0.0-beta2-10709).
Create an ASP.NET 5 class library project, I used the name ClassLibrary1.
Create a "normal" csproj class library, I named this ClassLibrary2 (make sure you put this in the src folder).
From the commandline, from the solutiondirectory run the command
kpm wrap .\src\ClassLibrary2
This gives the output:
Wrapping project 'ClassLibrary2' for '.NETFramework,Version=v4.5'
Source C:\Users\andersns\Source\ClassLibrary1\src\ClassLibrary2\ClassLibrary2.csproj
Target C:\Users\andersns\Source\ClassLibrary1\wrap\ClassLibrary2\project.json
Adding bin paths for '.NETFramework,Version=v4.5'
Assembly: ../../src/ClassLibrary2/obj/debug/ClassLibrary2.dll
Pdb: ../../src/ClassLibrary2/obj/debug/ClassLibrary2.pdb
Now in the project.json of ClassLibrary1 (which is ASP.NET 5) you can add a reference to ClassLibrary2 with this:
...
"dependencies": {
"ClassLibrary2": ""
},
...
Note: kpm wrap did not run properly for me with cmd, I needed to launch powershell to make it run.
Starting with (Visual Studio 2015 RC) the kpm command has been replaced by dnu
The dnu command stands for (.NET Development Utility)
dnu wrap .\src\ClassLibrary2\ClassLibrary2.csproj
New ASP.NET Features and Fixes in Visual Studio 2015 RC
http://blogs.msdn.com/b/webdev/archive/2015/04/29/new-asp-net-features-and-fixes-in-visual-studio-2015-rc.aspx
I have found it easiest to simply create a corresponding .kproj for the .csproj I want to reference. The .kproj does not require listing every included file, so this is rather straightforward.
You can create YourProject.kproj as a text file with the contents below, and only replace the [REPLACE_WITH_UNIQUE_GUID] and [ROOT_NAMESPACE].
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>[REPLACE_WITH_UNIQUE_GUID]</ProjectGuid>
<RootNamespace>[ROOT_NAMESPACE]</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<ProduceOutputsOnBuild>True</ProduceOutputsOnBuild>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
You can then add this project to your solution and reference it from your MVC 6 project.
In addition to this answer I found out that you need to use the if directive (#if) to make the call without errors:
Something like:
#if ASPNET50
using class2
#endif
When you use it in a call you need to do the same.
#if ASPNET50
ViewBag.Message = class2.Class1.Greetings()
#endif

Categories