Converting Delphi vcl.net application to c# using Reflector - c#

I have used reflector until its trial period ended
I have decoded many applications successfully. And by my recent post i was able to identify it can also decode delphi.net vcl apps (d2007).
Can i decode delphi.net vcl and translate it to a c# application which can be compiled success fully using visual studio.

The answer to the question Can i decode delphi.net vcl app and translate it to a c# application which can be compiled success fully using visual studio ? is No
This is the Why.
When you create a vcl net application using delphi (8), 2005, 2006 or 2007, the delphi compiler create an .NET application with a lot of dependencies to internal classes which are wrappers and helpers to call the real .net classes, these classes (wrappers) was created to facilitate the creation of .net applications to the existing delphi win32 developers.
Consider this sample.
This a delphi .net app
program DelphiNetConsole;
{$APPTYPE CONSOLE}
uses
SysUtils;
begin
try
Writeln('Hello From Delphi 2007.Net');
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
if you translate manually this code to C#
using System;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Hello From Delphi 2007.Net");
}
catch (System.Exception E)
{
Console.WriteLine(E.Message);
}
}
}
}
But using reflector you get this for the first snippet
public static void DelphiNetConsole()
{
System.IsConsole = true;
try
{
TextOutput.Output.WriteWideString("Hello From Delphi 2007.Net", 0).WriteLn();
System.#_IOTest();
}
catch (Exception exception1)
{
Exception exception2 = System.#ExceptObject = exception1;
Exception E = exception1;
TextOutput.Output.WriteWideString(TObjectHelper.ClassName(System.#GetMetaFromObject(E)), 0).WriteWideString(": ", 0).WriteWideString(E.Message, 0).WriteLn();
System.#_IOTest();
System.#ExceptObject = null;
}
}
As you can see the last code call a lot of helper classes and functions (like TextOutput) which are not part of the standard .net framework, rather they are part of the Borland.Delphi.System namespace.
Reflector can help you to translate some snippets of code but not the full application in an automated way.

The answer is no, and even if you deploy the corresponding Delphi assemblies, such as Borland.Delphi.dll and Borland.Vcl.dll, you have structures that have no equivalent in C#, such as class references, that cannot be used within Visual Studio/C#. I managed to convert about 80,000 lines of a non-visual application framework in Delphi to use in Visual Studio/C#, but it took me over 3 months and I had to convert code that used things like class references to use the System.Type class, amongst other things. After all this work, and with the deployment of some basic Delphi assemblies, an Indy assembly, and a Jcl assembly, I can now develop in either Delphi or Visual Studio and maintain communication compatibility between the two types of applications.
One other thing I did is to run some custom pre-processing of the source code before building to strip of the "T..." type prefix so that the actual framework assemblies look just like C# assemblies when used in Visual Studio. This was no easy task but was made possible by the fact that all types, constants, etc in my framework were ALL prefixed as well by either "Csi", "App", "Fwk", or "Dev". Without this I could not have stripped off the Deplhi-specific identifier naming conventions.
Unless there is an overwhelming benefit for doing this which outweighs the cost (like me), and your code is essentially non-visual (like me), the amount of effort involved is likely to be far too great to justify the work. I wonder if I am the only Delphi developer in the world to succesfully have migrated a significant amount of code from Delphi for use in Visual Studio. Nobody else seems to be able to provide a success story like this, which really makes you wonder how feasible this is.

Related

Communication between VBA and C#, with portability and no Admin Privilege

I am trying to write something that would access methods I have written in a WPF c# application, from a vba worksheet, an intermediary would be acceptable, as well as any command line solution, as long as I can run this intermediary from excel where the data I need to send will be kept.
Does anyone know any decent solutions for sending data to a c# without registering the dll, and preferably in a portable way that I can move to other machines easily?
Any help in that matter would be greatly appreciated, I am looking for pointers in the right direction as a COM solution is not viable right now.
Cheers.
You could write a C# Console Application which accepts command-line arguments, then call this using the Shell command.
Here's a sample Console application which handles the input parameters:
using System;
namespace ConsoleAppWithParams
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
foreach (string s in args)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}
Note that the parameters are coming from the command-line, so they are strings. You'd need to validate and convert the parameters if you need other data types.
You can call this from Excel VBA as follows:
Sub UseCSharpApp()
Shell "D:\Documents\ConsoleAppWithParams.exe Tom Dick Harry"
End Sub
If your C# application is fairly straightforward, then the only requirement would be for it to be copied to the expected directory, and for the correct version (or a more recent version) of the .NET Framework to be installed on the PC. If the C# app is written to target .NET Framework 2.0, then it's likely that most Windows PCs in a business environment would be able to use this, but obviously you should check whether that's the case in your environment.
Note that with this approach, you're limited to passing in values when first calling the application. This wouldn't be a useful solution in all scenarios, but might work if that's all you need to do.

Integrating Matlab Coder with c#

I want to integrate MATLAB Coder output with a C# project in Visual Studio 2010. My main idea is:
Create a *.m script in Matlab
Make sure the script is compatible with Matlab Coder.
Generate a C++ shared library (DLL) with Matlab Coder
Integrate with C# using something like this:
//Starts the model execution. May take several minutes
public static class DllHelper
{
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "Run()")]
public static extern int Run();
}
Also, I would like to be able to stop the execution and retrieve some partial results. To do this, I was thinking in two methods: StopExecution and RetrievePartialResults
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "StopExecution ()")]
public static extern int StopExecution ();
[DllImport(#"test.dll",CallingConvention=CallingConvention.Cdecl,EntryPoint = "RetrievePartialResults()")]
public static extern MyResults RetrievePartialResults();
Is it possible to do? If no, is there any alternatives? If yes, where can I find more examples?
I have no idea if your plan works, but MATLAB Builder NE might be an alternative. It directly outputs a .Net dll without those hard limitations to the m-code.
The disadvantage is, that MCR is required on the target machine.
I've done both ways. Formerly, our project was using MATLAB Compiler, but we now switched to Coder, because that avoids the overhead of having to install the runtime (which btw often failed to start inside the process for no apparent reason).
We compile the coder output as an unmanaged C project with a C interface and use a C++/CLR project as a wrapper. This has the advantage that we don't need to manually specify the interface for P/Invoke as the compiler will directly read the header files. The C++/CLR assembly is the linked to the C# project where the code is going to be used. Be aware that this is kind of expensive, so try to avoid calling the matlab code in a tight loop and better move the whole loop into the library if that is possible.
Here's a snippet from the wrapper library (still uses old Managed C++ syntax, but that doesn't matter here)
bool CTurconConnect2::Init()
{
// Call the exported function in the library. Imported using a header file.
turcon_initialize();
// Call one of the matlab functions (in this case, the entry function is manually defined
// in the C library, to have a clean interface)
SetParameters(36.0,400.0,20.0,30.0,15.0,40.0,110.0, 0.0, 100.0);
return true;
}
bool CTurconConnect2::Exit()
{
turcon_terminate();
return true;
}
I think your plan of writing a DLL and calling it from c# seems to be one of the two main ways to go.
The alternative would be to:
use the MATLAB as an automation server from C# using the engine
interface via com automation. This allows you to simultaneously debug
your C# application from both the C# side and the MATLAB side, using
debuggers on each side.
Here are examples for both methods, and even a third alternate method (that seems less recommended).
Integrating MATLAB with C# on File Exchange
I've achieved the exact functionality you're asking about using the MATLAB Compiler. I don't have any experience with the MATLAB Coder, but should be the same principle. Once you have a MATLAB Library compiled, you can access it using P/Invoke in C# like you would with any other unmanaged library (and as you specified in your question).
Theres a couple of caveats:
I think you might have an issue design-wise trying to successfully implement your "stop execution" strategy. The MATLAB executables/libraries are meant to execute from start to finish without much control over the runtime. If you can split your script up into multiple pieces to handle that design, that may work better.
Compiled MATLAB libraries require you to "Start" and "Stop" the MATLAB Component Runtime manually, as well as a component runtime for each script. So, execution flow, would be something like:
StartMCL();
StartScript1_Runtime();
Run_Script1();
StopScript1_Runtime();
StopMCL();
If you attempt to run the "Script 1 Runtime" prior to starting the overall MCL, the app will crash. So, you need to be careful with how you design the wrapper class to handle that properly. Also, you want to be sure to Stop everything before exiting your app, otherwise, the MCR will effectively see 2 "Runs" in a row, and will crash.
You didn't cover any input/output arguments in your question, but in most cases, you will need to use MATLAB functions to create the MEX variables to hand data in/out of the MATLAB environment.
There is a great set of sample source here that should cover all of the above:
http://www.mathworks.com/matlabcentral/fileexchange/12987-integrating-matlab-with-c
Also, the Compiler help itself has a bunch of useful resources.
http://www.mathworks.com/help/compiler/shared-libraries.html
So in a list form,
I doubt that you will be able to stop the matlab code unless you break it up into multiple functions, which you may call as needed.
That you should be able to halt execution by calling on a thread and stopping the thread as you need, or better, send a signal for the thread to stop, which it will abort between functions (for the purpose of partial results)
That matlab is a terrible language for fulfilling the requirements on item 1 (not that I have ever had any good experiences with it myself)

How to utilise C# methods in a different programming language

I am attempting to connect to a commercial server application, which only has a C# API.
I would imagine that the best approach for doing so would be to create a C# DLL - which is what I have done. However, when examining the methods contained within the DLL utilising 3rd party tools, the methods do not seem to be visible.
I have searched extensively on StackOverflow, and found that the following suggestion works for most people - however the methods are still not visible when utilising this extension.
Thus it may be time to seek an alternate approach to how this problem can be solved - one option could be a C# console application.
Any ideas regarding what would be the best approach?
EDIT:
After running the DUMPBIN program, this is the output:
C:\Program Files (x86)\Microsoft Visual Studio 11.0>dumpbin /EXPORTS "C:\Users\mark\Desktop\Test.dll"
Dump of file C:\Users\mark\Desktop\Test.dll
File Type: DLL
Summary
2000 .reloc
2000 .rsrc
2000 .text
If the Basic+ has an option to call C code, you have an option to create a project in Managed C++:
Exports some function decorated like:
extern "C"{
__declspec(dllexport) void _cdecl MyFunction()
{
_MyImpl(); //see below wy this
}
}
void MyImpl()
{
MyCSharpObj^ test = gcnew MyCSharpObj()...
test->Methods(...
}
Outside of the portion decorated with extern C you can safely call and mix managed and unmanaged calls. The reason you should go outside the extern C block is that almost all managed function have overloads, and Extern C does not support method overloading even in call.
You can call c# by just adding references ( actually you can write all your code in managed C++, but is not so friendly ) to your .NET libraries.
Basic+ seems to be made by Revelation Software.
On this page, it says:
OpenInsight 9.1 released
This new OpenInsight release included a
couple of .NET innovations. NetOI enables developers to code using
their Microsoft Visual Studio licenses and work against an OpenInsight
database. The RevDotNet functionality provides a method of calling
.NET APIs and using the .NET controls within an OpenInsight
application.
Can you use RevDotNet to call your C# APIs directly?

how to convert C# to C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Could someone please help me to convert C# to C++? here is an example:
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace read_website
{
class Program
{
static void Main(string[] args)
{
while (true)
{
DownloadString("http://www.xxx.asp");
Thread.Sleep(100);//update every 100 millisecoand
}
}
public static void DownloadString(string address)
{
WebClient client = new WebClient();
string website = client.DownloadString(address);
get_Current_X1_value(website);
}
static void get_Current_X1_value(string web)
{
int x = web.IndexOf("Current X1 value:");
string part1 = web.Substring(x, 100);
string[] array = part1.Split('>', '<');
for (int i = 0; i < array.Length; i++)
{
if (array[i].Contains("Current X1 value:"))
Console.Write(array[i]);
if (array[i].Contains("W"))
Console.WriteLine(array[i]);
}
}
}
}
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Have you considered Mono? It is something that's definitely worth checking before starting to learn C++ in order convert and run an existing .NET application on Unix. It's also binary compatible meaning that you don't even need to recompile your existing assembly.
Learn C#, learn C++, and spend a lot of time rewriting.
Or use PInvoke from the C# assembly to call into a C++ dll.
Or write managed C++ and compile with the /clr switch. The resulting assembly can be referenced and used from C# projects.
It is nearly impossible to directly translate C# to C++ so that it will run on Unix machines.
This is mainly due to the fact that the .NET Framework is not available (from C++) on Unix machines. Mono will allow you to run many C#/.NET programs, but does not support C++/CLI (the C++ extensions that allow directly working with the .NET Framework).
Converting the language is possible - though difficult due to differences in approach (e.g., garbage collection in C#), but the framework calls will require porting to different libraries, and it is often not a good candidate for a direct translation.
For example, in your code above, you'd have to decide on a C++ library for web access - and once you had that choice made, it would dictate the code required to call into that library to download the website string.
I'm using C# to C++ converter time to time. It's really great for snippet conversion from c# to c++ or c++/cli.
Consider looking at Vala. Vala is a C#-like language that converts into C and then into an executable. There are very little differences with C#. You will still have to use your brain though.
You may want to consider CoreRT. It's a .NET project whose goal is to eliminate the need for the CLR to be present on the target platform for running an application. Instead, it generates C++ code from a given C# code. That C++ code is compiled and linked on any target platform that supports C++.
A post on a Microsoft blog said: "If I really want to write some C# code and have it 'just work' on a new IoT device, I don’t have any options until the RyuJIT is capable of generating machine code that works with that processor and operating system." By cross-compiling C# to C++, .Net developers can then deliver their applications without needing to wait for .Net to be deployed on a given platform.
https://github.com/dotnet/corert
Edit:
The site listed has been discontinued. I'll leave the old answer here for reference ...
Old answer:
Here is an online converter that will automate the process for you! ...
Varycode online converter
It can do C# to C++ and back again as well as converters for Ruby, Python, Java & VB, apparently!
Edit:
It appears to have had its C++ (and java) functionality removed - it says temporarily, but has done so for a long time now. Hopefully they'll resurrect it soon!
Still works for some other languages (VB, Ruby, Python, Boo).
As already mentioned here, the translation of libraries can be an issue, but one open source project that might help at some cases is:
http://alexalbala.github.io/Alter-Native/
Citation from its main page:
It provides a tool to easy port applications
from high-level languages such as .NET to
native languages like C++. It is a research project
and it is under development with the
collaboration of UPC - BarcelonaTech and AlterAid S.L.

How to avoid .NET DLL files from being disassembled? [duplicate]

This question already has answers here:
How can I protect my .NET assemblies from decompilation?
(13 answers)
Closed 6 years ago.
I am writing a .NET application (a Windows class library) for implementing the licensing our product.
The problem is that the DLL can be easily disassembled by the MSIL disassembler or any other third-party tools and one can easily break the code.
I have even tried signing the assembly, but still it can be disassembled.
So how do I prevent this?
Is there any tool to available for this?
Check out the answers for this question.
You cannot achieve complete protection, but you can hinder disassembly in ways that make it more difficult for people to succeed at it. There are more ways to do this, some of them detailed in the answers to the question in my link above:
Obfuscate your code.
Use public/private key or asymmetric encryption to generate product license keys.
Use a packer to pack your .NET executable into an encrypted w32 wrapper application.
What I would add would be incremental updating, both for your core functionality and the protection code, so your users will constantly benefit from the new features while making crackers lag behind you in breaking your software. If you can release faster than they can break and distribute your software, you are in gain. Legitimate users will always have technical support and a word to say regarding new features. They are your best market, as the ones who crack your software wouldn't have payed for it anyway.
You can't, but you can use an obfuscator so that it's impossible to make sense out of your code.
For example, have a look at Dotfuscator.
The community edition of this program is included with Visual Studio.
.NET has an attribute called SuppressIldasmAttribute which prevents disassembling the code. For example, consider the following code:
using System;
using System.Text;
using System.Runtime.CompilerServices;
[assembly: SuppressIldasmAttribute()]
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world...");
}
}
}
As you can see, there are just two differences:
We have added System.Runtime.CompilerServices namespace decleration.
We have added [assembly: SuppressIldasmAttribute()] attribute.
After building the application in Visual Studio, when we try to open the resulting EXE file in ILDASM, now we get the error message.
Anything written for the .NET framework is subject to disassembly. You cannot prevent it.
There are obfuscation tools available that will change variable names and insert other 'noise' into your IL, for instance Dotfuscator.
You might want to consider taking another approach with your licensing library, that is, using something else other than .NET, if licensing your product is absolutely necessary.
As mentioned above in the selected answer, there is no true full proof way to secure you code.
Even in something like c++, if your applications code is in your customers hands : Eg - they have physical access to the binary, that application could potentially be disassembled.
The solution would be to keep the functionality that you are licensing, out of reach of people who may want to disassemble it, let them use it, but don't let them hold it.
Consider using :
Web Services
Keep your marketable content server side and beyond the reach of your clients. They can use it, but not examine the code.
Encrypted Binaries and Online Binaries
Maybe even streaming assemblies in an encrypted format to a wrapper application. Keep your decryption keys server side to prevent offline disassembly. This might be circumvented however if someone found a way of exporting the assembly from the app domain of the application, once it has loaded it. (You cannot load an encrypted binary, so an end user might wait until your application has done the work of decryption, then exploit that to export the finished binary) (I was investigating a way to accomplish this (the exporting) - I didn't quite get it working, doesn't mean someone else wont)
The only thing to remember is that ANY code, no matter how well coded it may be, is vulnerable if it is on a users system. You have to assume the worst when you put binaries on their system. A really talented Engineer can disassemble any dll, be it c++ or c#.

Categories

Resources