invoke bridge.net compiler at runtime - c#

I am designing an application that will need to create some C# classes at runtime. I would like to be able to convert those classes into javascript equivalents. For example I might have a C# class that looks like
public class Person
{
public int Score { get; set; }
public bool IsScoreValid()
{//code in real implementation would be more complex and make use of various properties
return Score > 0 && Score <= 100;
}
}
The trick here is that the Person class here will be created at runtime based on some configuration. I do not have control over the code in the IsScoreValid method and it could change while the application is running. I only know that it is valid C# code. I need a robust way to convert this class into a javascript equivalent, and I need to be able to perform this conversion at runtime. Would Bridge.net be a good way to convert this javascript? Can Bridge.net compiler be invoked at runtime?

If it is possible? It indeed is, see http://deck.net/. But unfortunately the project is not open source. Basically it is a project that directly calls Bridge.Translator.Translate() method with the right parameters to build the file.
A web project implementing real time bridge compilation would need to be capable of handling server-side calls, like webservices (ashx) in Asp.NET, but you can also do that via cgi-bin or php from linux/osx, using the Bridge CLI if you make commandline calls, or wire up a wrapper to call Bridge.Translator directly. That would need to be a Mono-capable binary to be linked against Bridge.Translator on Linux/osx though.
While the deck.net project is not open, Bridge itself is, so you have full access to see how to call Bridge's Translate() method from either the Bridge.Builder or Bridge CLI open projects.
Bridge Builder console app sources at Bridge main repository
Bridge Translator sources at Bridge main repository
Bridge CLI sources
But if you want the code not to care about references, like missing the definition or a prototype for IsScoreValid(), then that would be a problem to work with Bridge. It would require at least the method to be prototyped and marked External before it could accept the call; as the code tree is built thru roslyn, the c# code must be complete and buildable. (or else, could we call it proper C#? maybe, in your case, you don't really require full-fledged C#)

Related

How are APIs or Frameworks made, so scripts can use their functions but you cannot see the code?

I was wondering how I could program like a certain API, I have written an algorithm that I want to publish so people can use it, but I don't want people to see the code, and steal it? Paranoid, I know, but still.
How is that made, so for instance I can in a C# script (the API would also be written in C#), include it (with using ApiName) and use the functions inside, for instance if the API has a function that I program like "void Calculate(float x, float y)", and then from a script they can call "Calculate(100, 200)" for instance. I know it's somehow possible because of the Windows API, etc. Also is creating a Class Library the same thing?
Before any code runs, it is either compiled or interpreted into binary. This is highly simplified but that is the general idea. As long as a library or API provides an interface like names of functions, the implementation itself can be compiled and still work.
For C#, NuGet is a good example, you can create a NuGet of your code (see https://learn.microsoft.com/en-us/nuget/create-packages/creating-a-package) where the public function and method signatures will be visible and usable but the implementations will be compiled. DLLs work in a similar way. You can reference them and call their public members but not see the code unless you use a tool to decompile them.

C# classes exposed from javascript through Firebreath Framework

