How to add a link to C # Script

I use the CS-Script library to execute dynamic code. Instead of using it as a script engine, I want to use it to incorporate functionality into the application on the fly. Here's the hosting code ...

using System; using CSScriptLibrary; using System.Reflection; using System.IO; namespace CSScriptTester { class Program { static void Main(string[] args) { // http://www.csscript.net/ Console.WriteLine("Running Script."); CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox))); string code = File.ReadAllText("SomeCode/MyScript.cs"); dynamic block = CSScript.Evaluator.LoadCode(code); block.ExecuteAFunction(); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } } 

And here is the contents of SomeCode / MyScript.cs ...

 using System; using System.Windows.Forms; namespace CSScriptTester.SomeCode { class MyScript { public void ExecuteAFunction() { MessageBox.Show("Hello, world!"); } } } 

It works great. In the hosting code, I do not want the hosting code to be responsible for specifying assembly links. So I comment on CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox))); and run it and I get an error ...

error CS0234: Type or namespace name Forms' does not exist in the namespace System.Windows'. Are you missing an assembly link?

I know, if I were doing this using the command line tools, I could add this to the top of the script to add the link ...

 //css_reference System.Windows.Forms.dll 

But this seems ignored when executed in the context of a .NET application. How can I get it to resolve links correctly?

+6
source share
2 answers

Figured it out.

 string code = File.ReadAllText("SomeCode/MyScript.cs"); CSScript.Evaluator.ReferenceAssembliesFromCode(code); dynamic block = CSScript.Evaluator.LoadCode(code); block.ExecuteAFunction(); 

I am surprised that he does not automatically do this.

+3
source

I solved it differently, I set the necessary Copy Local link assemblies to true and uploaded them to my Evaluator before loading my scripts.

I recommend doing this because it will precompile and store downloaded assemblies that speed up the loading of ad-hoc scripts. Instead of looking for reference assemblies from the GAC or elsewhere every time the script is loaded, it just has them and loads the script as efficiently as possible.

 CSScript.Evaluator.ReferenceAssembly("<local path to dependency>.dll"); IScript script = CSScript.Evaluator.LoadFile<IScript>("<local path to script file"); 

Where the "local dependency path" is simply the name of the referenced object, which can be found as the "Description" string of any referenced assembly in your project.

0
source

All Articles