Exemple #1
0
        public Interpreter()
        {
            _session = Session.Create();

            string path = Environment.CurrentDirectory;
            string semanticLibPath = Path.Combine(path, "SemanticLib.dll");

            _scriptEngine = new ScriptEngine(new[] { semanticLibPath });
            _scriptEngine.Execute("using SemanticLib.Core;using SemanticLib.Plugins;", _session);
        }
Exemple #2
0
 public void Compiler_SystemType()
 {
     var session = new ScriptEngine().CreateSession();
     session.AddReference(typeof (QueryState<EventBase>).Assembly);
     session.AddReference(typeof(Func<int, bool>).Assembly);
     var actual = session.Execute<Func<int, bool>>("i => i == 1");
     actual.Should().NotBeNull("null compilation");
     actual.Invoke(2).Should().BeFalse("Should return false on 2");
     actual.Invoke(1).Should().BeTrue("Should return true on 1");
 }
Exemple #3
0
        static void Main(string[] args)
        {
            //Executing a simple C# statement passed as a string.
            {
                string statement = @"System.Console.WriteLine("" Hello World!!!"")";
                var engine = new ScriptEngine();
                engine.Execute(statement);
            }

            //Previous example does not use any execution context. So there is no sharing of execution context when multiple statements are executed.
            //In other words, one statement does not have access to other statement(variable/functions etc).
            //To share the variable/functions etc declared in one statement , with other statements, a session is used which acts as an execution context.

            {
                var engine = new ScriptEngine();
                var session = Session.Create();
                engine.Execute(@"var statement = ""Hello World!!!"";", session);
                engine.Execute(@"System.Console.WriteLine(statement);", session);
            }
            //Session object worsks as a container and holds the object declared. If you do not pass session object as a second parameter in the Execute(), this code will throw an exception that statement
            //does not exist in the current context.

            //Interaction with the host object -
            //Interaction with the host application means, accessing the value from hosting application which is executing the script.
            //For this, you need an host obejct which expose any thing which need to be passed to the script, by a public property/Function.

            {
                hostObj hostObj = new hostObj();
                var engine = new ScriptEngine(new string[]{ hostObj.GetType().Assembly.Location });
                var session = Session.Create(hostObj);
                engine.Execute(@"System.Console.WriteLine(""File name is ""+GetFileName())",session);
            }
            //In this example, script is accessing a variable calles 'FileName' from the host Application through host object.

            //Executing a Script from a file.
            {
                var engine = new ScriptEngine(new string[] { "System" });
                engine.ExecuteFile(@"Script1.csx");
            }

            Console.ReadLine();
        }
Exemple #4
0
 public void Compiler_CustomType()
 {
     var session = new ScriptEngine().CreateSession();
     Type generic = typeof (Func<,>);
     session.AddReference(generic.Assembly);
     session.AddReference(typeof(EventBase).Assembly);
     var actual = session.Execute<Func<EventBase, bool>>("@event => @event.Type == 1");
     actual.Should().NotBeNull("null compilation");
     actual.Invoke(new Event<int>(1, 1)).Should().BeTrue();
     actual.Invoke(new Event<int>(2, 1)).Should().BeFalse();
 }
Exemple #5
0
        public static void Run()
        {
            ScriptEngine engine = new ScriptEngine();
            int result = engine.Execute<int>("1 + 2");

            Console.WriteLine(result);

            //ScriptEngine engine = new ScriptEngine();
            //Session session = Session.Create();

            //engine.Execute("int i = 21;", session);
            //int result = engine.Execute<int>("i * 2", session);

            //Console.WriteLine(result);
        }
Exemple #6
0
 public static void RunScript(string script)
 {
     Session session = Session.Create();
     ScriptEngine engine = new ScriptEngine();
     engine.Execute(script, session);
 }
        public string Execute(string code)
        {
            var task = Task<string>.Factory.StartNew(() =>
            {
            try
            {
                if (!Validate(code)) return "Not implemeted";

                var e = new Evidence();
                e.AddHostEvidence(new Zone(SecurityZone.Untrusted));

                var ps = SecurityManager.GetStandardSandbox(e);
                var security = new SecurityPermission(SecurityPermissionFlag.NoFlags);

                ps.AddPermission(security);

                var setup = new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory };
                var domain = AppDomain.CreateDomain("Sandbox", e, setup, ps);
                AppDomain.CurrentDomain.AssemblyResolve += DomainAssemblyResolve;
                using (var memoryStream = new MemoryStream())
                {
                    var defaultReferences = new[] {"System"};
                    var defaultNamespaces = new[] { "System" };
                    CommonScriptEngine engine = new ScriptEngine(defaultReferences, defaultNamespaces);
                    var options = new ParseOptions(kind: SourceCodeKind.Script, languageVersion: LanguageVersion.CSharp6);

                    foreach (var ns in defaultNamespaces) engine.Execute(string.Format("using {0};", ns), Session);
                    byte[] assembly = null;

                    var resultCode = engine.CompileSubmission<object>(code, Session);
                    resultCode.Compilation.Emit(memoryStream);
                    assembly = memoryStream.ToArray();

                    //var compilationSubmission = Engine.CompileSubmission<dynamic>(code, Session);
                    //compilationSubmission.Compilation.AddReferences(new AssemblyNameReference("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));
                    //compilationSubmission.Compilation.Emit(memoryStream);

                    domain.Load("mscorlib");
                    domain.Load("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                    domain.Load("Microsoft.Csharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                    domain.Load("Roslyn.Compilers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                    domain.Load("Roslyn.Compilers.Csharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

                    _dynamicAssembly = Assembly.Load(assembly);

                    var loaded = domain.Load(assembly);

                    var submission = loaded.GetTypes().Where(x => x.Name.Contains("Submission")).Last();
                    var methods = submission.GetMethods();
                    var result = methods.Where(x => x.Name.Contains("Factory")).First().Invoke(submission, new[] { Session });

                    if (result != null)
                        return result.ToString();

                    AppDomain.Unload(domain);
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }

            return null;
            });
            var finished = task.Wait(10000);

            if (finished)
            return task.Result;

            return "Timeout";
        }