Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not tooo hard ;) I put together a little example. This should help you decide if you want to use dynamic scripts.. or regexes.</p> <p>What you can do is create an interface in your assembly, which your dynamic code will implement:</p> <pre><code>namespace CompileScriptExample { public interface IStringManipulator { string processString(string aString); } } </code></pre> <p>Then create a ScriptRunner class:</p> <pre><code>namespace CompileScriptExample { public class ScriptRunner { public static string RunScript(string scriptCode, string scriptParameter) { CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); //configure parameters CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = false; string reference; // Set reference to current assembly - this reference is a hack for the example.. reference = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); parameters.ReferencedAssemblies.Add(reference+"\\CompileScriptExample.exe"); //compile CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { scriptCode }); if (results.Errors.Count == 0) { IStringManipulator compiledScript=(IStringManipulator)FindInterface(results.CompiledAssembly, "IStringManipulator"); return compiledScript.processString(scriptParameter);//run the script, pass the string param.. } else { foreach(CompilerError anError in results.Errors) { MessageBox.Show(anError.ErrorText); } //handle compilation errors here //..use results.errors collection throw new Exception("Compilation error..."); } } private static object FindInterface(Assembly anAssembly, string interfaceName) { // find our interface type.. foreach (Type aType in anAssembly.GetTypes()) { if (aType.GetInterface(interfaceName, true) != null) return anAssembly.CreateInstance(aType.FullName); } return null; } } </code></pre> <p>}</p> <p>Now all you have to do is create a script string with code that implements your interface like..</p> <pre><code>string myScriptString=@"using CompileScriptExample; public class MyStringManipulator : IStringManipulator { public string processString(string aString) { return aString+aString; } }; </code></pre> <p>and then.. in your code, make use of the ScriptRunner to process your string with your dynamic code:</p> <pre><code>string processedString = ScriptRunner.RunScript(myScriptString, "hello"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload