C# --> Java code generator - c#

I have a small (~2000 lines of code) class that I would like to use from both java & .NET. There are several approaches to do this - among them wrapping the class as a service, using some interop voodoo, or duplicating the code to both C# & java.
Do you know an out-of-the-box tool that accomplishes the latter - takes a simple C# class with no dependencies and converts it to an equivalent java class?

IKVM.NET does pretty good job in taking a jar file and compiling it to a managed .NET assembly.

If it is small (or in fact, even if it is large), I'm not sure of the wisdom of mechanical translation tools; I've simply never had much joy with them. However, one option would be to write the .NET code in J#.
But I stress - if it was me, I'd manually port it between the two manually and maintain them separately. Most of the time the differences aren't huge - signed bytes, the boxing differences, etc. Of course, anything with delegates will need changing - and captured variables work differently, etc etc.

There used to be a COM bridge and you can register C# assemblies for use in COM with regasm.exe or visual studio.

It's not really what you asked for, but I would just create a simple C# to Java translator.
The differences are not that huge and you seem to be the author of the source so you can avoid nasty constructs that are quite difficult to translate. That way your translator would be quite simple. I would go from C# to Java because C# is more expressive, and you can emulate almost all the C# functions in Java.
Actually cs2java seems to do just that.

This is list of tools I know. Sharpen or j2cstranslator looks like good options.

Related

Upgrading from C++ to C#

I have a large application written in C++, For various reasons I am going to rewrite it in C#, I have done plenty of Delphi to C#, VB to C# but C++ to C# I have never done, although I am competent in C++ I want this to be as smooth a conversion as possible.
Mainly what I am asking is what pitfalls await me in this conversion is there any key areas I should be aware of or any advice you can provide me.
This article is quite good, but is there anything else I should be weary of?
http://msdn.microsoft.com/en-us/magazine/cc301520.aspx
Main pitfall - do not think it's an upgrade. These are DIFFERENT languages, and in many places you will need complete different approach to the problems. So you should think reimplementation with minimal code reuse.
This article is decent.
I'd advice you to pay attention to the objects lifecycle.
In C++ you destroy objects explicitly when you've done with them. In C# (.NET) you don't. It can happen that an object holds on to some important resource (file handle, database connection etc.). If it is an issue, make use of the using directive.
You need to translate the spirit of the code, but not the code itself. You need to leave behind all the things you had to do in C++ because that was how it was done there. Good translation is highly creative process, so be creative.
The handling of strings was a pitfall for me at the beginning. While I Visual C++ you use pointers the methods in C# have indeed return values.
dummy = dummy.Replace("a", "b");
If you have C++ dll and you want to use them in your C# project you can used them by pinvoke and DllImport
There will be lot of differences while you will try to convert or rewrite unmanaged code to managed one. Here is a C++ to C# converter which is quite good for converting your c++ code to C# , though you can not expect to convert the whole project using it.

Effort estimation: using C / Win32 or learning C# / .NET