I need to create the classes in C# and call that classes from javascript through C++CLI and Firebreath Framework .. create the complex hierarchy class structure and expose it from javacsript
The flow should be :
Javascript <-- C++(FireBreath)<-- C#
C#-->C++(Firebreath)-->Javascript
I have to create the generalized solution for this problem.
Then how should i implement this? If you have any solution,sort of information ,ways to solve this problem then please let me know..
Suppose my Class Library in C# which includes the classes like :
public class TestImage
{
}
public class DrawImage
{
public void ShowImage(TestImage testImage)
{
}
}
Here I need to call ShowImage(TestImage testImage) method from JavaScript page of Firebreath Framewaork.
I already created the wrapper but I dont have an idea to expose the class object as argument to the method like the above ShowImage () in tjhe JavaScript page of the Fireabreath Framework.
If you have any idea related to this please let me know.
When you say "generalized solution"... do you mean a tool or process that automates this?
I believe this is possible. Here's how I would do it:
I'm assuming you have gotten started with FireBreath and have some understanding of it. I'm glossing over countless problems you'll run into integrating all this within a FireBreath solution; that would take days! So this is just architectural advice. I'm sorry to omit so many details.
I would write a tool that dynamically loads your .NET assembly or assemblies, and uses reflection to traverse the 'complex hierarchy class structure'. This tool would generate two things: A C++/CLI wrapper for your .NET library, and a set of native C++ FireBreath classes that bind from Javascript to that C++/CLI wrapper.
The C++/CLI wrapper (see enter link description here) makes your .NET library callable from the native C++ of FireBreath.
Actually, here is a tool on CodePlex that claims to generate such a wrapper.
The Javascript adapter is a set of .cpp modules (probably one for each of your library/C++/CLI classes). Each of these is a C++ class derived from FB::JSAPIAuto, which allows these classes to be instantiated as Javascript objects. Within the constructor for each of these classes, the automated tool inserts code to create the object's Javascript API. Code that looks like this:
registerMethod("Start", make_method(this, &thisClass::Start));
registerMethod("Abort", make_method(this, &thisClass::Abort));
registerProperty("Size", make_property(this, &thisClass::get_Size,&thisClass::set_Size));
The automated tool must synthesize these methods of the class, like thisClass::Start and thisClass::set_Size. Their parameters and return types are the Javascript-compatible types supported by FireBreath - like int and double and bool, but also std::string, FB::VariantMap and FB::VariantList. In the body of each such method, the tool generates code to call the corresponding C++/CLI wrapper API, doing any necessary conversion between parameters and returns.
I suppose that each FB::JSAPIAuto-derived class inherits from, has as a member, or holds a pointer to, the C++/CLI class/object it represents.
As a FireBreath project, your .NET library is ultimately represented by a GUID - this is how Javascript finds its way into your library, by creating a root object from that GUID. It then calls methods or reads properties of that object to get other objects, and so on to access your entire library API.
I suppose there will be some issues mapping between Javascript and C#. You will have to study the Javascript parameter and return types supported by FireBreath, and limit your C# API accordingly. Probably key is figuring out how Javascript objects and arrays are represented as they cross the C++/CLI layer.
I've just achieved something like this using COM. I exposed the C# library as a COM object, then wrote a couple of wrapper functions which called this library in FireBreath. (I was lucky thought I had a very simple API).

if __name__ == "__main__": equivalent in C#

With python, I can use if __name__ == "__main__": for using the module both as a library and a program.
Can I mimic this feature in C#?
I see a class in C# can have a 'static void Main()', but I'm not sure if every class can have a Main() without a problem.
ADDED
/m:CLASS_NAME is a way to specify the class to run the Main().
You can put a Main method in as many classes as you like, although only one can be an entry point for an application. (For talks, I often have a main method in every class, and use a helper library to present all of those pseudo-entry-points when I run the project.)
Likewise you can definitely add a reference to a .exe assembly and treat it like a library. For example, you could make a unit testing assembly work like a class library in most cases, but also write a main method so that you could just run it to execute the tests without a GUI or whatever.
You can compile a C# project as a program (executable) with a Main() method, and you'd still be able to use it as a library. No special syntax required.
You could add a Main() method to every class, but I doubt it's useful.
.NET applications usually have different structures than Python ones; trying to fit the same programming model is unlikely to get you good results.
C# project files specify a startup object when multiple entry points are available.
See this article for more info.

How to Communicate DLLs in C#

That's what I wanna achieve :
There will be dll which contains only methods which calls my actual methods from my application and I can share that dll with outside world regardless of which methods it includes because actual methods will be in the dll in my application but if some one uses that outside dll he/she can manages to get my application to do something in limits of I desire.
I hope I could describe what I want. I don't know if you have ever used Skype4COM.dll. It actually works like that, it somehow connects to Skype Client and let me call some one I want. For example :
Skype s = new Skype();
s.PlaceCall("phoneNumber");
I import Skype4COM dll in my project and when i write code like above in C#, it connects to Skype and make a call.
I think there is no actual methods which makes calls in Skype4Com.dll. I think it only does have some sort of methods which reach actual methods in Skype API and make the call so whatever the developers change in Skype, it doesn't affect Skype4Com.dll wrapper as long as signature stays the same.
So, that's what I want to achive, I am not quite interested in writing wrappers tho, that was a sample case, I want to write a dll which reachs my API and uses method signatures and let people use the application from outside so as long as the signatures stay same, if I want to change something between block I don't need to change the dll given out to outside..
Thank in advance....
If I understand you correctly, you want to expose a limited subset of the functions of your application to outside users. In effect, you want to offer a service, but nothing else.
Then you should use Windows Communication Foundation to host a service inside of your application (or elsewhere). This service could use industry-standard protocols like SOAP; or could use REST; or it could use faster binary transfers over TCP/IP for your .NET clients.
It's perfect for a service-oriented situation like yours.
What you're describing is a COM wrapper around Skype. If you really want a COM wrapper around your C# DLL, you can do that. Microsoft has provided an example that demonstrates how to create a COM Class from C#.
If you're looking into providing a wrapper around your code from managed DLLs, then it's as simple as providing a public interface that consumers of your DLL can use. You'll probably also want to install your code in the GAC (Global Assembly Cache) so that anyone that wants to call into your API can do so without putting copies of your code all over their system.
You could make everything internal instead of public inside this DLL. Internal keyword restricts access to classes, methods or properties to assembly while public keyword allows access from other assemblies

