예제 #1
1
 public RoslynScriptEngine(IScriptHostFactory scriptHostFactory, ILog logger)
 {
     _scriptEngine = new ScriptEngine();
     _scriptEngine.AddReference(typeof(ScriptExecutor).Assembly);
     _scriptHostFactory = scriptHostFactory;
     _logger = logger;
 }
        static DefaultScriptEngine()
        {
            Instance = new ScriptEngine();

            DefaultAssemblies.ForEach(Instance.AddReference);
            DefaultNamespaces.ForEach(Instance.ImportNamespace);
        }
예제 #3
0
        protected OpohoExecutorBase()
        {
            if (!Provider.IsValid)
            {
                Log.Error("Invalid CompositionProvider. Unable to initialise OpohoExecutor");
                return;
            }
            Config = Provider.ConfigurationProvider as IConsoleConfigurationProvider;
            if (Config == null)
            {
                Log.Error("Invalid ConfigurationProvider. Unable to initialise OpohoExecutor");
                return;
            }
            if (!Config.IsValid)
            {
                Log.Error("Invalid configuration. Unable to initialise OpohoExecutor");
                return;
            }
            CsharpEngine = new ScriptEngine { BaseDirectory = Config.LibDirectory };
            CsharpEngine.AddReference(typeof(System.Linq.Enumerable).Assembly);
            CsharpEngine.AddReference(typeof(IOpohoReportCommand).Assembly);
            CsharpEngine.AddReference(typeof(ReplContextBase).Assembly);

            if (Config.IsValid)
            {
                AddReferences();
                AddImports();
            }
        }
 public HttpResponseMessage Post([FromBody] Code code)
 {
     var scriptEngine = new ScriptEngine();
     Session session = scriptEngine.CreateSession();
     session.AddReference("System");
     session.AddReference("System.Core");
     if (code.Buffer != null)
     {
         code.Buffer = code.Buffer.Where(x => x.EndsWith(";")).ToList();
         code.Buffer.Add(code.CurrentCode);
     }
     else
         code.Buffer = new List<string> { code.CurrentCode };
     var toExecute = string.Join(" ", code.Buffer);
     try
     {
         var result = session.Execute(toExecute);
         return Request.CreateResponse(HttpStatusCode.OK,
             result == null
                 ? new Code { Success = true, Message = string.Empty, Buffer = code.Buffer }
                 : new Code { Success = true, Message = result.ToString(), Buffer = code.Buffer });
     }
     catch (CompilationErrorException errorException)
     {
         return Request.CreateResponse(HttpStatusCode.OK, new Code { Success = false, Message = errorException.Message, Buffer = code.Buffer });
     }
 }
예제 #5
0
 public ScriptingHost(dynamic context)
 {
     // Create the script engine
     _engine = new ScriptEngine();
     // Let us use engine’s Addreference for
     // adding some common assemblies
     new[]
         {
         typeof (Type).Assembly,
         typeof (ICollection).Assembly,
         typeof (ListDictionary).Assembly,
         typeof (Console).Assembly,
         typeof (ScriptingHost).Assembly,
         typeof (IEnumerable<>).Assembly,
         typeof (IQueryable).Assembly,
         typeof (DataSet).Assembly,
         GetType().Assembly
         }.ToList().ForEach(asm => _engine.
                     AddReference(asm));
     //Import common namespaces
     new[]
         {
         "System", "System.Linq",
         "System.Collections",
         "System.Collections.Generic"
         }.ToList().ForEach(ns => _engine.
                     ImportNamespace(ns));
     _session = _engine.CreateSession(context);
 }
