How I can get c# version from my code on run time? I use .net core. For example I can get framework version with this code:
FrameworkName = Assembly
.GetEntryAssembly()?
.GetCustomAttribute<TargetFrameworkAttribute>()?
.FrameworkName
And I need something similar for C# version.
There is no such thing. The language version is completely lost in the compilation process, as the end result is just compiled IL code.
The fact that you used C# 6 or C# 7 or Visual Basic.NET is not retained in any form in the runtime program, and is only used to emit code.
Related
Has anyone managed to find a workaround/way to dynamically compile a file, or files, or text, into a .dll in .Net Core (2.1)?
var csProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerResults compilerResults = csProvider.CompileAssemblyFromFile(options, files);
results in a PlatformNotSupportedException and it seems CodeDom is only of very limited use in .Net Core. See similar complaint and compare view of System.CodeDom.Compiler in .Net Core 2.1 vs .Net Framework 4.7.2.
We need to be able to write and dynamically compile custom code on-site. I have a way of dynamically loading any resultant .dll, but I just need to be able to get that .dll in the first place.
The only workaround I can see at the moment is to create a .Net Framework api/service to do this. Is the only other solution here to give up on .Net Core and go to .Net Framework?
Note: I wanted to do this dynamically within the code base. So the solution for "Is it possible to compile a single C# code file with .net core Roslyn compiler?" is not relevant as it states: "To invoke Roslyn compiler directly it is necessary to use command line driver" which would have set me on completely the wrong path. However "How to compile a C# file with Roslyn programmatically?" would provide the solution if I'd known that that is what I was looking to do.
The link provided by #Sami Kahmonem to Joel Martinez' solution in .Net Core 1 was what I used to solve this problem.
There are two options for you.
Use the Roslyn Scripting API (Microsoft.CodeAnalysis.CSharp.Scripting). This is pretty easy and surprisingly fast. Also you do not write any binaries to the file system.
Use the full compiler to create a DLL and load it. I would not recommend doing this if possible.
For detailed explanations you should look at this question: Compiling and Running code at runtime in .Net Core 1.0 (you do not need to create a NuGet.config or anything like this)
I found following on a ASP.NET book. I am learning and curious about following content.
The second major advantage of an IL architecture is that it enables the Framework to be language neutral. To a large degree, language choice is no longer dictated by the capabilities of none language over another but rather by their preferences of the developer or the tam. You can even mix language in a single applications. A class written in C# can be derived from a VB2005 class, and an exception thrown in a C# method van be caught in a VB#005 method.
My question is , does ASP.NET use same compiler to compile VB.net and C#?
Update: (Another query)
Can C# compiler compile a VB.Net code ?
They have separate compilers (csc.exe for C# and vbc.exe for VB.Net) but they both get compiled into IL and then at run-time JIT compiles it into machine code.
Question 1 : can C# compiler compile VB.net code?
Answer 1: No it can't and you will see that in the below example. It gives an error if you try to do that as it looks for C# syntax.
Question 2: I think that's what they say in the book. Since it is two compilers, I feel it is not compatible
Answer 2: It doesn't say that you can compile VB code using C# but it says that you can mix languages in a single application like I did in the example below and still able to compile C# and VB (using their compilers).
See below example to understand how it works. I created a solution with a C# project with a C# class and a VB project with a VB class. You should not mix C# and VB classes in same project as it will ignore the vb file if its a C# project during build.
Content of ClassCSharp.cs:
namespace ClassLibraryCSharp
{
public abstract class ClassCSharp
{
public int MyProperty { get; set; }
protected abstract void Test();
}
}
Content of ClassVBInCSharp.vb in C# ClassLibrary. See how I can inherit from a C# class and also access its properties and override the method.
Namespace ClassLibraryVB
Public Class ClassVBInCSharp
Inherits ClassCSharp
Property Test2 As Integer
Protected Overrides Sub Test()
Test2 = MyBase.MyProperty
End Sub
End Class
End Namespace
See below commands I ran:
vbc.exe /reference:"ClassLibraryCSharp.dll" /target:library /out:"ClassLibraryCSharpVbVersion.dll" "ClassVBInCSharp.vb"
Microsoft (R) Visual Basic Compiler version 12.0.20806.33440
Copyright (c) Microsoft Corporation. All rights reserved.
See above VB Compiler is used to compile vb class.
csc.exe /reference:"ClassLibraryCSharp.dll" /target:library /out:"ClassLibraryCSharpVersion.dll" "ClassVBInCSharp.vb"
Microsoft (R) Visual C# Compiler version 4.0.30319.33440 for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
ClassLibrary1\ClassVBInCSharp.vb(1,1): error CS
0116: A namespace cannot directly contain members such as fields or methods
See above if I try to use C# Compiler to compile vb class it throws an error as its looking for C# syntax.
ASP.Net is a server-side Web application framework designed for Web development to produce dynamic Web pages.
What you are confused is about the compilation of languages, now, C# and VB.Net has it's own compilers. ASP.Net is a framework that could be achieved using languages like C# and all.
So do not get confused with language compilers. Each language will have their respective compilers that will convert the source code to a Intermediate language (IL) code that the Common Language Runtime (CLR) can understand. So a web framework like ASP.net is a framework that provides a mechanism to process the HTTPRequest and HTTPResponse. Now the language compilers will do their part of work of compiling respective programming language to IL code.
From MSDN:
ASP.NET is a unified Web development model that includes the services
necessary for you to build enterprise-class Web applications with a
minimum of coding. ASP.NET is part of the .NET Framework, and when
coding ASP.NET applications you have access to classes in the .NET
Framework. You can code your applications in any language compatible
with the common language runtime (CLR), including Microsoft Visual
Basic and C#. These languages enable you to develop ASP.NET
applications that benefit from the common language runtime, type
safety, inheritance, and so on.
Update:
Now answering the second doubt that you posted in the commenting section of your question. (Can C# compiler compile VB code)
Actually you cannot. Let us consider C# compiler, what any compiler like C# or VB know's is that you have certain code written in front of you and you need to understand the code and provide an equivalent IL code in this case. This means, a C# compiler has to work with code that has syntax of C# and a VB compiler has to work with code that has syntax of VB. You see a compiler basically needs to know what it is compiling (processing). Now consider some language X has a X compiler, now the compiler will be written in order to just crack and decode the language X.
Now, this does not stop you from writing VB code that talks to C# code or vice versa. That interoperability. See more.
C# and VB.Net are different languages. They have different programs (executables) which are the actual compilers. These compilers compile the high-level code to IL which is what the CLR understands and executes.
The compiler program can either generate an exe or a dll. For asp.net applications the program makes a dll always.
The below link would help you get familiar with the c# compiler command line program:
http://msdn.microsoft.com/en-us/library/2fdbz5xd.aspx
Update:
Q. Can a C# compiler compile vb code?
The answer is: No.
However, for an asp.net website there is a possiblity of having both c# and vb code in a single project. Take a look at the following link to know how that is done:
http://timheuer.com/blog/archive/2007/02/28/14002.aspx
Update:
why it says "multiple code files only works inherently (along with codeSubDirectories)
with the web site model" ?
That was the intent of the website model projects: http://msdn.microsoft.com/en-us/library/dd547590(v=vs.110).aspx#scenarios
There is a compiler for C# (CSC.Exe) and one for VB.NET (Vbc.exe). These compilers do not generate machine code but compile the respective language to intermediate language (IL). When executing the program (or running the website) on a computer, IL is interpreted and converted into machine code that is executed on the processor.
The compilers that ASP.NET uses are the same that are also used for other .NET programs, e.g. Windows applications.
I know that Java code is compiled into byte-code, that is executed by the JVM.
What is the case with C# ? I have noticed that applications written in C# have the .exe extension what would suggest they are native machine instructions. but is it really so ?
No.
Like Java, C# is compiled to an intermediary language (called MSIL or CIL).
Unlike Java, the IL is stored in EXE files which have enough actual EXE code to show a dialog box asking users to install .Net.
C# compilation is done in these two steps :
1. Conversion from C# to CIL by the C# compiler
2. Conversion from CIL to instructions that the processor can execute.
A component (just in time) performs this compilation at run time from CIL to machine code
What that .exe is supposed to tell you is that the file is executable. C# is compiled into bytecode, just as java is, but .NET wraps this in a CLR executable.
Look here for a more in depth look at CLR executable http://etutorials.org/Programming/.NET+Framework+Essentials/Chapter+2.+The+Common+Language+Runtime/2.2+CLR+Executables/
c# code is compiled to MSIL. it likes java bytecode. msil will be convert to machine isntrctions at runtime.
C# code is compiled to MSIL, MSIL is taken care by .NET CLR
There is also a project that allows compilation of C# to standalone binary executables: CoreRT
I want to make use of .net dlls in node.js. Does that mean I need to make those dlls available with c/c++ using 'clr hosting', a la
.NET Framework 4 Hosting Interfaces or
Hosting the Common Language Runtime
Unfortunately the example Creating a nodejs native .Net extension over at github was a bit of a disappointment, just scroll down to the last step
Change the "Common Language Runtime Support" option to No Common Language RunTime Support
and you know what I mean. Correction to do that article justice: It suggests to change that option to "No Common Language RunTime Support" only for the file SharpAddon.cpp, so other .cpp-files you add will have CLR support enabled (the default for a CLR project), which means you can in fact use .net dlls from those other .cpp files.
This question is actually a duplicate of Using a .NET DLL in Node.js / serverside javascript, which was written at a time when there was not even a native Windows port of node, so times might have changed, although google makes me doubt it.
Update: node-gyp can do the manual steps below automatically when the binding.gyp file is setup properly. See this answer for this simplified procedure.
It turned out to be rather easy. After struggling with CLR hosting and getting data in and out of the host for a while, it turns out you can actually enable /clr for your node extension no problem (so far). Here's how:
follow the instructions on http://nodejs.org/api/addons.html to generate the project files
open the generated .sln in Visual Studio (I'm on VS 2010) and enable /clr in the project settings
now it probably won't build and you have to let the - in this case actually quite helpful - error messages guide you to the flags that conflict with /clr
The flags that I had to change to make it work:
disable /EHsc (C++ exceptions)
disable /RTC1 and /RTCsu
Release: change /MT to /MD
Debug: change /MTd to /MDd
Release: change /GR- to /GR
Then you can mix managed and unmanaged code like this, referencing your .net dlls.
#pragma managed
#using <managed.dll>
void callManaged()
{
managed::Class1^ c1 = gcnew managed::Class1();
System::String^ result = c1->Echo("hola");
System::Console::WriteLine("It works: " + result);
}
#pragma unmanaged
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
callManaged();
return scope.Close(String::New("world"));
}
Update Just discovered this link with an easy howto: http://joseoncode.com/2012/04/10/writing-your-first-native-module-for-node-dot-js-on-windows/
Sounds like edge.js is the new answer from the author of iisnode:
Edge.js supports using C# and .NET instead of writing native node.js extensions
These days, there's cmake-js and node-addon-api that make things both easier, plus the ABI of node-addon-api means the module does not need to be recompiled when used with a newer version of Node.js.
See this answer for a short tutorial: https://stackoverflow.com/a/54339042/709537
Im working on creating a feature in a website, where people cah write C# code in the input box , and it can be compiled and results emitted.
Any resources or suggestions as to how to start with this.
The .Net framework has built in runtime compilers. They are in the System.CodeDom.Compiler namespace.
The other thing to consider is when you are compiling the code what assemblies you link in. If you link in an assembly the code you compile will have full access to that assembly and it will be compiled and running on your server.
Code compiled should be done in a sandbox. You can interface with the compiler through the command line.
http://msdn.microsoft.com/en-us/library/1700bbwd(v=vs.71).aspx
I'm using Microsoft.Build and Microsoft.Build.Framework in my online .Net IDE, Chpokk. Soon, Roslyn will be the way to go (I'm currently using it for Intellisense).