Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported [duplicate] - c#-9.0

This question already has answers here:
Testing C# 9.0 in VS2019 - CS0518 IsExternalInit is not defined or imported ... How do I define/import it?
(4 answers)
Closed 2 years ago.
I have been having this issues while testing the new features of C# 9.0 with Visual Studio 2019 Preview. I was testing the init setter, but the compiler shows error with the message:
Error CS0518 Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported. Below is the code snippet that I've tried:
public class Book
{
string ISBN { get; init; }
}

This is a small bug in Visual Studio 2019 that hasn't been fixed yet. To solve this, you need to add a dummy class named IsExternalInit with the namespace System.Runtime.CompilerServices anywhere in your project. That will do it.
If writing a library it's best to make this class internal, as otherwise you can end up with two libraries both defining the same type.
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit {}
}
Edit (November 16, 2020):
According to a reply I got from the Principle Developer Lead on C# Language Team, Jared Parsons, the issue above is not a bug. The compiler throws this error because we're compiling a .NET 5 code against older .NET Framework version. See his message below:
Thanks for taking the time to file this feedback issue. Unfortunately
this is not a bug. The IsExternalInit type is only included in the
net5.0 (and future) target frameworks. When compiling against older
target frameworks you will need to manually define this type.
Link to the report on Visual Studio Developer Community: https://developercommunity.visualstudio.com/content/problem/1244809/error-cs0518-predefined-type-systemruntimecompiler.html

If you want to stay with .NET Core App 3.1, you will need to add the type like Kinin Roza explained in in this bug report.
However, if you change your csproj to have the <TargetFramework> set to net5.0, it will solve your problem as this type is only defined in 5.0.
Here's my sample Console app csproj file.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>

Related

VS Code - Error check missing in some projects

