code snippets interpretation - c#

Let's say I have a WinForm App...written in C#.
Is it possible?

After all, put my eye on Iron Python.

C# is not interpreted, so unlike javascript or other interpreted languages you can't do that natively. You can go four basic routes, listed here in order of least to most complex...
1) Provide a fixed set of operations that the user can apply. Parse the user's input, or provide checkboxes or other UI elements to indicate that a given operation should be applied.
2) Provide a plugin-based or otherwise dynamically defined set of operations. Like #1, this has the advantage of not needing special permissions like full trust. MEF might come in handy for this approach: http://mef.codeplex.com/
3) Use a dynamic c# compilation framework like paxScript: http://eco148-88394.innterhost.net/paxscriptnet/. This would, in theory, allow you to compile small c# snippets on demand.
4) Use IL Emit statements to parse code and generate your operations on the fly. This is by far the most complex solution, likely requires full trust, and is extremely error prone. I don't recommend it unless you have some very obscure requirements and sophisticated users.

The CSharpCodeProvider class will do what you want. For a (VERY outdated, but still working with a few tweaks) example of its use, check out CSI.

If you are willing to consider targeting the Mono runtime, the type Mono.CSharp.Evaluator provides an API for evaluating C# expressions and statements at runtime.

Related

Is it possible to add keyword to C# or VB.NET?

I know it might not be worth it but just for education purposes I want to know if there is a way to inject your own keywords to .NET languages.
For example I thought it's good to have C++ asm keyword in C#.
Remember I'm not talking about how to implement asm keyword but a general way to add keyword to C#.
My imagined code :
asm{
mov ax,1
add ax,4
}
So is there a way to achieve this ?
The answers which cover implementing keyword{ } suits enough for this question.
This isn't possible at the moment. However, there's a Microsoft project in development called Roslyn that can be summarised as "the compiler as a service." It allows you, amongst other things, to extend or modify the behaviour of the compiler through an API.
When Roslyn becomes available, I believe this should be something that (with caution!) is quite doable.
You can use whatever tools you would like to pre-process your code before sending it to the C# compiler. For example, you might use VS macros to do the pre-processing, mapping a given syntax that you invented into something that does compile into C# code, possibly generating an error if there is a problem. If VS macros aren't powerful enough for you then you can always use your own IDE that does whatever you code it to do to the text before sending it to the compiler.
There is no built in support in the compiler for specifying your own keywords/syntax; you would need to handle it entirely independent of the compiler.
Unfortunately this is not possible. You can't extend or alter the languages in any way.
You could in some obscure way use PostSharp to read and parse strings and transform them to custom code at compile time (a pre processor). But you would not get very happy with that, as it is very error prone and you won't get any kind of intellisense or code completion for your magic strings.
According to MSDN keywords are predefined and cannot be altered. So you can't add any, because you would need to tell the compiler how to handle them. Insofar, no you can't.

Is it possible in C# to provide an IComparer implementation and somehow have it "compiled" into the application at runtime?

