Basicly, I want to create code that I can compile from a STRING that I will be loading from a file.
Is that even possible?
I did my research and I couldn't find any answers.
Reading your follow-up comment, it sounds like what you would be looking for would be a scripting language rather than compiling C# code dynamically. A scripting language allows you to pass in and execute code as a string, while also allowing to tie in your current execution to that code. For instance, you can pass in the character's current health to the scripting language, and then read back the character's current state (dead? immune? etc). The two most popular languages to do scripting for games are Lua and Python. Both of these languages have .NET libraries/bindings to allow them to be used within C#.
It has been a bit of time since I have set up my own project in C# with Lua, but I believe this tutorial looks very similar to what I was using, and therefore how I answered my question (ie, being able to closely bind them). However, searching Google for "lua C# binding" or "python .NET binding" will give you lots of libraries and tutorials. Which one you ultimately decide upon really comes down to which of those two languages (though there are bound to be many other scripting languages out there as well) you feel more comfortable with using.
I suppose, as EZI said above, it would be possible to compile C# code dynamically. But from your question, it sounds like you'd be looking for a scripting language instead.
Related
Environment
Windows 8.1 64bit
Microsoft Visual Studio
C#
What I'm trying to do
To implement a mini language in C#
My job in my company is to make a software which automates evaluation of the performance of company products. The evaluation involves opening valves, flowing chemicals, fetching signals from sensors, calculating some values, etc...
The issue is when a user wants to change the procedure and parameters like how long the reaction time is, the order of opening valves, whether reaction conduit is flushed out or not, the programmer has to change the source code and build another software every time the user requires it.
So I'm trying to implement a mini language in C#. A user can organize a procedure of measurement with the easy-to-understand language. The user writes a code in a txt file, my software reads it, parse each line of code, extract commands and parameters, call corresponding method in the software.
For example, a user writes a line of code like open_valve(3), my software reads the code and call an internal method send_commands_to_ADconverter(VALVE, 3) which sends appropriate commands to a target valve via an A/D converter connected to the computer. This is my conception.
However, due to lack of my programming skill, I have no idea where to start. What technology is available? What are the keywords to achieve the goal? How can I achieve this objective? Any help would be appreciated. Thanks.
Edit 1
c# - Adding scripting functionality to .NET applications - Stack Overflow doesn't refer to accessing external devices like sensors, valves via A/D converter which is crucial for my purpose, so it is unclear this is a duplicate question of the link above.
In order to create a language you need a "parser" of some sort. You will need to define a "grammar". Parsing your "progam" via the grammar will result in a structure that you can then call methods in your code that implement each feature of your language.
You are on a big learning curve here :) lots of strange things like EBNF. You will probably see lots of references to things like Gold and ANTLR. These are hugely capable but involve things like "compiler compilers" and add a level of complexity that can be confusing and require extra steps in you build pipeline.
Here are a couple of libraries I've used that allow you to define you grammar in c#.
https://github.com/picoe/Eto.Parse
https://irony.codeplex.com/
Irony is very good (I've used it for various projects) but hasn't been maintained for a while.
Eto.Parse is more recent. It also has built in parsers that allow you to create a Grammer by parsing BNF. This is very cool
If I understand, your goal is to parse a syntax written by your user and take a decision with what he typed.
I suggest you to use regular expression to match and split the user input.
There are several scripting languages which can be run directly from C#.
As your users doesn't seem to have programming knowledge it might help to use a verbose language like VBScript.
To run VBScript you can use the Scripting Control. See this question for samples: Use Microsoft Scripting Control to evaluate 'If' expressions (via c#)
IIRC the script control must be run as a 32bit application.
Well, the easiest option would be to use what you already have - C#.
You can compile C# code on the fly, and it's very easy and cheap with the new compiler, Roslyn. Then all you need to do is define your interface so that it's easy to use for the users, and put that code in a method you can call from your code. This allows you to easily support all the various development tools for C# as well, including Visual Studio/VS Code. In the simplest form, all you need to do is make your "script" implement some base class that has all the methods you want the users to have - there's certainly better approaches, but this one is very simple, which sounds like something you're looking for.
Of course, this only makes sense if you can trust your users. Making safely sand-boxed code in C# is a lot more complicated (though certainly possible), and you'd probably be better off using some ready scripting solution.
I am starting with game dev using Unity3d and I can see there's 3 supported languages for creating scripts: C#, unityscript and Boo...
although, coming from a web-design past I am obviously used with javascript, but after few attempts I could notice Unity3d doesn't really have full support to the script language and some elements like new Date().valueOf() and some other statements within methods such as the attribute arguments and many other won't work properly, also it seems my file can't have a wrapper method that envolves all the other methods like:
(function (scope) {
function Start() {
...
}
...
}(this));
and when using something like new Date().valueOf() which is valid in JS I get:
MissingMethodException: Method not found: 'System.DateTime.valueOf'. Boo.Lang.Runtime.DynamicDispatching.MethodDispatcherFactory.ProduceExtensionDispatcher ()
So perhaps the compiler turns that initial 'unityscript' code into Boo language? so perhaps Boo is the right 'native' choice and maybe unityscript itself isn't the best way to go when developing unity3d apps?
I was thinking on a language that has full support to all known native classes and methods which will work without problem?
Sorry for any errors mentioned above and please let me know what you think.
Unity doesn't use 'real' Javascript per se. See:
http://forum.unity3d.com/threads/1117-Javascript-Version
UnityScript is based on javascript 2.0. There are a few things missing (switch statements, etc.), but they get half the speed of C++, which is way faster than Mozilla.
Once you get used to it, developing in 'JS' for unity is very very fast and flexible...but of course, if you're going to develop native components, or interface to anything in C, you'll need to use C# (in the end, C# is not difficult to learn).
If you want to be a developer in Unity and build a career on it, learn C# and use it - don't waste your time with UnityScript. You can use C# outside of Unity for programming. If your main career is already web development (or will be), then continue using javascript because ultimately C# and UnityScript have the same functionality but C# is much more widely used for programing games and applications.
The majority of the assets on the store that I have used are C# or offer both JS and C#. Mixing between the languages creates serious dependency problems because in order to use a class in either language it has to already have been processed by the Unity script loading order. To use a Javascript defined class in C#, that script file must have been processed prior to the C# script file. If the javscript class then later needs something from the C# class, you would have to find ways around it because its simply no longer possible from the javascript file. Unity has ways to define the script order.
I thought that I would warn you about mixing C# with UnityScript because if you don't focus on one or the other, you will run into this problem. Ultimately, C# is the middle ground between ambiguous languages like VB and JavaScript, and pedantic languages like C++ (I have a C/C++ background of about 10 years).
Your title "What is the best xxx" leads to opinionated answers, but I am trying to give the best advice possible without being subjective. C# will allow you to continue, even if Unity were to go away a year from now. UnityScript/JavaScript would only allow you to move into being a web developer. A C# developer can easily move into UnityScript/JavaScript, but the reverse is much harder (not impossible, just more difficult).
You should use c#. It is popular, mature, native to .NET. c# is what big teams use. Learning c# will be useful in the future. JS in Unity3D is not real JS as already mentioned and nobody heard of Boo.
JS is the most popular language for use with Unity. But the language is implemented in Mono, and so any restrictions in that implementation are going to affect Unity scripts too.
I don't know how the Mono implementation of JS works, but judging from the error message, it uses datatypes initially defined for Boo, at least. However, that doesn't mean that JS is "turned into Boo". Both are compiled into the same bytecode, which is JIT'ed and run by the Mono runtime. So neither language is "more native" than the other.
Checkout advantages and disadvantages of using c# and Java script from here.
C# is little bit faster than JavaScript and you get extra features provided by C#. You can get peoples opinion from here.
Developing with c# has advantage of Visual Studio 2010. It provides better code completion feature than Mono develop.
In JavaScript only, variables can have an unspecified type. This only occurs if you do not assign a value while declaring the variable.
Performance is slower with dynamically typed variables, and you can run into casting problems. Iif this is a concern, use #pragma strict.
I'm doing a POC (Proof of concept) for a little open source project, to integrate Lua into c# looks pretty straight forward, but for this project we want to go a little further. We want to be able to edit Lua scripts from within our C# program (WPF client but we can go for winforms if that what it takes), the IDE needs basic code completion and that we can add our C# objects and methods (The ones you will be able to reach from the Lua scripts while running) so they will be auto completed.. Are they such a API available for C#?
edit: Schollii wanted some example code that i want code completion for
while true do
Mouse:setY(TrackIR:getPitch())
end
where Mouse and TrackIR are c# objects accessible from Lua script
If you want to integrate a Lua editor with syntax highlighting C#, IMO the easiest way is to go for the Scintilla control, which is available in C# through ScintillaNET. It already contains highlighter for the Lua language, and is relatively easy to embed and use.
For interfacing Lua with C#, you can use LuaInterface and back. See this question for documentation links.
Code completion will not be an easy task if you require completion beyond the standard library, which can be described in a simple dictionary. With Lua being a dynamic language, it is not trivial to deduce the contents of a variable before actually running the code up to a given point - it is not impossible, take a look at lua-inspect which is available for SciTE and ViM and allows code inspection (but it's not perfect).
If you want to try code in a running environment - i.e. you have a Lua state running with modules loaded and variables set - you can get inspired by Advanced Readline Support patch at LuaPowerPatches and adapt it to your enviroment in C#. It supports among other:
Completion of keywords and global variable names.
Recursive and metatable-aware completion of variable names.
Context sensitive delimiter completion.
It seems you just want an embeddable editor that can have code completion and syntax highlighting, preferably WPF based. It doesn't need to explicitly support Lua.
Have a look at Avalon Edit. Here is an article about it
You will have to implement the highlighting file and completions yourself within the framework it provides - but that looks easy enough.
I am not aware of any such libs. Some tool you will likely need/find useful are Luainterface and some open-source Lua editors that provide code comppletion such as blua and Scite. Note that code completion comes in different flavors, each with pros/cons in terms of power, ease of implementation, etc. For instance if you just want to provide a list of possible words that correspond to objects in global Lua namespace then you don't need much at all; if OTOH you want code completion to work with table fields and objects and various levels of nesting, work will be much increased.
I've been playing with Java for years as a means of developing quick and easy tools for repetitive tasks. I am not a true "developer" in the traditional sense, but I have lots of experience creating a wide assortment of tools and PoCs.
Unfortunately for me, I have noticed many shops are specifically looking for experience with C#, and not so many for Java. Even here on SO, there are more questions and more followers to C# related issues than Java. My preference will always be Java over C# simply for the cross-platform compatibility, but since the languages are so similar, I believe it would be beneficial for me to cross-train. I have already dabbled in other languages and scripts (VB and other BASIC flavors, Javascript, VBScript, ASP, JSP, PHP, etc.) so adding another isn't out of the question.
My current Java environment simply consists of a text editor (primarily jEdit for its plugins and layout) and homemade scripts to compile/jar my projects. I don't like to use IDEs because I want full control over my code and don't want a program writing code for me. (I also prefer to write my own code as opposed to using any sort of external library/package, if feasible. It helps me learn and greatly reduces unnecessary code.)
Therefore, what are my options for a non-IDE C# SDK? Libraries are obviously not that important to me. I've heard of Mono, which appears to separate the functions, but haven't tried it yet. What other SDKs exist that are similar to a simple Java SDK combined with a text editor?
Using an IDE doesn't have to mean anything writing code for you. I'm not generally keen on designer-generated code, but unless you decide to use a designer (or snippets etc), Visual Studio won't be writing code for you. Of course it will create a skeleton class for you when you create one, add the appropriate method signatures when you implement an interface etc - but is that boilerplate really something you want to write yourself?
I'd also suggest that your policy of not using external libraries is a bad one. I agree that it's useful for educational purposes to sometimes reimplement something, but it means that the code quality is likely to end up being worse... why would you not want to use code that has already been used and improved by many other people? Yes, you need to be careful about what libraries you use - but you really don't want to do everything yourself... not if you want to be productive, anyway.
I often use a text editor and command line myself for simple test code (e.g. for Stack Overflow questions) but I wouldn't dream of doing that for "real" code that I plan to keep.
Honestly, a lot of C# and .NET is about learning the tools; Visual Studio gives you a lot that you wouldn't be able to do with a text editor. There's a free version, and I highly suggest you check it out! People hiring will want to know that you're familiar with the tools they'll most likely be using.
You can just start with Notepad and csc.exe, the the command-line C# compiler that ships with the .NET SDK.
However, IDE is not necessarily synonym for code generator. I would download Visual Studio Express and start with empty Console projects.
Have fun!
Don't forget you can build/assemble C# projects using MSBuild and a .sln file if you really want. But the IDEs will make life a lot easier.
The IDE will not write code for you, it will help you writing code. Using libraries will help you concentrate on what you really want to program, not the things that already have been done.
Check into AvalonEdit, the text editor component of SharpDevelop. It is an open source text editor that has classes that could implement features such as intellisense and syntax highlighting. You would only have to use as much of it as you wanted and you could embed it anywhere you would use a text box control.
If you are familiar with Ant from Java then you could also check out NAnt to do your compile phase.
As far as I know, with Visual Studio you also get a command line C# compiler, csc. You could use a text editor and manually compile your C# code with that on the command line if you really want - that wouldn't be very practical however when your project contains more than a handful of source files.
If your project becomes bigger, you could use a tool like NAnt, which is a .NET version of the popular Java build tool Ant.
I agree with Jon Skeet about that your way of working is not very practical. If you are really looking for a software development job, you'd better learn to use the tools that other developers use. An employer will also not accept the fact that you'd want to write all the code yourself instead of using libraries. By using libraries instead of writing it all yourself you save lots of time, you are reusing well-tested code and your code will be much easier to maintain by other developers.
I've been jumping from C# to Java an awful lot and the "differences" between the two are a bit of an annoyance.
Would it be possible to write a set of extentions/plugins that would merge the two languages syntaxes.
I'm talking about adding either IDE support or using language constructs that would for example:
treat these two lines equivalently:
System.out.println("Blah");
Console.out.writeline("Blah");
Automatically notice that when you type in string you mean String
Recognise common API calls and translate them in the background.
The end goal being to be able to write a java/C# program and to pick at compile time which VM/Runtime you are targeting.
If you could do this would it be a good idea?
If not why not?
The two languages are so similar it's painful in some aspects but in other aspects they are really different.
I've seen Code that will translate a C# project into Java and I'm assuming there is probably the reverse, what I am proposing is a middle ground, so we can all just "get along".
No, absolutely not. Certainly not in the languages themselves (as implied by the title) and preferably (IMO) not in the IDEs (as requested in the body).
They are different languages. The idioms and conventions are subtly different. I don't want to be thinking in Java when I'm writing C# or vice versa. I believe developers should be actively encouraged to separate their thinking. It's not too hard to switch between the two, but that switch should be present, IMO.
While I totally agree with Jon Skeet, if you must have this why not create your own library of Java API so you can create System.out namespace which has a method call printLn which calls Console.Writeline()?
That gets you close to what you want.
Just because Java and C# share some similar syntax you need to see past this and think in terms of Java Platform and .NET Platform. The two are distinctly different, so my answer is definitely not.
There actually already is a Java language for the .NET framework, developed by microsoft: J#
This way you get the java-syntax but you are still developing with the .NET framework.
But i am not recommending anyone to use it.
I knew Java before i knew C# so i tried out J# because i thought it would be an easier transition. At first I liked it but after I tried C# I'm never going back. First of all, nobody uses J# so it's kinda hard to find examples and tutorials. Second, C# has (IMO) much more convenient syntax, specially for events, properties, lambda, anonymus methods and alot of other things, it's also being updated every now and then with even more syntax sugar which i don't think J# is.
Maybe if you often write Java and sometimes have to write a .net app it might be a good option.
I think no. I also switch from java to c#. But if the syntax is identical was is to stop someone from trying to compile c# in a Java compiler, or vice-versa.
Visual Studio actually ships with a Java to C# converter, which tries to do some of the things you mention. Unfortunately it fails miserably (1) for anything beyond the simple hello world application.
Despite being very similar on the surface, there are many significant differences between Java and C#, so you would achieve very little by doing what you suggest imo.
(1) To be fair, it actually does a fairly good job if you consider the limitations given for such a task, but in practice the resulting code is of limited use and you have to do a lot of clean up after the conversion.
Firstly what you are describing is not a difference in language syntax but a differences in class libraries. Both languages are relatively simple in terms of keywords and features but understanding or knowing the libraries and how they operate requires considerable learning.
The mistakes you are describing are things that the developer should not be making to begin with - the IDE should not be guessing. There are going to be many cases where you can't easily / trivially translate between java or dotnet. In the end a skilled developer learns and knows when and which class libraries to use.
Actually in the beginning there was no dotnet - microsoft was behind java. They however proceeded to change java in ways not compatible with the java plstform standard. To paraphrase sun sued microsoft and won I'm court. Following that ms proceeded to create dotnet and particularly c# which became microsofts VM platform. Of course along the way a whole stack of things got changed. Microsoft introduced many things which broke Javas run anywhere etc. They have done the same thing with dotnet which have cause problems for the mono team to be able to faithfully reimplemwnt everything for other non windows platforms.
• String vs string.
• lowercase method names (java) v uppercase method names(dotnet).
• Giving java keywords new names - "package".
In the end dotnet was microsoft response so they can control the platform and do their own thing instead of following a standar