예제 #6
0
        public void Execute(string script, IEnumerable<string> paths, IEnumerable<IScriptcsRecipe> recipes)
        {
            var engine = new ScriptEngine();
            engine.AddReference("System");
            engine.AddReference("System.Core");
            var bin = _fileSystem.CurrentDirectory + @"\bin";
            engine.BaseDirectory = bin;

            if (!_fileSystem.DirectoryExists(bin))
                _fileSystem.CreateDirectory(bin);

            foreach (var file in paths)
            {
                var destFile = bin + @"\" + Path.GetFileName(file);
                var sourceFileLastWriteTime = _fileSystem.GetLastWriteTime(file);
                var destFileLastWriteTime = _fileSystem.GetLastWriteTime(destFile);
                if (sourceFileLastWriteTime != destFileLastWriteTime)
                    _fileSystem.Copy(file, destFile,true);

                engine.AddReference(destFile);
            }

            var session = engine.CreateSession();
            var csx = _fileSystem.ReadFile(_fileSystem.CurrentDirectory + @"\" + script);
            session.Execute(csx);
        }
예제 #7
0
        private void CreateEngine()
        {
            //Create the script engine
            //Script engine constructor parameters go changed
            _engine = new ScriptEngine();
            //Let us use engine's Addreference for adding the required
            //assemblies
            new[]
                {
                    typeof (Type).Assembly,
                    typeof (ICollection).Assembly,
                    typeof (ListDictionary).Assembly,
                    typeof (Console).Assembly,
                    typeof (ScriptingHost).Assembly,
                    typeof (IEnumerable<>).Assembly,
                    typeof (IQueryable).Assembly,
                    //typeof (DbSet).Assembly,
                    GetType().Assembly
                }.ToList().ForEach(asm => _engine.AddReference(asm));

            new[]
                {
                    "System", "System.Linq",
                    "System.Collections",
                    "System.Data.Entity",
                    "System.Collections.Generic"
                }.ToList().ForEach(ns => _engine.ImportNamespace(ns));
        }
        /// <summary>
        /// This Method is a javascript callable method.
        /// </summary>
        /// <param name="e">A parameter from javascript.</param>
        /// <param name="y">A callback to javascript.</param>
        public void WebMethod2(string e, Action<string> y)
        {
            // http://blog.filipekberg.se/tag/roslyn/

            var engine = new ScriptEngine();
            var session = engine.CreateSession();

            //error: Attempt by method 'Roslyn.Compilers.ReadOnlyArray`1_ReadOnlyList_<GetEnumerator>d__d<T>.MoveNext()' to 
            // access field 'Roslyn.Compilers.ReadOnlyArray`1+ReadOnlyList<System.__Canon>.array' failed.
            // replace NestedPrivate!

            try
            {
                Console.WriteLine(e);

                var result = session.Execute(e);


                // Send it back to the caller.
                y("output: " + result);
            }
            catch (Exception ex)
            {
                y("error: " + ex.Message);

            }
        }
        public CSharpScriptingEngineRunner(string scriptBefore, string scriptLine, string scriptAfter)
        {
            this.scriptBefore = scriptBefore;
            this.scriptLine = scriptLine;
            this.scriptAfter = scriptAfter;
            scriptingSessionHost = new ScriptingSessionHost();
            importedNamespaces = new[]
                                     {
                                         "System",
                                         "System.Linq",
                                         "System.Collections",
                                         "System.Collections.Generic",
                                         "System.Text.RegularExpressions",
                                         "NppPluginNET"
                                     };

            scriptEngine = new ScriptEngine(new[]
                                                {
                                                    typeof(ScriptingSessionHost).Assembly,
                                                    typeof(Console).Assembly,
                                                    typeof(IEnumerable<>).Assembly,
                                                    typeof(IQueryable<>).Assembly,
                                                    typeof(Regex).Assembly
                                                }, importedNamespaces
                );
            scriptEngineSession = Session.Create(scriptingSessionHost);
            InitializeUsings();
        }
예제 #10
0
        public void Run()
        {
            var hostObject = new HostObject();
            Console.WriteLine("Value is {0}", hostObject.Value);
            Console.WriteLine("Enter code. Type exit to quit");

            var engine = new ScriptEngine();
            var session = engine.CreateSession( hostObject, hostObject.GetType());
            session.AddReference(hostObject.GetType().Assembly);
            string code = string.Empty;
            while (true)
            {
                code = Console.ReadLine();
                if (code == "exit")
                {
                    break;
                }
                try
                {
                    session.Execute(code);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            Console.WriteLine("Value is {0}", hostObject.Value);
            Console.ReadLine();
        }
예제 #11
0
		public ExecutifyEngine(ILog logger, IFileSystem fileSystem)
		{
			_scriptEngine = new ScriptEngine();
			_scriptEngine.AddReference(typeof(ScriptExecutor).Assembly);
			_logger = logger;
			_fileSystem = fileSystem;
		}
예제 #12
0
파일: Program.cs 프로젝트: node-cs/node.cs
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: node.cs <filepath>");
                return;
            }
            try
            {
                using (StreamReader sr = new StreamReader(args[0]))
                {
                    string code = sr.ReadToEnd();
                    var engine = new ScriptEngine();
                    engine.AddReference("System");

                    var session = engine.CreateSession();
                    session.Execute("using System;");

                    session.Execute(code);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #13
0
 public void SimpleEvaluationUsingScriptEngine()
 {
     ScriptEngine engine = new ScriptEngine();
     Session session = engine.CreateSession();
     int result = session.Execute<int>("1 + 2");
     Assert.AreEqual(3, result);
 }
예제 #14
0
        public ChartScriptEngine()
        {
            engine = new ScriptEngine();

            new[]
                {
                    typeof(System.ComponentModel.Component).Assembly,
                    typeof (int).Assembly,
                    typeof (HttpContext).Assembly,
                    typeof (Color).Assembly,
                    typeof (Chart).Assembly,
                    typeof (IEnumerable<>).Assembly,
                    typeof (IQueryable).Assembly
                }.ToList().ForEach(asm => engine.AddReference(asm));

            new[]
                {
                   "System",
                   "System.Web",
                   "System.Drawing",
                   "System.Linq",
                   "System.Collections",
                   "System.Collections.Generic",
                   "System.Web.UI.DataVisualization.Charting"
                }.ToList().ForEach(ns => engine.ImportNamespace(ns));
        }
        public ShoppingCartScriptEngine(Order order)
        {
            if (order == null)
                throw new ArgumentNullException("order", "cannot be null");

            Order = order;
            _engine = new ScriptEngine();
        }
예제 #16
0
 static void Main(string[] args)
 {
     var se = new ScriptEngine();
     var session = se.CreateSession();
     var result = session.Execute("20 + 30");
     Console.WriteLine(result);
     Console.ReadKey(true);
 }
예제 #17
0
        public MainWindow()
        {
            InitializeComponent();
            editor.Text = @"var x = 10;
            x == 10";

            _engine = new ScriptEngine();
            _session = Session.Create();
        }
예제 #18
0
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			var engine = new ScriptEngine();
			var session = engine.CreateSession();

			// Note that we use session.Execute<T> to get a delegate
			Func<string, object> f = session.Execute<Func<string, object>>(parameter.ToString());
			return f(value.ToString());
		}
예제 #19
0
 public MainWindow()
 {
     InitializeComponent();
     var scriptEngine = new ScriptEngine();
     _session = scriptEngine.CreateSession();
     _session.AddReference("System");
     _session.AddReference("System.Core");
     Loaded += MainWindowsLoaded;
 }
예제 #20
0
        public void UsingSessionsForMultipleEvaluations()
        {
            ScriptEngine engine = new ScriptEngine();
            Session session = engine.CreateSession();

            session.Execute("int i = 21;");
            int answer = session.Execute<int>("i * 2");

            Assert.AreEqual(42, answer);
        }
예제 #21
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);
        }
예제 #22
0
 static RoslynScript()
 {
     _engine = new ScriptEngine(
         new[] { "System",
                 "System.Core",
                 // TODO: remove hard-coded dependency
                 @"C:\Users\Colin Bayer\Documents\Demotic\Demotic.Server\bin\Debug\W3b.Sine.dll",
                 Assembly.GetExecutingAssembly().Location,
               });
 }
예제 #23
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");
 }
