What are some ways to compile Java from C# code? - c#

I'm writing a multi-language IDE in C#. Right now, it works as a reasonably functional editor. However, I'm working now on adding the ability to compile and run Java code (I know it sounds silly to write this in C#, but I prefer using C#, and I need the Java support for a school class).
After that background, here is the question: What is the best way to compile Java code from C#? Right now, I am using the System.Diagnostics.Process class. Basically, I am invoking the compiler the same way you would call javac from the command line. Here is a rough example of my current implementation:
ProcessStartInfo buildInfo = new ProcessStartInfo();
buildInfo.WorkingDirectory = Path.GetDirectoryName(sourcePath);
buildInfo.RedirectStandardOutput = true;
buildInfo.RedirectStandardError = true;
buildInfo.UseShellExecute = false;
Process buildProcess = Process.Start(buildInfo);
I redirect standard output and error because later the application catches them to determine whether the compilation was successful. Is there a better way to do this? It feels a little sloppy, and I wanted to know if I was overlooking something.

You do have other options. Java provides JNI (Java Native Interface ) which allows Java to call native code and apropos, for native code to call Java (albeit in a rather complex way.)
Depending on how much of a learning experience you want this to be you can use JNI directly or use a library such as jni4net. A different interop approach is to use ikvm which is a jvm running inside the clr, but I don't think it'll be useful to you as it does not include a compiler.
You can also research alternative compilers such as gcj or ejc.
Not having tried to write an IDE I don't know whether these approaches are actually better than using the command line directly. My hunch is that for simple integration the command line is the easier to use however more complex scenarios, e.g. incremental compilation of large projects with multiple components, may require tighter integration.
If you plan on providing features such as inline debugging and error highlighting while you type you're going to require tighter integration anyway.
IDEs are extremely complex programs, even mere programming editors are complex enough.

A quick googling suggests (no surprise) there's no .Net API for compiling Java. Thus, the simplest way will probably be to use javac via the command line, as you are currently doing.
Your command line code looks similar to examples I've seen, so I don't expect there's much room for improvement. Thus, the short answer to your question: no, you're good (as good as compiling Java from C# can be, anyway).

You could use the Java Invocation API to host the JVM within your process and then run the compiler through the compiler API. It's probably faster than spinning up separate compiler process for compilation and certainly makes for a good learning experience (you'd need to use P/Invoke from the .NET side etc.).

There are some free and commercial tools out there:
http://community.versant.com/Blogs/db4o/tabid/197/entryid/94/Default.aspx
http://visualstudiogallery.msdn.microsoft.com/9789645d-9b31-4033-bcb1-53dc5ff58e05
And so forth...

Related

About "GUI in C# and code in C++"

First of all, until now, all my programming education, has been targeted to console applications, just like everyone who starts learning C and C++. (the 2 languages i know)
Now, i want to jump to the nice graphical World.
So, I am exploring Windows Forms, i have already got many headaches trying to understand the language that it uses (quite diferent from native C++), but i managed to do a couple of things like using textbox and buttons.
Well, the thing is, i have read in many places that, in order to avoid headaches trying to code winforms in C++, i'd better "Build the GUI in C#, because it's way easier, and the logic, and code in C++". And that is my question, i don't understand that statement, at all.
What is that supposed to mean?
Also, it's C# THAT similar to C++, as to affirm that statement? Cause, if C# was too diferent to C++, i would have to learn the whole C# language
hope you understand my doubt.
PD : Sry about my bad english.
Joan, while it is certainly possible to develop an applications Front End in C# and the logic in C++ I believe it to be a huge waste of effort to do it this way since you only complicate yourself for no real benefit since you can code both things in the same language.
C# has many advantages over C++ and I personally use mostly C#, but I can clearly see many programmers who love C++.
Now going into your question regarding the similarities between C++ and C# the answer is yes and no. Yes in the sense that C#'s syntax is clearly derived from C++. Many things like ifs and for loops are written exactly the same, so if you know how to write an if in C++ you can write it in C#.
The difference (and a critical one that is) lies in the way the languages work. C++ is an strictly compiled language (it goes from C++ code to machine code). C# is an interpreted language (it goes from c# to MSIL and during runtime to machine code). In C# you can't use pointer arithmetic without explicitly allowing, in C++ you can (and will) use pointer arithmetic. C# has garbage collection, C++ does not.
In the end, as I said in the first paragraph you can use both languages to build an application, but it would be highly complicated. My advise to you is to learn a bit of C# and then decide which language you would prefer to build your GUI application. But don't believe even for a second that C++ can't be used to build a front-end since there are a myriad of frameworks for that. One I remember from the top of my head is Qt.
Another option for you is to use "C++/CLI" which is a flavor of C++ which can use the .NET Framework (the same framework C# uses)
EDIT: Thanks Jerry for pointing out that Managed C++ is obsolete and that C++/CLI is the one!
C# has braces, semicolons, and uses the concept of classes. It has "C derived" syntax, but otherwise is very dissimilar to C++. Java is really the precursor to C#, not C++.
You can build application GUIs using C#, and then use various methods of calling into C++ (such as P/Invoke). Unless you are using lots of existing libraries, or looking for absolute performance, its going to be a headache.
If you are looking for examples of modern Windows GUIs using C++, take a look at the Hilo example program.
It is not very difficult to switch to a new language. The few keywords you would have to learn are not the issue. What costs most energy if to get used to the new environment and class libraries. That is probably what you mean and it is true, you'll need some time.
Now coming to the split GUI in C# and code in C++, then you'll have to make all bindings and marshalling of parameters if there are buffers and strings for example. I don't think this would make your life any easier. Interfacing with native Dlls can become some pain. However if you use third party dlls and have already a large working codebase you could try to compile the logic code with /clr enabled. This generates a DLL that can be used from within .NET directly.
NOTE: WinForms is now out-of-date for new applications, consider using WPF instead. It scales nicely, but the learning curve might be steep for newcomers.
Please note that you have native C++ and C++/CLI, the first one is the one you have learned, but the second one is the one you will need to use if you want to combine it with a C# GUI. However, I would suggest you to stay away from C++/CLI because this will cause a lot of confusion if you don't have a solid ground in C++, C# and .NET.
The reason that you can't use the native C++ is because C# is a managed language, so you will either have to find another GUI that fits with C++ or you will have to go C# for everything. For more information about managed see the environment part of Difference between C++ and C#, the article will also provide you with a good comparison between both.
Well, this aint a direct answer but hope it will help you. Since you stated that, you are just started and you want C++ combined with GUI, I suggest you to take a look at Qt. IMO I found C++ and GUI made easy in Qt. Also it's good too.
Although it's not a direct response to the question you're asking, I'd first caution that WinForms are already basically a dead-end, so for new code you'd be much better off avoiding them. If you're going to do a GUI in .NET, the currently preferred choice is WPF.
Some people find C# an easier way to do a GUI. It's definitely true that Microsoft provides considerably more in the way of Wizards and such to do it with little or no coding if you use .NET for the job. Other people (especially those with more experience doing so) can produce a GUI in C++ just quickly (or even a little more so) using C++ instead.
Mixing languages like this can work well in relatively large projects where you have completely separate teams of people working on the different parts. For smaller projects where the same people typically work on both parts, the difference in syntax is at just about the worst possible level -- not enough different to really shift gears and think differently, but still enough different that you can't plan on just typing things and having any hope of them compiling. All in all, you're usually a lot better off picking one language and sticking to it.

Modifying text files and executing programs with command line parameters in c# or c++ on Linux

I have a need to create a utility in Suze Linux. The utility will make modifications to some text files, and then use the information in those text files to program a device in the computer using a different executable which accepts command line parameters.
I am fluent in c#, but have never worked with Linux. Should I take the time to learn Gnu C++ to do this, or install Mono? How would I execute the programming utility and pass it command line parameters?
Is there a reason you want to restrict yourself to only C++ or C#? There are many options you could consider, for example:
For very simple tasks:
Bash: In some cases a simple Bash script will be able to solve the task. Piping information from one process to another is a breeze, and you have the power of sed, awk, etc. at your fingertips. Another major advantage is that it is installed almost everywhere.
For slightly more involved tasks you could try a scripting language:
Python: Easy to learn, pleasant to read. Very useful for putting together small applications quickly. You can use subprocess to communicate with other processes.
Ruby: Similar comments to Python - a good scripting language with a clean syntax.
Perl: Perl is very good at processing text, although personally I dislike the syntax.
Other options:
Java: Your C# experience will allow you to learn Java quickly as it is a very similar language. Java is officially supported on Linux.
C#: A lot of Linux users are wary of C# because it isn't free enough, but obviously that isn't a worry for you. It has worked fine the few times I've tried it. Note that Mono is not 100% compatible with Microsoft's version.
C++: For what you're planning to do I personally wouldn't recommend C++. It will solve the task though, and if you already know some C++ then I guess it is worth considering.
Obviously there are many other suitable options too.
In C and C++ there's system("command arguments") which you can use to execute a command using the system's interpreter (i.e. you can use it as though you had typed in the command in the shell). The command string can be constructed at runtime. I'm not very familiar with C#, but if I recall correctly you can use Process and ProcessStartInfo classes to run system commands.
Based on the complexity of your program I'd recommend using a scripting language like Perl. It's always a good idea to have a scripting language in your toolbox.

What's a good way to write batch scripts in C#?

I would like to write simple scripts in C#. Stuff I would normally use .bat or 4NT .btm files for. Copying files, parsing text, asking user input, and so on. Fairly simple but doing this stuff right in a batch file is really hard (no exceptions for example).
I'm familiar with command line "scripting" wrappers like AxScript so that gets me part of the way there. What I'm missing is the easy file-manipulation framework. I want to be able to do cd(".."), copy(srcFile, destFile) type functionality.
Tools I have tried:
NANT, which we use in our build process. Not a good scripting tool. Insanely verbose XML syntax and to add a simple function you must write an extension assembly. Can't do it inline.
PowerShell. Looks great, but I just haven't been able to switch over to this as my primary shell. Too many differences from 4NT. Whatever I do needs to run from an ordinary command prompt and not require a special shell to run it through. Can PowerShell be used as a script executor?
Perl/Python/Ruby. Really hate learning an entirely new language and framework just to do batch file operations. Haven't been able to dedicate the time I need to do this. Plus, we're a 99% .NET shop for our toolchain and I really want to leverage our existing experience and codebase.
Are there frameworks out there that are trying to solve this problem of "make a batch file in C#" that you have used?
I want the power of C#/.NET with the immediate-mode type functionality of a typical cmd.exe shell language. Am I alone in wanting something like this?
I would try to get over the PowerShell anxiety because it is the shell of the future. All of the software coming out of Microsoft is using it as their management interface and especially version 2.0 is ridiculously useful.
I'm a C# developer most of the time but PowerShell has solved that whole "WindowsApplication42" problem of temp projects just piling up. PowerShell gives you full access to the .NET framework in a command line shell so even if you don't know how to do something in PowerShell, you most likely know how to do it in .NET.
IronPython and IronRuby do let you leverage all of your .NET "experience and codebase" (they don't answer your objection to learning new languages, however).
If you have any bash nerds, you can always try cygwin.
Also remember that Python was originally intended as a "glue" langauge. If you used the aforementioned IronPython, it's pretty easy to tie together pre-written C# classes.
If you are bind to MS, PowerShell is surely the way to go. But I don't like it much.
I personally use MSBuild script more, and would like to see Mono C# Shell one day comes to Windows.
I think CS-Script might be the ideal solution for you.

IronPython vs. C# for small-scale projects

I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Since Python is my favorite programming language (mainly because of its conciseness and clean syntax), IronPython sounds like the ideal option. Yet after reading about it a little bit I have several questions.
For those of you who have used IronPython, does it ever become unclear where classic Python ends and .NET begins? For example, there appears to be significant overlap in functionality between the .NET libraries and the Python standard library, so when I need to do string operations or parse XML, I'm unclear which library I'm supposed to use. Also, I'm unclear when I'm supposed to use Python versus .NET data types in my code. For example, which of the following would I be using in my code?
d = {}
or
d = System.Collections.Hashtable()
(By the way, it seems that if I do a lot of things like the latter I might lose some of the conciseness, which is why I favor Python in the first place.)
Another issue is that a number of Microsoft's developer tools, such as .NET CF and Xbox XNA, are not available in IronPython. Are there more situations where IronPython wouldn't give me the full reach of C#?
I've built a large-scale application in IronPython bound with C#.
It's almost completely seamless. The only things missing in IronPython from the true "python" feel are the C-based libraries (gotta use .NET for those) and IDLE.
The language interacts with other .NET languages like a dream... Specifically if you embed the interpreter and bind variables by reference.
By the way, a hash in IronPython is declared:
d = {}
Just be aware that it's actually an IronPython.Dict object, and not a C# dictionary. That said, the conversions often work invisibly if you pass it to a .NET class, and if you need to convert explicitly, there are built-ins that do it just fine.
All in all, an awesome language to use with .NET, if you have reason to.
Just a word of advice: Avoid the Visual Studio IronPython IDE like the plague. I found the automatic line completions screwed up on indentation, between spaces and tabs. Now -that- is a difficult-to-trace bug inserted into code.
I'd suggest taking a look at Boo [http://boo.codehaus.org/], a .NET-based language with a syntax inspired by Python, but which provides the full range of .NET 3.5 functionality.
IronPython is great for using .NET-centric libraries -- but it isn't well-suited to creating them due to underlying differences in how the languages do typing. As Boo does inference-based typing at compile time except where duck typing is explicitly requested (or a specific type is given by the user), it lets you build .NET-centric libraries easily usable from C# (and other languages') code, which IronPython isn't suitable for; also, as it has to do less introspection at runtime, Boo compiles to faster code.

Calling C# code from Java?

Does anyone have a good solution for integrating some C# code into a java application?
The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc.
Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible.
Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.
You would use the Java Native Interface to call your C# code compiled into a DLL.
If its a small amount of C#, it would be much easier to port it to Java. If its a lot, this might be a good way to do it.
Here is a highlevel overview of it:
http://en.wikipedia.org/wiki/Java_Native_Interface
Your other option would be to create a COM assembly from the C# code and use J-Interop to invoke it.
http://sourceforge.net/projects/j-interop/
I am author of jni4net, open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.
If it's short, I think you're better off re-writing the code in java. Downloading one 50Mb runtime is bad enough.
There is an IL to Java Bytecode compiler GrassHopper which may be of use to you. I've never tried it though.
I'd look at rewriting your code in Java though
EDIT: Note that Grasshopper seems to be no longer available.
We used JNBridge for this, and it worked great. It handles Java->.NET and vice versa, all in-proc.
If you do not want to rewrite hadle it as an Inter-process communication and choose one of following:
Named pipes
Sockets
SOAP
I would rewrite it if it's not too much trouble.
The web service would work, but it seems like that would be a lot of overhead just to reuse a little code.
http://www.infoq.com/articles/in-process-java-net-integration suggests running CLR and JVM in the same process space and passing calls back and forth. It sounds very efficient. I'm going to give it a try and integrate it into Jace if it works well.
If it is a piece of code that is exposable as a command line utility, I just make the other host language use a system call to execute the utility.
If your C# app needs to call Java, compile a special Java main that takes appropriate command line args and returns text output.
It the oldest, simplest method.
You can call your c# classes (compiled in a dll) via a bridging library, various libraries are available, every one with his characteristics. JNBridge generate proxy classes that you can call to manage the code in java classes. JCOBridge let you load your c# classes and use it from java using the invoke mechanism, also javonet let you import java classes and call java code using the invoke mechanism. All the explored solutions are commercial solutions that let you call java code from .NET and vice-versa with graphical user interface integration and other amenities.
Links:
jnbridge java-.NET bridge Developer and Deployment license schema with 30 day free trial
jcobridge java-.NET bridge Developer and Deployment license schema with unlimited Trial
javonet java-.NET bridge Research and Professional license schema with 30-day unlimited Trial after sign-up

Categories

Resources