Use the dynamic keyword/.NET 4.6 feature in Unity - c#

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

Related

error CS1644: Feature `null propagating operator' cannot be used because it is not part of the C# 4.0 language specification

I have Unity 2018.1.9f2 and I downloaded the Unity ml agents and added the folder to my unity project. But When I try to run the '3DBall' scene I get this error in the console:
Assets/ml-agents-master/UnitySDK/Assets/ML-Agents/Scripts/Brain.cs(79,25): error CS1644: Feature null propagating operator' cannot be used because it is not part of the C# 4.0 language specification. When I double click it then it opens the VS and brainBatcher?.SendBrainInfo(name, agentInfos); is underlined.
and when I hover over the code it says Feature 'null propagating operator' is not available in C# 4. Please use language version 6 or greater.
I tried to follow the answer from anther similar question: Unity Visual Studio C# version synchronization. So I used unity-c-5.0-and-6.0-integration and that error was not displayed but I got 150+ other errors.
Any help will be much appreciated.
Make sure your Player Settings / Scripting Runtime Version is set to .NET 4.x not .NET 3.5
Why not just remove the ?
In my case, the following change fixes the build even using .net 3.5 framework
Action<DeleteObjectsResponse, string> result;
// Change:
//result?.Invoke(null, responseObj.Exception.ToString());
// To:
if (result != null)
result.Invoke(null, responseObj.Exception.ToString());

dynamic in android xamarin

i have seen in the link below:
Can execute Code Dynamically in monotouch?
that it is impossible to use dynamic in ios xamarin. how about in Andoid xamarin?
I tried to do the following:
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
However, when I want to access MyDinamic.A, it says that Unknown Member: A.
Can someone please help? Thanks.
Edit:I also have added the Microsoft.Csharp dll in the solution reference as per the screenshot:
I'm not sure which IDE did you use for developing your xamarin android app, by my side I used VS2015, and the error is
Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
This is because when use the dynamic keyword in your project. The assembly contains the C# runtime binder. To solve this issue, we need to add reference to Microsoft.CSharp library(Microsoft.CSharp.dll) in our project:
After adding this reference, your code runs well by my side.
But I'm not sure if the Xamarin.Android will limit the use of dynamic object, through I didn't find any limitation in xamarin's official document. For more information about dynamic object, you can refer to:
System.Dynamic.DynamicObject Class
System.Dynamic.ExpandoObject Class
Go to NuGet Package Manager > Manage NuGet packages menu. Then change Source to Microsoft Visual Studio Offline Packages. After adding, it should compile successfully.

CSharpAddImportCodeFixProvider encountered an error and has been disabled

I had my PC re-imaged for me. I have Visual Studio Version 14.0.25123.00 Update 2 installed on my computer. I'm getting this error when I try to use VS intellisense to reference another project.
CSharpAddImportCodeFixProvider encountered an error and has been disabled
I have two projects. One of them using namespace ProjectName.Web. And the other project using ProjectName.Web.Controllers. The provider crashes when I reference ProjectName.Web.Controllers, I believe because it is setup as a project. Any idea how to fix this?
I had the same issue on VS-2015 update 3.
I did was :
1) Closing visual studio
2) restarting as administrator
Happened to me when chose Add using System.Data.SqlClient automatically after typing using (SqlConnection...){} in DataLayer, in one of Repository classes.
Nothing helped (except creating new project), but I saw that the problem was with loading System.Data.SqlClient.dll file, although it existed in appropriate folder.
Found by trial and error that after removing Dependencies->Assemblies->System.Data.SqlClient from DataLayer (right click -> Remove, or just press Delete key when selected), I can Add System.Data.SqlClient without any errors.
Didn't try for other cases where CSharpAddImportCodeFixProvider encountered an error and has been disabled message appears, but the solution might be similar.
In my case the problem appeared probably due to .net Core version conflict or something like that, because the project was on external drive and created on another computer.
Edit: Also, some errors might be caused by .vs folder (hidden by default) inside Solution folder, especially if the project is moved between different computers. I know from experience that IntelliSense can seem to be broken and classes from other namespace would be unavailable although using namespace_name statement is present. The solution is to delete .vs folder or just avoid copying it with the project, as suggested here: https://weblog.west-wind.com/posts/2018/Aug/07/Fixing-Visual-Studio-Intellisense-Errors
There may be multiple reasons why this error occurs. So this answer may not apply to all situations, though it seems that it only occurs when another project is referenced.
The error does not occur for all statements. In my case I had the following code:
private System.Threading.Timer Timer;
public void Start()
{
Timer.Change(0, 60000);
}
As soon as intellisense would open for Timer.Change( the error occurred. Please note that I had no parameters at that point. If valid parameters are present there will be no error.
I could solve the issue by updating the version of the framework. I found out that both projects targetted different frameworks, resp. 4.5.2 and 4.6.
As long as the framework versions are different the error occurs. As soon as both are equal (either 4.5.2 or 4.6) the error no longer shows.
I have tested this with VisualStudioVersion = 14.0.25420.1 (Visual Studio Community 2015).
-- update --
I've reported this as a bug to Microsoft. Including steps to reproduce.
I end up with this same error.
what i did was to manually go and find the nuget packet for System.Data.SqlClient, installed and then invoke it in the class i was working on, like:
using System.Data.SqlClient;
Dont know if this is some kind of bug, cause it happens on a new blank project i create using visual studio 2019 community
hope it helps someone
Had the same problem solved by installing the sqlClient package from nuget package manager
right-click on the project choose manage nuget packages.. and go to browse tab and search for System.Data.SqlClient and install it. that easy :)
Judging from the label you were given, "CSharpAddImportCodeFixProvider", I'd guess your problem was due to Visual Studio trying to identify and/or correct a missing "using" statement at the top of your C# source code file in which you made reference to a class that needed it. The Visual Studio components that usually deal with this type of problem are Intellisense, or third-party syntax highlighting/correction plugins like JetBrains' ReSharper.
On second thought, I'm not quite sure it's Intellisense's fault as opposed to the plugin ReSharper's. That's to be determined.
I did file a similar bug report with Microsoft. The error in my case seemed to be a result of the Intellisense not knowing how to deal with a logic error in my own code (see https://connect.microsoft.com/VisualStudio/feedback/details/3133049).
In my case, I had inadvertently placed code for a method outside its class definition, though inside its similarly named namespace. Visual Studio 2015 Update 3 complained,
'GenerateVariableCodeFixProvider' encountered an error and has been
disabled.
The fix was to move my method back into its corresponding class definition, but it definitely brought a Visual Studio bug up to the surface.
Specifically, Visual Studio Intellisense had seen the line of code,
Response.Write("I did something");
placed in a method that was declared outside a class definition (i.e., inside a namespace, but inadvertently not inside its class). The "'FeatureLabel' encountered an error and has been disabled" error was then displayed in a yellow bar across the top of my editor window and an "Enable" button and an "Enable and ignore future errors" button were displayed next to it.
I believe that Intellisense (or ReSharper?) tried to automatically deal with the situation and attempted to generate a variable for the keyword, "Response", but it tripped trying to do so--which in turn caused the error that was displayed.
anyone trying this solution from here ?
https://developercommunity.visualstudio.com/content/problem/623872/add-import-not-working.html
the last reply solves my issue..
Tools > Options > Text Editor > C# > Advanced
turning off Suggest usings for types in NuGet packages

How do I enable C# scripting in VS 2015?

How do I configure VS 2015 to enable Roslyn's C# scripting capabilities?
I've tried installing various Nuget packages, including both the 1.0 and 1.1.0-beta1 versions of Microsoft.CodeAnalysis.CSharp, Microsoft.CodeAnalysis.Scripting.CSharp, etc., but I can't get any of the examples I've found online to work. I am getting "type not found" errors, i.e.,
var scriptEngine = new ScriptEngine();
... fails because the type "ScriptEngine" is not found.
Can someone provide as recipe that includes which nuget packages to install, which using statements are required, etc., to implement Roslyn scripting?
UPDATE #1:
I have made some progress, but still having issues. I get a bunch of compiler warnings and then a TypeInitilizationException which is apparently due to a component version mismatch.
I'm now using the following example code (taken from a test), and there's no missing types:
using System;
using Microsoft.CodeAnalysis.Scripting.CSharp;
namespace RoslynScriptingTest {
class Program {
static void Main(string[] args) {
var script = CSharpScript.Create("1 + 2");
var fn = script.CreateDelegate();
var value = fn();
Console.WriteLine("value={0}", value.ToString());
}
}
}
I've loaded all of the nightly packages that are available at https://www.myget.org/F/roslyn-nightly/.
I get a series of build warnings that refer to Microsoft.CodeAnalysis, v1.1.0.0.
Running the exe despite the warnings yields the TypeInitilizationException mentioned above. Based on the stacktrace, the TypeInitializationError is caused by a version mismatch for System.Reflection.Metadata.dll.
I am not sure where to go from here. I don't understand how the scripting-related packages/components fit together. I saw some posts from earlier this year that describe building Roslyn completely. I have not done that. Is that necessary?
This is reminding me of DLL hell from the old days.
The scripting APIs are still in progress, and were removed from the release packages.
Try the nightlies instead.
With visual studio 2015 update1 the REPL is back and scripting api's are enabled.
Here is what Microsoft says about it:
In this release, the C# Interactive Window is back in Visual Studio, as well as the command-line C# REPL window. (The Interactive Window is the REPL window inside Visual Studio.)
We've also released scripting APIs that enable you to build and run C# as a script. The scripting APIs are available on GitHub.
Additionally, we've released csi.exe, which is a tool that you can use to run a C# script file (.csx) from the Developer Command Prompt. For example, simply type csi myScript.csx to run your script file. Or, you can enter the command-line REPL mode to interactively evaluate snippets of C# code. To get to this mode, run the command csi without any arguments from the Developer Command Prompt.
Reference:
https://www.visualstudio.com/news/vs2015-update1-vs#Csharp

How to use XDocument class in Mono

I'm trying to use XDocument class inside a Unity3D project on Windows 7.
I did the following:
added the reference System.Xml.Linq to the Mono project.
included the namespace:
using System.Xml.Linq;
set the target framework to: Mono/.NET 3.5
clean and rebuild the project
But still Unity3D complains about it. Here's the error output in the console:
Assets/Scripts/Editor/RoadManager/RoadManager.cs(3,18): error CS0234:
The type or namespace name `Linq' does not exist in the namespace
`System.Xml'. Are you missing an assembly reference?
Any idea?
This has been discussed many times before, but few of these answers are complete.
As has been said before, Unity3d only supports up to .NET version 2.0, and it seems System.Xml.Linq was introduced in .NET 3.5, besides the fact that it is not listed on the Unity3d compatibility list anywhere.
The only things to try are to set the Mono API compatibility level to 2.0 (Menu: Edit > Project Settings > Player and look in the Other Settings panel), but it seems that that was a mistaken solution for Linq2SQL.
Another possible solution is to add the DLL yourself into the Unity Editor as shown:
Try dragging the C:\Program Files
(x86)\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.Linq.dll file
into the unity project window like you would a texture or other game
asset.
If none of these yield ANY luck for you, then I'm afraid you are out of luck.
Unity3D supports .Net 2.0 only, so setting compatibility to .net 3.5 in MonoDevelop/Visual Studio will not work. You will have to make do without the class. This shows what library classes are available:
http://docs.unity3d.com/Documentation/ScriptReference/MonoCompatibility.html
See also this post in UnityAnswers: http://answers.unity3d.com/questions/46039/can-not-reference-systemxmllinq.html

Categories

Resources