Hi everyone I am not sure if what I want to do is even remotely possible but I am going to do my best to explain it and would really appreciate any suggestions / ideas,
Imagine I have :-
public class Attribute{
object Value;
**(X1)**IComparer<T> comparer
}
public class AttributeValues
{
List<Attribute> values;
SortedList<Attribute> Sort(){
this uses the comparer defined in **(X1)** to sort the values in the list
}
}
These classes allow the user to create user defined attributes and select a pre-defined sort algorithm to sort the values
In the simplistic case, I can do AttributesValues.Sort() using one of the comparers that I have created and compiled in source code which has been chosen by the user. This is fine when the comparison is known in advance such as a simple ascending alphabetical sort for example.
However, there are some circumstances where more logic is needed and it is not known in advance. For example, the string "4DFG5ET" might codify a date that needs to be sorted and there may be some other attribute with similar logic and so on.
If possible I don't want to keep writing the IComparer implementations and would love for it to be possible that somehow I could define the IComparer implementation in a text box or file at runtime and it would be somehow compiled in the program or persisted then available in the selction of comparisons that could be used to sort an attribute.
Does anyone have any suggestions on how to approach this?
Please ask if you would like me to clarify something as I know it is a slightly obscure question.
Many thanks in advance
Alex
Sure, there are several different technologies that support that. Reflection.Emit comes to mind, and since the .NET framework includese a compiler you should also be able to emit C# and compile that on the fly to an assembly that you then load. There are more options in the new dynamic languages space, I believe.
You can make use of CSharpCodeProvider (see documentation here) to compile the provided text into a DLL and load the resulting class using reflection.
Also, this SO question might be of good help for you
I think you can use MEF for that:
quote:
"The Managed Extensibility Framework (MEF) is a composition layer for .NET that improves the flexibility, maintainability and testability of large applications. MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications."
As I see it, you have two options. First, you can construct your own language which can parse simple user commands and then execute the code in JIT fashion.
The second option is to actually let your users write C# code and the compile it on the fly. (As previously mentioned, Reflection.Emit should take care of most simple needs.)
EDIT
A third option isn't exactly what you wanted, but you could setup a directory for comparer plugins. When your application starts, it can scan that directory and load the assemblies. Using Reflection, you can extract any classes that implement the IComparer interface, then provide them as a list to the user. (You could also use custom attributes to define friendly user names and descriptions, etc).
In this case, you would not need to recompile your entire application just to quickly add some new comparer. Also, if you have a superuser, they could use some free .NET code editor to quickly write up their own comparer and "install" them to the directory.

Tool for 'Flattening' (simplifying) C# Source

I need to provide a copy of the source code to a third party, but given it's a nifty extensible framework that could be easily repurposed, I'd rather provide a less OO version (a 'procedural' version for want of a better term) that would allow minor tweaks to values etc but not reimplementation using the full flexibility of how it is currently structured.
The code makes use of the usual stuff: classes, constructors, etc. Is there a tool or method for 'simplifying' this into what is still the 'source' but using only plain variables etc.
For example, if I had a class instance 'myclass' which initialised this.blah in the constructor, the same could be done with a variable called myclass_blah which would then be manipulated in a more 'flat' way. I realise some things like polymorphism would probably not be possible in such a situation. Perhaps an obfuscator, set to a 'super mild' setting would achieve it?
Thanks
My experience with nifty extensible frameworks has been that most shops have their own nifty extensible frameworks (usually more than one) and are not likely to steal them from vendor-provided source code. If you are under obligation to provide source code (due to some business relationship), then, at least in my mind, there's an ethical obligation to provide the actual source code, in a maintainable form. How you protect the source code is a legal matter and I can't offer legal advice, but really you should be including some license with your release and dealing with clients who are not going to outright steal your IP (assuming it's actually yours under the terms you're developing it.)
As had already been said, if this is a requirement based on restrictions of contracts then don't do it. In short, providing a version of the source that differs from what they're actually running becomes a liability and I doubt that it is one that your company should be willing to take. Proving that the code provided matches the code they are running is simple. This is also true if you're trying to avoid license restrictions of libraries your application uses (e.g. GPL).
If that isn't the case then why not provide a limited version of your extensibility framework that only works with internal types and statically compile any required extensions in your application? This will allow the application to continue to function as what they currently run while remaining maintainable without giving up your sacred framework. I've never done it myself but this sounds like something ILMerge could help with.
If you don't want to give out framework - just don't. Provide only source you think is required. Otherwise most likely you'll need to either support both versions in the future OR never work/interact with these people (and people they know) again.
Don't forget that non-obfuscated .Net assemblies have IL in easily de-compilable form. It is often easier to use ILSpy/Reflector to read someone else code than looking at sources.
If the reason to provide code is some sort of inspection (even simply looking at the code) you'd better have semi-decent code. I would seriously consider throwing away tool if its code looks written in FORTRAN-style using C# ( http://www.nikhef.nl/~templon/fortran/fortran_style ).
Side note: I believe "nifty extensible frameworks" are one of the roots of "not invented here" syndrome - I'd be more worried about comments on the framework (like "this code is ##### because it does not use YYY pattern and spacing is wrong") than reuse.

