Using C# as my DSL — is this possible, if so, how?

对着背影说爱祢 提交于 2019-12-24 00:14:59

问题


Is it possible to use C# as a DSL in which the C# source code is edited by the end user in a TextBox, compiled while the application is running, then called by the already-running application?

I ask because in the next few months I will be needing to implement a simple math-crunching DSL (similar to somthing Rachel Lim blogged about at http://rachel53461.wordpress.com/2011/08/20/the-math-converter/ I am focused on the math-processing aspect of her code, not the XAML/Converter aspect). I would lean against just reusing her code because I want to add if-statements and possibly other features. If I can use C# itself, then I get all of the features without having to re-implement them.

If it is possible to do this, what framework or namespace or class would I want to use to accomplish such?

Please note that one thing I would do with the C#-derived DSL is hard-code all necessary using header statements, then remove all using statements entered by the savvy user. The purpose of this is to reduce the prospect of an end user trying to leverage my C#-like DSL into a full-fledged compiler against the wishes of their enterprise policy or without the knowledge of the site administrator. Is my proposed managing of using statements an adequate defense against user mischief?

Finally, if all of the answers up to this point are "yes", then what are the drawbacks of this approach, especially drawbacks of introducing a security vulnerability?

Paul


回答1:


Stackoverflow automatically converts link answers to comments now. How lovely.

Compile and run dynamic code, without generating EXE?

Anyway, the answer lies with Microsoft.CSharp.CSharpCodeProvider




回答2:


Is my proposed managing of using statements an adequate defense against user mischief?

No. You'd have to remove references to fully-qualified classes as well. And then, the user can still use reflection to gain access to classes they have not referred to in either way.

You'll want to create a separate appdomain to contain the user's code, which you can then sandbox appropriately. Here is a relevant article on MSDN, which explains this process in depth.




回答3:


Removing using directives will not help, unless you also find some way to prevent the user from writing e.g. System.Diagnostics.Process.Start("evilprogram.exe"). Doing this (without also preventing property accesses) will require you to use a C# parser.

You might, however, be able to use Code Access Security for this.



来源:https://stackoverflow.com/questions/12964790/using-c-sharp-as-my-dsl-is-this-possible-if-so-how

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!