Plugin based application in C#

I have to make a graphical user interface application using the language of my choice. The application will run on Windows XP. It will be some sort of a complex windows form application.
I think and as per most suggestions, C# will be the best to use.
The tree structure on the left of the GUI will populate after reading from a configuration file which will be a binary file . (but initially I can work with a simple ASCII file to test my code.). The application will accept some inputs from the user through this GUI and will write the back to the same config file and will reflect the changes in the tree structure or the labels or any other pertaining field on the form.
There will be 3 tabs and 3 corresponding config files for each of the tabs.
I need some help designing the application for now. I am planning to make a host application (main application) and use the 3 tab controls as plugins. Is this workable ? If so can you please guide me on this. I mean how do I make 3 plugins in C# and how do I write the interfaces so that the main application knows which plugin to load and when to load it ? Will there be a separate “Plugin” folder under my project folder ? I hope you got my point though this is too little of an information for you to begin with.
Also there are some .cpp files already existing in the project. These files along with some .h files contain some important definitions and constants in them. These need to be integrated with my C# application. I have no clue how to do that but I am sure that it is possible by compiling the .cpp code in a .dll and then exposing the compiled .dll to my C# application. Please let me know if you need some more information for the top level design.
Thanks,
Viren
To implement a plugin interface manually, you will need a method something like this. I've left some TODOs in, where you would want to enhance the error handling and/or make the implementation a little more case specific.
public List<T> LoadPlugin<T>(string directory)
{
Type interfaceType = typeof(T);
List<T> implementations = new List<T>();
//TODO: perform checks to ensure type is valid
foreach (var file in System.IO.Directory.GetFiles(directory))
{
//TODO: add proper file handling here and limit files to check
//try/catch added in place of ensure files are not .dll
try
{
foreach (var type in System.Reflection.Assembly.LoadFile(file).GetTypes())
{
if (interfaceType.IsAssignableFrom(type) && interfaceType != type)
{
//found class that implements interface
//TODO: perform additional checks to ensure any
//requirements not specified in interface
//ex: ensure type is a class, check for default constructor, etc
T instance = (T)Activator.CreateInstance(type);
implementations.Add(instance);
}
}
}
catch { }
}
return implementations;
}
Example to call:
List<IPlugin> plugins = LoadPlugin<IPlugin>(path);
As for the c++ part of your question. There are few different ways you could approach this, though the correct choice depends on your specific situation. You can make a clr compliant .dll in c++, which your c# project could reference and call like any other .dll it references. Additionally, you could use P/Invoke to call into a native .dll.
One of the easiest plugin concepts I have ever used was certainly the Managed Extensibility Framework which will be part of .NET 4 (afaik). Unfortunately it is not yet finished and only a preview is available which may differ from the final version. That being said, we used MEF Preview 3 for a uni project and it worked without problems and it certainly made the whole plugin stuff a lot easier.
Look at the System.Addin namespace :
http://msdn.microsoft.com/en-us/library/system.addin.aspx
Otherwise you can do everything yourself. Before this namespace was available, I used a common interface "IPlugin" that every plugin/addin needed to use. I then had a loader which inspected all the *.dll in a folder then used reflection to check for the interface. I could then create instances of classes which implemented my plugin/addin interface
The cpp files will probably need converting to c#, or you could possibly create a dll to reference.
Take a look to Castle.
.NET Framework use COM model in its guts. See http://blog.caljacobson.com/2007/07/26/creating-a-plug-in-framework-in-c-resources/ for a list of plugin example using this techique.

Categories

Resources