Dynamicaly extensible generic parser

I wrote an application which makes use of a meta-parser generated using CSharpCC (a port of JavaCC). Everything works fine and very good I can say.
For the nature of the project, I would like to have more flexibility on the possibility to extend the syntax of the meta-language used by the application.
Do you know any existing libraries (or articles describing the process of implementation) for Java or C# which I could use to programatically implement my own parser, without being forced to rely to a static syntax?
Thank you very much for the support.
Would Scala's combinator parsers do the trick for you? Since Scala compiles to Java bytecode, anything you write could be called from your Java code however you please.
Take a look at the way that the JNode command-line interface handles parsing of command line arguments. Each command 'registers' descriptors for the arguments it is expecting. The command line syntax is specified separately in XML descriptors, allowing users to tailor a command's syntax to meet their needs.
This is underpinned by a framework of Argument classes that are basically context sensitive token recognizers, and a two level grammar / parser. The parser 'prepares' a user-friendly form of a command syntax into something like BNF, then does a naive backtracking parse, accepting the first complete parse that it finds.
The downside of the current implementation is that the parser is inefficient, and probably impractical for parsing input that is more than 20 or so tokens, depending on the syntax. (We have ideas for improving performance, but a real fix is probably not possible without a major redesign ... and banning potentially ambiguous command syntaxes.)
(Aside: one motivation for this is to support intelligent command argument completion. To do this, the parser runs in a "completion" mode in which it explores all possible (partial) parses, noting its state when it encounters the token / position that the user is trying to complete. Where appropriate, the corresponding Argument classes are then asked to provide context sensitive completions for the current "word".)
The parser (written in C#) used in the Heron language (a simple object-oriented language) is relatively simple and stable, and should be easy to modify for your needs. You can download the source here.

Where would you use C# Runtime Compilation?

I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.
Thanks much.
Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you.
You can use this to add scripting support to your application. For examples look here or here.
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could with relative ease add something to your application that has the same effect as for example VBA for Office.
I've seen this (runtime compilation / use of System.Reflection.Emit classes) in generating dynamic proxies ( Code project sample ) or other means of optimizing reflection calls (time-wise).
At least one case you might use it is when generating dynamic code. For example, the framework is using this internally to generate XML serializers on the fly. After looking into a class at runtime, it can generate the code to serialize / deserialize the class. It then compiles that code and users it as needed.
In the same way you can generate code to handle arbitrary DB tables etc. and then compile and load the generated assembly.
Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.
I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.
IMyProxy : IXmlRpcProxy
{
[XmlRpcMethod]
int Add(int a, int b);
}
Then in my code I call something like
IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:
int result = proxy.Add(1, 2);
This then handles the XML-RPC call for me. Pretty cool.
I used runtime compiler services from .NET in my diploma thesis. Basically, it was about visually creating some graphical component for a process visualization, which is generated as C# code, compiled into an assembly and can then be used on the target system without being interpreted, to make it faster and more compact. And, as a bonus, the generated images could be packaged into the very same assembly as resources.
The other use of that was in Java. I had an application that had to plot a potentially expensive function using some numerical algorithm (was back at university) the user could enter. I put the entered function into a class, compiled and loaded it and it was then available for relatively fast execution.
So, these are my two experiences where runtime code generation was a good thing.
something I used it for was for allowing C# and VB code to bu run by the user ad-hoc. They could type in a line of code (or a couple lines) and it would be compiled, loaded into an app domain, and executed, and then unloaded. This probably isnt the best example of its usage, but an example of it none-the-less

Categories