예제 #24
0
        private static ScriptEngine ConfigureScriptEngine(ScriptInfo scriptInfo, Assembly modelAssembly)
        {
            var scriptEngine = new ScriptEngine();

            scriptEngine.AddReference(modelAssembly);
            scriptInfo.Assemblies.ToList().ForEach(scriptEngine.AddReference);
            scriptInfo.Namespaces.ToList().ForEach(scriptEngine.ImportNamespace);

            return scriptEngine;
        }
예제 #25
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();
 }
예제 #26
0
        public static bool Brainfuck(this string src, out string code, out string result)
        {
            var sb = new StringBuilder();
            sb.AppendLine(@"var ptr = 0;");
            sb.AppendLine(@"var buffer = new char[30000];");
            sb.AppendLine(@"var sb = new StringBuilder();");
            foreach (var c in src) {
                switch (c) {
                    case '>':
                        sb.AppendLine(@"++ptr;");
                        break;
                    case '<':
                        sb.AppendLine(@"--ptr;");
                        break;
                    case '+':
                        sb.AppendLine(@"buffer[ptr] = (char)(buffer[ptr] + 1);");
                        break;
                    case '-':
                        sb.AppendLine(@"buffer[ptr] = (char)(buffer[ptr] - 1);");
                        break;
                    case '.':
                        sb.AppendLine(@"sb.Append(buffer[ptr]);");
                        break;
                    case ',':
                        //not supported
                        //sb.AppendLine(@"buffer[ptr] = (char)Console.Read();");
                        break;
                    case '[':
                        sb.AppendLine(@"while(buffer[ptr] != 0) {");
                        break;
                    case ']':
                        sb.AppendLine(@"}");
                        break;
                    default:
                        break;
                }
            }
            sb.AppendLine(@"sb.ToString();");

            code = sb.ToString();
            //run
            var engine = new ScriptEngine();
            engine.ImportNamespace("System");
            engine.ImportNamespace("System.Text");
            var session = engine.CreateSession();
            try {
                result = session.Execute<string>(code);
            } catch(Exception ex) {
                result = ex.ToString();
                return false;
            }

            return true;
        }