I intend to write a small application to scratch a personal itch and probably make the life of some colleagues easier. Here is what I have:
10+ years of experience in C
Plenty of experience in programming against the Win16/32 API in C from the Win3.1 to 2000 days.
C library written by myself already doing about 75% of what the application shall do.
What the application shall do:
open a binary, feed it into the mentioned library.
take the resulting text output and feed it into a new Excel Workbook.
apply some formating.
integrate nicely with the Windows environment (availability in "Open With...", remember some stuff using the registry etc.)
(maybe later) before giving the CSV data to Excel, parse it by looking up the meaning of some values in an XML file.
Except for the XML parsing part I have done all of that stuff before including COM / Office Automation in C/Win32. There is a lot of boilerplate code involved, but it is doable and the result will be a pretty small application without the need for an installer.
So why even think about C# / .Net?
no experience with parsing XML
the promise of less boilerplate code for the Windows and Excel stuff (yes, I have done C++ with OWL, MFC, ATL etc. but I am not going there anymore - not for free/fun)
Since I have also experience with C++, VB(not .Net) and a little Java / Objective-C I suppose learning C# will all be about the .Net libraries and not actually about the language.
My considerations so far:
Learning .NET might be fun and might result in less code / first steps in a more modern environment.
Sticking with what I know will lead to a predictable outcome in terms of effort and function (except for the optional XML stuff)
VB looked great at the beginning until the projects where about 80% done, then the pain started and the DLL coding in C. I am concerned history could repeat itself if I choose .Net.
My primary objective is the functionality. Effort is a concern. The XML parsing is optional.
Please advice.
Update: one thing I forgot to mention explicitly is that I am also worried about easy deployment of the tool to my co-workers. With Win32 I am pretty sure I can come up with an EXE file < 1Mb that can be easily emailed and does not require installation. With .Net not so much. Can I create the necessary MSI or whatever in Visual Studio Express (free) or do I need 3rd party tools?
as others have your question mostly covered, I'd just like to quickly comment on your considerations:
Learning .NET might be fun and might result in less code / first steps in a more modern environment.
Totally agreed. It is definitely fun and usually it does result in less code. The investment you make now will certainly benefit you in future projects. It is way faster to program in .Net than in C. Not only it is easier, but it is also safer. You are isolated from many programming errors common in C mostly related to memory mismanagement. You also get a very complete managed API to do stuff you would usually need to build your own framework.
Sticking with what I know will lead to a predictable outcome in terms of effort and function (except for the optional XML stuff)
Hence your indecision. :-)
VB looked great at the beginning until the projects where about 80% done, then the pain started and the DLL coding in C. I am concerned history could repeat itself if I choose .Net. My primary objective is the functionality. Effort is a concern. The XML parsing is optional.
.Net is an entirely different beast from VB. Most of the things you wouldn't be able to do in VB, or at least do them easily, are supported by .Net. For instance, Windows Services are a snap to build in .Net. Socket programming is also supported, but there are very few reasons to do it yourself, as you've got loads of communication APIs with .Net. You've got web-services, .Net Remoting, MSMQ management, and more recently WCF. Proper multithreading is supported by .Net, unlike the idiotic apartment model in VB. In case you really need to go low level, you can also actually use pointers in C#, inside of unsafe code blocks, even though I would never advise to do so.
If you really need to do things in C, then integrating is also relatively easy. You can create COM objects and use interop to work with them from .Net. You can also interact directly with plain ol' dlls using DllImport. Using www.pinvoke.net makes it easier.
When I developed in VB, sometimes I also had to go back to C++ to do stuff that I wasn't able of doing in VB. Since I began programming in .Net, the only extremely rare scenarios I would need to go back to C++ were when I needed to use legacy COM components that used types I was having a hard time to marshal via interop. I wouldn't worry about history repeating itself.
If you're using COM, you may be interested in using C# 4.0 instead of earlier versions - the downside being that it's only in beta. But basically it makes COM stuff somewhat less ugly for various reasons.
I'd expect there to be plenty of good C libraries for XML parsing by now. I would expect the main benefit to actually be the knowledge gained. I doubt that you'll actually produce the code faster for this project, but the next one may well be a lot quicker.
How much do you care about learning new stuff?
It sounds like an ideal project for learning C# & .NET.
You know most of what you need to do so you can use that to gain a base level of understanding of C# & .NET which you can then apply to the stuff you need to learn.
As Rune says though, a key driver could be the timescales. If this is something you need in a hurry then coding it in C & using win32 directly might be the answer.
Sorry I couldn't be more definite.
I think you should use C#. With your experience the learning curve won't be too steep. The code will ultimately be cleaner (and less of it) than you probably could with C/Win32.
There is probably going to be no problem using your existing C-library with the [DllImport] attribute.
It depends. :-) It depends on whether you want to do this quickly or if you want to learn something new. It depends on whether you will be the only maintainer of the code or if others will maintain it in the future. It depends on how complex your xml handling will be and on how complex the COM automation is.
You will probably get a working application quicker if you do it in C than in C#. Both since you have much of the stuff needed already in place and since you know C well.
But this project sounds like a good match for C# and .Net. .Net has great support for XML and COM interop is easy but clumsy in C# (much better in the next version!). So if you are interested in learning C# and .Net this would be a good project to do so.
I would definitely do this in .Net and probably C# (but I am biased). Using .Net would probably result in code that is easier to read and maintain and most probably easier to write. So if you are interested in learning C# I would suggest you go for it!
Edit:
You worry about the size of the executable if you write it in .Net. I doubt that will be a problem, for most if not all of the libraries you will use for a project like this will already be installed on your computer. 1 Mb is rather large for a .Net executable, event for a big project.
a short notice on the installation. .NET is as default xcopy-able so you wouldn't need an installer for the exe to be usable. Mail it around (or with the next release of the .NET framework optionaly leave it on a network share)
You could look at building a hybrid system that uses C++/CLI and C#. C++/CLI provides a nice bridge between the two and lets you easily split different parts of the system between the managed and unmanaged worlds.
Not sure if the setup projects are included in the free versions of visual studio. But you could use clickonce (included with the framework) or WIX (open source XML based msi creation tool).
learning C# will all be about the .Net libraries and not actually about the language
No there are many things you need to learn about the language (delegates , events , generics ...) and also it is object oriented and it manages the memory by itself and yes no pointers :)
anyway C# and .NET are great all you need is some effort to get up to speed