I made a new solution in .NET with a class library (dotnet new classlib) and an XUnit test project (dotnet new xunit). I then added a reference to the class library, from the test project (dotnet add <test-project> reference <class-library>).
Now I have live error checking (syntax highlighting) in the class library, but no in the test project. You can see an example below, where the class Foo doesn't exist anywhere, but doesn't generate a live warning in the unit test project (it still fails on build).
This is a VS Code issue only. If I open it in Visual Studio 2022, it works just fine.
What's going on here?
Thanks to this answer on Twitter I found a way to fix it...
I had to restart OmniSharp (the C# extension for VS Code). It can be done in the command palette (Ctrl+Shift+P). Search for "OmniSharp" and select "OmniSharp: Restart OmniSharp".

There was an error running the selected code generator: 'Scaffolding failed. The path is empty. (Parameter 'path')' in VS 2022

Project type is asp.net MVC core. Adding a Razor View with or without Model I receive the following results:
There was an error running the selected code generator: 'Scaffolding failed. The path is empty. (Parameter 'path')'
Using VS2022 17.0.4 targeting .net 6.0 EntityFrameworkCore 6.0.1
I tried some of the remedies from the question that pops up on SO for VS2013:
cleaned out bin and obj folders and rebuilt
verified that all projects with EntityFrameWorkCore had the same version
BTW, adding a controller works.
Any help or guidance would be welcomed. This is a show stopper.
EDIT: I noticed that some or all of the projects in the solution were corrupted so I recreated project from scratch. I was able to add two views and then I received the message as above, again. Also, as I was building the project again I tested by adding a Razor view before I made any changes to the template generated project (asp.net core MVC) and it worked.
Something is corrupting one or more of my projects, and I think it might be NuGet. Any help would be greatly appreciated. I will now go rebuild the project from scratch for a third time and observe better and more frequently as to when the add Razor view fails.
I solved this issue by uninstalling the nuget package: Microsoft.AspNetCore.Identity
Reference
I got this error today while adding the Identity Scaffolded item to my existing Blazor server project.
I tried to add Identity Scaffolded item after updating the EF Core packages to 6.0.9 but unfortunately there seems to be some issue in the latest EF core packages.
So, I rolled back the EF Core packages from 6.0.9 to 6.0.8 and everything worked fine.
When I was recreating the solution from scratch I found the culprit. ME!
I do not like the new style of Main entry points where the code just starts without a namespace or class definition such as follows:
namespace MyNamespace
{
public static class MyClass
{
public static void Main(string[] args)
{
}
}
}
So I rewrote the class Program and created Startup and attempted to refactor all the code from Program. Obviously I did not do well. This caused my problem with the failed add of a templated Razor view.
download all packages the same version and cleaned up obj and bin file and rebuild your project. It worked for me
I was having the same issue and tried everything I could find to resolve it. - Made sure project would compile. Made sure all NuGet packages were the same version - 7.1. Looked for references to Microsoft.EntitiyFramework.Identity.
- No love.
Then I ran the latest Visual Studio updater to 17.4.3, I don't recall the version I as on, and we're good to go!

using dynamic keyword with Unity 3D [duplicate]

I am trying to implement GraphQL into Unity3D (version 2017.1.0f3 Personal). I am using .NET 4.6 (Experimental), but despite this, Unity does not support dynamic keyword. Which is odd, since .NET 4.0 it is the part of .NET. Except in Unity. I was googling for some solution how to get it work, but no solutions to the dynamic keyword. The error is this:
Severity Code Description Project File Line Suppression State
Error CS1980 Cannot define a class or member that utilizes 'dynamic'
because the compiler required type
'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you
missing a reference? skiing-prototype (1) D:\skiing-prototype
(1)\Assets\Scripts\GraphQL.cs 62 Active
That is the only caveat of using GraphQL C# client. Has anyone tried it yet to get it work? I hadn't found any greater efforts to get it up and running yet.
EDIT:
I am using this client here: https://github.com/bkniffler/graphql-net-client
Also this is an error from visual studio, but in Unity console it shows errors too, will update what exactly momentarily
Assets/Scripts/GraphQL.cs(80,16): error CS1980: Dynamic keyword requires
`System.Runtime.CompilerServices.DynamicAttribute' to be defined. Are you
missing System.Core.dll assembly reference?
this is the unity editor error, which seems to be the same that in visual studio
The first step is to check if Unity recognizes these 2 basic C# 6 features from MS site.
1.Try "Index Initializers" feature:
private Dictionary<int, string> webErrors = new Dictionary<int, string>
{
[404] = "Page not Found",
[302] = "Page moved, but left a forwarding address.",
[500] = "The web server can't come out to play today."
};
2. then "String Interpolation" feature:
private string FirstName = "";
private string LastName = "";
public string FullName => $"{FirstName} {LastName}";
If they give you error then the problem is not just the dynamic keyword but a problem that Visual Studio cannot recognize the .NET version being set by Unity.
From the comment section your Unity failed to compile the first example.
Go through the steps one by one for a possible fix. Do not skip of them.
1.Go to Edit --> Project Settings --> Player --> Other Settings --> Configuration --> Scripting Runtime Version --> Experimental (.Net 4.6 Equivalent).
2.Go to Edit --> Project Settings --> Player --> Other Settings --> Configuration --> Api Compatibility Level --> .NET 4.6
3.Restart Unity Editor and Visual Studio. You must restart both.
Test both C# features above. If they work then the dynamic keyword should as-well. If they don't then move on to #4.
4.Update Visual Studio. This is very important. Update the visual Studio to the latest version/patch.
5.If you can't still get both C#6 features above to compile then Re-install both Visual Studio and Unity then perform step #1 and #2 again as some files are missing.
6.Finally, if you get both C#6 features working but the dynamic keyword is still not working then update from Unity 2017.1 to Unity 2017.2. This version fixed many .NET issues.
Note that I am using Unity 2017.2 with the dynamic keyword without any issue. Also, GraphQL is working fine.
I seem to have found a solution
Navigate to Edit > Project Settings > Player > Other Settings > Configuration > API Compatibility Level and change from .NET Standard 2.0 to .NET 4.x
This immediately removed the compiler error and allowed me to run code using the dynamic keyword.
Let me know if that was useful

Project referencing Portable Class Library gives error in Visual Studio Code

I create a console application in Visual Studio 2015 RC and add Automapper 3.3.1 using nuget to the project.
If I then add the following snippet to my project:
public class Class1
{
public void Test()
{
AutoMapper.Mapper.Map<B>(new A());
}
}
And then open the same project in Visual Studio Code preview on Windows 10 then I get a red squiggly on the Map function.
The error message says:
The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'.
My project is configured to use .NET 4.52 and there are absolutely no errors or warnings when building the same project using visual studio 2015 RC or using MSBuild from the command line.
Automapper is portable class library and this is what seems to trigger the problem.
Is this a known issue with Visual Studio Code or Omnisharp?
Are there any way to suppress these error messages?
Update:
I have now tested with VS Code version 0.3 and it is still not fixed.
To make it even simpler to reproduce I have also verified that the problem also exist for a ClassLibrary project containing only the 3 classes: Class1 as shown and class A and class B, which are just two dummy classes used to have something to map.
It does not matter which version of Visual Studio is used to create the project. The same problem exist if I create the class library project using VS 2013.
Maybe you added the reference in both dnx451 and dnxcore50 in project.json file.
I think the problem is Automapper did not support .NET Core 5.0, please refer this article for more detail about .NET core 5.0 and .NET framework 4.6.
http://blogs.msdn.com/b/cesardelatorre/archive/2014/11/18/what-is-net-core-5-and-asp-net-5-within-net-2015-preview.aspx.
This might be the limitation of multi-environment in .NET Core 5.0 when using available libraries. You should write by yourself or waiting for other libraries update if you want to use, otherwise, please remove dnxcore50 in project.json.
Happy coding!
This is actually a known issue with the OmniSharp-roslyn server which powers VS Code, see: https://github.com/OmniSharp/omnisharp-roslyn/issues/265
I suspect you might have better luck using the yeoman ASP.NET 5 generator to generate an ASP.NET 5 Console application.
See: http://docs.asp.net/en/latest/client-side/yeoman.html
And http://docs.asp.net/en/latest/dnx/console.html

add-migration causing a "Could not load assembly" error

Here's what I am looking at
PM> Add-Migration AddedSubdivion -StartUpProjectName Data -Verbose
Using StartUp project 'Data'.
Using NuGet project 'Registry'.
Could not load assembly 'Registry'. (If you are using Code First Migrations inside
Visual Studio this can happen if the startUp project for your solution does not
reference the project that contains your migrations. You can either change the startUp
project for your solution or use the -StartUpProjectName parameter.)
I have no idea why it's trying to reference the Registry project. Registry depends on Data, not the other way around. I am very new to this, so I'd appreciate any help.
This is embarrassing, but maybe this will help out a googler in the future.
At the top of the "Package Manager Console" my default project was set to the wrong project. Changing that to my models project fixed it.
This can also be caused by a platform mismatch between .NET Core and your project. You get the error:
Could not load assembly 'DataProject'. Ensure it is referenced by the startup project 'ProgramProject'.
even though you have specified correct project and startup project names. (Either by using the drop down boxes in VS and the Package Manager Console, or by using the -project and -startupproject parameters.)
You can fix it by switching to Any CPU instead of x86, or vice-versa (or maybe to x64, etc.), but then you will have to switch back and forth every time you need to make changes to your model/DB.
As per this answer you can fix this by changing the order of your .NET Core path entries in system environment variables. If you're getting this error, then it means that either the first .NET Core path is for x64 but you're trying to make changes to your x86 project, or possibly other way around. Move the one you're targeting above the one you're not targeting, save, and then restart Visual Studio.
You can see which one is currently being used with the command dotnet --info.
(Note that this assumes you've installed both. You may also only have one of them installed, in which case you'd need to install the other one, and then check the order of the PATH entries; if the second one you installed is the one you want, then you will definitely need to change the PATH order to make it the one used by VS, since its entry should be at the bottom.)
The problem might not be so obvious if you have Package Manager Console docked with a narrow window...hiding the default project.
Its needs a wide docking.
If all fails there's always the verbose flag (-v).
A command like dotnet ef database update -v should help clarify the problem ef is facing.
In my case, the issue stemmed from EntityFramework finding it difficult to deal with the fact that my platform target was changed from AnyCPU to x86 or x64.
System.BadImageFormatException: Could not load file or assembly 'MyProject, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.
Temporarily changing the platform target to AnyCPU worked just fine.
Make sure that you are focused on:
1- Startup Projects is UI (MVC, API, ... etc).
2- Default project in package manager console is place of (ApplicationDbContext).
I would like to add, if you are using .net6 preview, you will need to update the packages.
so you will need to use the preview versions EntityFrameworkCore.Tools and EntityFrameworkCore.SqlServer (6.0.0-rc-1.21452.10 version as of today)
I had this exact problem, and it turned out because I createdthe project under a blank solution and then added the class libraies and web app seperately it didnt have a start up project.
None of these worked for me. I temporarily unloaded the unrelated project from the solution, ran the command, and then loaded the project back in.
I've got this issue migrating an Asp.Net 5 to Asp.Net 6.
The problema was in the .csproj file.
This configuration
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
I've just removed this property group and the dotnet ef worked
This can also be caused by a platform mismatch between .NET Core and
Also check this in your packages
if don't have that package Dependency Injection
Its very simple you have to install dependency injection package
The package manager window has a Default Project Property.
Setting the default project in the package manager window fixed this for me.
I also had to set the startup project to the same application in the solution explorer.
You should define 2 constructor and OnConfiguring method in context.cs. And also in your UI layer you should define connection string.
Like this:
In Context.cs :
public Context()
{
}
public Context(DbContextOptions<Context> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=..");
}
}
In appsetting.json:
"ConnectionStrings": {
"SqlServer": "Data Source=....."
}
In Program.cs:
builder.Services.AddDbContext<Context>(opt =>
{
opt.UseSqlServer(builder.Configuration.GetConnectionString("SqlServer"));
});
Set the target project for the migration as the startup project and continue