예제 #27
0
 public MainWindow()
 {
     _scriptEngine = new ScriptEngine();
     _session = _scriptEngine.CreateSession();
     _scriptEngine.CreateSession();
     _defaultNamespaces = new[] {"System"};
     foreach (string defaultNamespace in _defaultNamespaces)
         //_session.ImportNamespace(defaultNamespace);
         InitializeComponent();
     Loaded += MainWindowsLoaded;
 }
예제 #28
0
        protected DapperTemplateViaRoslyn(string name, string sql )
        {
            //var lexer = new TypeSqlLexer(new ANTLRStringStream(sql));
            // //var lexer2 = new TypeSqlLexer(new ANTLRStringStream(sql));

            // //var commonTokenStream = new CommonTokenStream(lexer2);
            // var rewriteTokenStream = new TokenRewriteStream(lexer);

            //var parser = new TypeSqlParser(rewriteTokenStream);
            //var parseResult = parser.sql();
            //var ast = (CommonTree) parseResult.Tree;
            // var nodeStream = new CommonTreeNodeStream(ast);
            // var rawSqlOutput = new RawSqlTransform(nodeStream);
            // nodeStream.TokenStream = rewriteTokenStream;
            // rawSqlOutput.sql();
            // string rawSql = rewriteTokenStream.ToString();

            // //parser = new TypeSqlParser(commonTokenStream);
            // //parseResult = parser.sql();
            // //ast = (CommonTree)parseResult.Tree;
            // //nodeStream = new CommonTreeNodeStream(ast) {TokenStream = rewriteTokenStream};
            // lexer.Reset();
            // rewriteTokenStream.Reset();
            // parser.Reset();
            // nodeStream.Reset();
            // var daoTransform = new DaoTransform(nodeStream){TemplateGroup = new StringTemplateGroup(
            //    new StreamReader(new FileStream(@"..\..\..\TypeSql\Parsing\DapperDao.stg", FileMode.Open)),
            //    typeof (TemplateLexer))};
            // var template = daoTransform.sql(name, rawSql).Template;
            // string src = template.ToString();

             //var parseResult = Parser.Parse(sql);

             //var template = new DapperDaoTemplate(name, parseResult);

             //var transformedTemplate = template.TransformText();

             var compileResult = TypeSqlCompiler.Compile(sql, name);

             var engine = new ScriptEngine();
             Session = engine.CreateSession();
             Session.AddReference("System");
             Session.AddReference("System.Core");
             Session.AddReference(typeof(DapperDao<>).Assembly);
             Session.AddReference(typeof(IDbConnection).Assembly);
             Session.AddReference(this.GetType().Assembly);
             Session.AddReference("System.Configuration");
             Session.Execute("using System.Linq;");
             Session.Execute("using System.Data.SqlClient;");
             Session.Execute("using System.Data.Common;");
             Session.Execute("using System.Configuration;");

             Session.Execute(compileResult.Dao);
        }
예제 #29
0
        public RoslynScriptEngine(IScriptHostFactory scriptHostFactory, ILogProvider logProvider)
        {
            Guard.AgainstNullArgument("logProvider", logProvider);

            ScriptEngine = new ScriptEngine();
            _scriptHostFactory = scriptHostFactory;
            _log = logProvider.ForCurrentType();
#pragma warning disable 618
            Logger = new ScriptCsLogger(_log);
#pragma warning restore 618
        }
예제 #30
0
        public ScriptHost(Profile profile, CategoryController category_controller, MainWindowViewModel vm)
        {
            script_engine = new ScriptEngine();
            script_session = script_engine.CreateSession(this);
            script_session.AddReference("System");
            script_session.AddReference(GetType().Assembly.Location);

            Profile = profile;
            ViewModel = vm;
            CategoryController = category_controller;
        }