From many examples of compiling a Roslyn SyntaxTree, I have seen code such as:
[... create tree and compilation ...]
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("foo"), AssemblyBuilderAccess.RunAndCollect);
var module = assembly.DefineDynamicModule("foo");
var result = compilation.Emit(module);
But when I try to do this in the current Roslyn released with Visual Studio 2015 RC, I see no Emit() which takes a module. I need to write to a stream and load it into a regular AppDomain-locked Assembly.
I then see this answer from Tomas Matousek: https://stackoverflow.com/a/22977158
Where he says that this has been removed because it was "problematic".
I am having difficulty finding any other information about this on the Internet. Does anyone know if:
There is another way in Roslyn to compile into an assembly that can be garbage collected?
Or this will be supported in the final release of VS / Roslyn?
Where I should direct this question if nobody here knows (had trouble finding an official, active Roslyn forum)?
As svick and JoshVarty said in the comments, this is currently not possible. I also created an issue (https://github.com/dotnet/roslyn/issues/2621) for this that might or might not end up with some more information from the Microsoft team.
Related
I've encountered a problem in expression evaluator of visual studio 2015 that says "Internal error in the expression evaluator", after some investigations I found that this is caused by an assembly that is loaded using reflection. This assembly wouldn't throw any exceptions but after that, vs exp evaluator will fail.
This is not the only assembly that I load, there are some good working ones that don't influent the evaluator.
To overcome this issue I had to check 'Menu > options > debugging > Use Managed Compatibility Mode' but this disables the 'Edit & Continue' feature, what can I do?
Properties of the causer assembly:
its name is the same as the main assembly
(i changed its name but nothing happened)
all of my projects are using dotNet 4.5
all root namespaces are same
(all of the assemblies are so)
Thanks!
That sounds like a bug in the expression evaluator. For a better workaround, instead of checking "Use Managed Compatibility Mode", check "Use the legacy C# and VB expression evaluators". This should enable you to continue using Edit and Continue as well as other features added within the last few releases.
In terms of the "Internal error in expression evaluator", can you please open an issue by going to Help -> Send Feedback -> Report a problem? That will help us fix the problem in future releases.
Just extending on the solution provided by Patrick Nelson. For Visual Studio 2015+ as inquired, the steps are as follows.
If you're debugging at the moment, this option will be unavailable. Stop the debugger.
Go to Tools -> Options
and here under the Options select Debug -> General and scroll down to find the ...legacy C# expression.. option:
More information is provided here:
Switching to Managed Compatibility Mode
Note: There are also some serious drawbacks that occur from switching to the legacy mode. Especially Runtime Reflection of the implemented Interfaces becomes almost an impossibility or extremely inconvenient. There are also other Reflection methods which will throw errors.
I finally figured out what created this problem in my Visual Studio!
The quick fix is to delete the debug object favorites from the "Documents/Visual Studio xx/Visualizers" folder and restart Visual Studio.
When you "pin" a variable in the debugger, Visual Studio saves a 'favorite' json object for it.
It appears that there is a bug in Visual Studio which corrupts the 'favorite' for some child variables that are dynamic in nature (not exactly sure of the conditions though).
For me checking "Use Managed Compatibility Mode" option worked. I was also seeing question marks when hovering over variables, instead of properties and values
I resolved this issue by simply resetting my visual studio settings by going to: to Tools->Import and Export Settings and selecting to reset to default settings
I had the same issue with VS2019. I ended up deleting my Documents/Visual Studio 2019 folder. Hope this might help someone, one day. Cost me a day.
PS. Probably not required to delete all, and of course not your projects (if they're in there), but in my case, everything in there was autogenerated by VS.
I of course tried all solutions mentioned here, and even reinstalling VS didn't work. Refactoring the class to another name was the 'trigger' which made me think there must be some cache, despite cleaning symbols and such didnt work.
In my case I was trying to evaluate lambda expression on List<> and had such error ("Internal error in the expression evaluator"). I was using VS2015, so lambda expressions were allowed. It turns out expression evaluator was lacking of Linq library. I added
using System.Linq;
to my current class and voilà! Lambda evaluated.
I encountered the "internal error in the expression evaluator" error when I was debugging in release mode instead of in debug mode. I had changed it to Release when publishing to production and forgot to change it back to Debug.
Check your use of the [DebuggerBrowsable] attribute; I found a minimal case in VisualStudio 2017 15.5 and posted it here.
In this particular case, the expression evaluator (EE) crash appears related to the [DebuggerBrowsable] attribute applied to a property overriding a field of the same name. This will account for some percentage of the cases that people are experiencing out there, but there's no way of knowing how many are due to this specific issue until it gets fixed.
The full and complete demonstration example is shown in the image (and included below for good measure)
Machine-readable copy of the code in the image:
using System;
using System.Diagnostics;
class Program { static void Main() => new _derived(); }
abstract class _base
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Object trace;
};
class _derived : _base
{
public _derived() => Debugger.Break(); // <-- vs2017 EE crash when stopped here
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
new public Object trace => base.trace;
}
In my case, I had 2 same dll files in 2 different folders (seems, one dll was not correct). Deleting the .dll and rebuilding solution solved my issue.
In my case the data I was attempting to inspect was extremely large, a string which unexpectantly had hundreds of megabytes of data in it. The issue wasn't apparent when the amount of data being inspected was reasonable.
How can we access the complete visual studio solution from code analyzer in Roslyn?
I have been trying semantic analysis without much help.
var sol = ((Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions)context.Options)
.Workspace.CurrentSolution;
This is what I came up with using intellisense but this always gives a null value.
In general, you can't. Analyzers run as part of commandline builds in csc and vbc, which have no notion of Workspaces or Solutions.
We are considering adding a VS specific analyzer API that would allow access to the Solution, but for Roslyn's 1.0 release, there is no supported way to do so.
For the moment WorkspaceAnalyzerOptions is internal sealed. One can use context.Options with reflection. Hacky, but working.
Solution solution =
((HostWorkspaceServices)context
.Options
.GetType()
.GetRuntimeProperty("Services")
.GetValue(context.Options))
.Workspace
.CurrentSolution;
Note, along with it the compiler gives a warning:
RS1022 Change diagnostic analyzer type to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.Host.HostWorkspaceServices, Microsoft.CodeAnalysis.Solution, Microsoft.CodeAnalysis.Workspace'
When I try to install IronPython on Debian with Mono (3.12), I get the following error:
socket.cs(1900,63): error CS0117: `System.Net.Sockets.SocketOptionName' does not contain a definition for `IPv6Only'
How can I solve this problem? According to the IronPython website, everything should compile without errors.
In the Mono mailing list there is already such a bug, but there is no answer to this bug. Therefore I thought that maybe this forum is a better place for this question.
I'm no expert on either IronPython or Mono, but out of curiosity I just tried this.
For whatever reason, the IPV6Only value in the SocketOptionName enum appears to be missing in the Mono implementation. The error message you're getting is from the code in IronPython.Module/Socket.cs attempting to reference this. It turns out that this is already recognised in the codebase as a feature that not all platforms have, so there's an easy workaround:
The Common.proj project file in the Solutions/ directory in your git checkout defines a number of possible ReferencedPlatform values. The default value is V4. Just below there in the XML, find a block starting:
<PropertyGroup Condition="'$(ReferencedPlatform)' == 'V4'">
Nested in there is a Features element with a list of the features that apply, and if you find and delete FEATURE_IPV6 at the end of the list, then you should find that the project will build using make. I briefly tried firing up the ipy.exe that is generated and it seems to work.
Obviously this isn't a very good solution. Probably the best thing would be to file a bug report with the IronPython project. I guess that Mono on Linux is probably a fairly low priority for the guys who are working to maintain it.
Correct, up to mono 4.0 throws Protocol option not supported when setting IPv6Only false.
This is probably resolved here: https://github.com/mono/mono/blob/mono-4.2.0-branch/mono/metadata/socket-io.c#L536
But do note the compile flag IPV6_V6ONLY
I'm digging deeper into Entity Framework Templating and want to find out more about the GetSourceSchemaTypes routine, used here as an example
foreach (EntityType entity in GetSourceSchemaTypes<EntityType>().OrderBy(e => e.Name))
{
}
It appears to be part of the Microsoft.VisualStudio.TextTemplating namespace but I can't find that on MSDN.
I'm looking for something specific but the answer may be revealed in the definition of this routine.
thanks
GetSourceSchemaTypes (Microsoft.VisualStudio.TextTemplating namespace) can be found in the Microsoft.VisualStudio.TextTemplating assembly (Microsoft.VisualStudio.TextTemplating.dll) delivered with the Visual Studio SDK
You can use a .NET decompiler to have a look at the code.
ILSpy is free and works fine: http://ilspy.net/
If you have any difficulty to locate the Microsoft.VisualStudio.TextTemplating assembly, you can have a look at this question: Cannot find Microsoft.VisualStudio.TextTemplating assembly :)
For example, if you use Visual Studio 2012 the assembly may be here:
C:\Program Files (x86)\Microsoft Visual Studio
11.0\VSSDK\VisualStudioIntegration\Common\Assemblies\v4.0
PS: I don't understand why this answer is downvoted, there is nothing wrong with decompiling.. It's a nice tool to improve understanding of something..
I'm new to .NET C# programming. I'm following few books. It is said that instead of compiling C# code directly to machine code, it is converted into an intermediate language (called MSIL aka CIL). But when I compile, I get an exe/dll file.
Is this MSIL/CIL contained in these exe/dll files?
I want to see that intermediate language code, just to get feel for its existence. How do I view it?
They are calling this exe/dll file an assembly. Are they using this "fancy word" just to differentiate these from the exe/dll files that contain native/machine code?
Yes it is, more exactly in the .text section of the PE file (portable executable = *.exe or *.dll). More information can be found here.
The best choice is to use ILSpy (Reflector is no longer free). It's a free disassembler that can dissassemble your assembly into MSIL but also C#, VB (to some extent). The .NET Framework SDK contains ILDasm, which is the official MSIL dissasembler.
Basically yes. An assembly is a file that contains MSIL code and corresponding metadata. This is not restricted to PE files per se, but all current CLR implementations use them.
If I may recommend a good book on that matter too, it's Expert .NET 2.0 IL Assembler by Serge Lidin. He's the guy who designed MSIL.
One of my favorite ways to see IL for a snippet of C# is to use the free LINQPad tool. After entering some code and choosing "C# statements" at the top (or "C# Program", whichever suits), click the "IL" button under the code entry area, and you will see the generated IL.
Using LINQPad for this is much more convenient than loading up Visual Studio or running the compiler from the command line, then loading up ILDASM and opening the .il file with a text editor.
If you want it online, .NET Fiddle is excellent. Just paste your code and click View IL option at the top right.
Another option: Use ReSharper
Source / IL synced view: left blue background line corresponds with right IL Block
In Visual Studio:
Choose ReSharper | Windows | IL Viewer
or Context Menu: Navigate | IL Code
Supports synced view of Source Code and IL - when you click on a statement in source, the corresponding block in IL is highlighted (and vice versa). Displays descriptions for IL from Microsoft Developer Network and "Common Intermediate Language (CIL) instruction set" from ECMA standard specification.
see Viewing Intermediate Language (IL) in Resharper Help. Picture above is from Resharper Help.
Free option is to use Jetbrains dotPeek
see also: "Exploring Intermediate Language (IL) with ReSharper and dotPeek", by Maarten Balliauw, January 19, 2017 - Jetbrains Blog
sharplab is an online tool, great for simple use cases. Type your code on the left, IL shows up on the right.
I believe that they are called "assemblies" because an assembly is a set of modules, assembled together by a manifest.
(source: microsoft.com)
See Assembly Contents for details.
Yes it is in assembly.
You need .NET Reflector or ILDasm.
More details on assembly check HERE.
P.S As you are following some books I will highly recommend you CLR via C#.
In many respects, .NET assemblies are similar to Java bytecode packages.
Yes. They also contain manifests and other data, but the CIL is part of the exe/dll.
Use ILDasm or Reflector - most people would say Reflector, as it is much more powerful. Both will show you what CIL was produced. Wikipedia has a list of all CIL instructions, for a better feel (it is assembly like).
I guess it is meant as an assembly of code. A good way to differentiate it from native.
I know this is an old question, and I'd prefer any of the tools above. However, in a pinch, there has been an MSIL viewer in the box with Visual Studio since at least Version 2005.
The tool is named ildasm.exe, and is located in the following folders after default Visual Studio installations:
Visual Studio 2005
"C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin\ildasm.exe"
Visual Studio 2008
"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ildasm.exe"
Visual Studio 2010
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\ildasm.exe"
For more information, see: "How to: View Assembly Contents" in the MSDN Library.
I have just spent a couple of hours searching for the best tool that could let me view the IL code directly inside Visual Studio.
The only solution I found so far is Msiler https://visualstudiogallery.msdn.microsoft.com/60fc53d4-e414-461b-a27c-3d5d2a53f637
it works quite well!
Otherwise the second best solution, but without visual studio integration, is JetBrains dotPeek, which is quite awesome to be honest.
From my experience the best source of IL-related knowledge is Andrew Troelsen “Pro C# and .NET Platform”. Starting from 3rd edition he has really, really outstanding chapter (approx 50 pages) on how to understand IL and even write your own code and use ILAsm. I’ve employed that information to investigate whether multiple inheritance exists in .NET world. Also you could try to employ some very interesting features in IL (e.g. filtering of exceptions which only exists in VB but not in C#).
I highly recommend to read that chapter.
Eventually, .NET Reflector is an enterprise standard for investigating IL code of assemblies and Richter's book is definitely "must read" stuff. But from other books like mentioned above you could reveal really useful things :)
Yes, each assembly in .NET world holds some IL code (alongsite with manifest) which could be viewed thru Reflector or ILDasm. Even more, Reflector could show you C# and VB optimized code. This means that any person could view the source code of an assembly and that's why in commercial products obfuscators are used.
I you want to view the intermediate language, Try downloading JustDecompile from Telerik (Which is currently free, requires a sign up though).
Drag in your DLL and choose IL from the drop down box at the top!
There is now another option. You can do this in VS Code with this extension built with Roslyn. This is currently limited to .NET Core.