Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add a Reference to a C# Script

Tags:

c#

cs-script

I am using the CS-Script library to execute dynamic code. Rather than using it as a script engine, I want to use it to plug functionality into an 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's the contents of SomeCode/MyScript.cs...

using System;
using System.Windows.Forms;

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

This works fine. In the hosting code, I don't want the hosting code to be responsible for specifying assembly references. So I comment out CSScript.Evaluator.ReferenceAssembly(Assembly.GetAssembly(typeof(System.Windows.Forms.MessageBox))); and run it and I get the error...

error CS0234: The type or namespace name Forms' does not exist in the namespaceSystem.Windows'. Are you missing an assembly reference?

I know if I were executing this using the command line tools I could add this to the top of the script to add the reference...

//css_reference System.Windows.Forms.dll

But that seems to be ignored when executing it in the context of a .NET Application. How can I get it to resolve the references properly?

like image 539
mason Avatar asked Apr 07 '14 15:04

mason


1 Answers

Figured it out.

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

I'm surprised that it doesn't automatically do this.

like image 112
mason Avatar answered Oct 23 '22 04:10

mason