Should C# and Java incorporate each others syntax?

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

How should I convert Java code to C# code?

I'm porting a Java library to C#. I'm using Visual Studio 2008, so I don't have the discontinued Microsoft Java Language Conversion Assistant program (JLCA).
My approach is to create a new solution with a similar project structure to the Java library, and to then copy the java code into a c# file and convert it to valid c# line-by-line. Considering that I find Java easy to read, the subtle differences in the two languages have surprised me.
Some things are easy to port (namespaces, inheritance etc.) but some things have been unexpectedly different, such as visibility of private members in nested classes, overriding virtual methods and the behaviour of built-in types. I don't fully understand these things and I'm sure there are lots of other differences I haven't seen yet.
I've got a long way to go on this project. What rules-of-thumb I can apply during this conversion to manage the language differences correctly?
Your doing it in the only sane way you can...the biggest help will be this document from Dare Obasanjo that lists the differences between the two languages:
http://www.25hoursaday.com/CsharpVsJava.html
BTW, change all getter and setter methods into properties...No need to have the C# library function just the same as the java library unless you are going for perfect interface compatibility.
Couple other options worth noting:
J# is Microsoft's Java language
implementation on .NET. You can
access Java libraries (up to version
1.4*, anyways).
*actually Java 1.1.4 for java.io/lang,
and 1.2 for java.util + keep in mind that J# end of
life is ~ 2015-2017 for J# 2.0 redist
Mono's IKVM also runs Java on
the CLR, with access to other .NET
programs.
Microsoft Visual Studio 2005 comes
with a "Java language conversion
assistant" that converts Java
programs to C# programs
automatically for you.
One more quick-and-dirty idea: you could use IKVM to convert the Java jar to a .NET assembly, then use Reflector--combined with the FileDisassembler Add-in--to disassemble it into a Visual C# project.
(By the way, I haven't actually used IKVM--anyone care to vouch that this process would work?)
If you have a small amount of code then a line by line conversion is probably the most efficient.
If you have a large amount of code I would consider:
Looking for a product that does the conversation for you.
Writing a script (Ruby or Perl might be a good candidate) to do the conversion for you - at least the monotonous stuff! It could be a simple search/replace for keyword differences and renaming of files. Gives you more time/fingers to concentrate on the harder stuff.
I'm not sure if it is really the best way to convert the code line by line especially if the obstacles become overwhelming. Of course the Java code gives you a guideline and the basic structure but I think at the end the most important thing is that the library does provide the same functionality like it does in Java.

Is there an easy way to convert C# classes to PHP?

I am used to writing C# Windows applications. However, I have some free hosted PHP webspace that I would like to make use of. I have a basic understanding of PHP but have never used its object-oriented capabilities.
Is there an easy way to convert C# classes to PHP classes or is it just not possible to write a fully object-oriented application in PHP?
Update: There is no reliance on the .NET framework beyond the basics. The main aim would be to restructure the class properties, variable enums, etc. The PHP will be hosted on a Linux server.
PHP doesn't support enums, which might be one area of mismatch.
Also, watch out for collection types, PHP despite it's OO features, tends to have no alternative to over-using the array datatype. Check out the sections on the PHP manual on iterators if you would like to see beyond this.
Public, protected, private, and static properties of classes all work roughly as expected.
A huge problem would be to replicate the .Net Framework in PHP if the C# class usses it.
It is entirely possible to write a PHP application almost entirely in an object-oriented methodology. You will have to write some procedural code to create and launch your first object but beyond that there are plenty of MVC frameworks for PHP that are all object-oriented. One that I would look at as an example is Code Igniter because it is a little lighter weight in my opinion.
I don't know about a tool to automate the process but you could use the Reflexion API to browse your C# class and generate a corresponding PHP class.
Of course, the difficulty here is to correctly map C# types to PHP but with enough unit testing, you should be able to do what you want.
I advice you to go this way because I already did a C# to VB and C++ conversion. That was a pain but the result was worth it.
If the problem is that you want to transition to PHP and you are happy to continue running on a windows server with .NET support you might consider wrapping your code using swig.
This can be used to generated stubs to execute from php and you can then go about rewriting the .NET code into PHP in an incremental fashion.
This works for any of the supported languages. ie. you could incrementally rewrite an application in c++ to java if you really wanted to.

Categories