private static async Task Main(string[] args) { // This seems to be required for enabling the console to read and write Unicode on Windows. 🙁 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Console.OutputEncoding = Encoding.Unicode; Console.InputEncoding = Encoding.Unicode; } var host = new InteractiveHost { IsNewSessionRequested = true, }; var options = CreateScriptOptions(); ScriptState <object> state = null; var cts = CancellationTokenSource.CreateLinkedTokenSource(host.CancellationToken, default); Console.WriteLine("Solid# Interactive"); Console.WriteLine("------------------"); Console.WriteLine(); Console.WriteLine("Use the reset() method to reset the session, and the exit() method to quit."); Console.WriteLine(); Console.CancelKeyPress += (s, e) => cts.Cancel(); while (!cts.IsCancellationRequested && ReadLine() is string line) { if (string.IsNullOrWhiteSpace(line)) { continue; } try { if (host.IsNewSessionRequested) { state = await CSharpScript.RunAsync(line, options, host, cancellationToken : cts.Token); host.IsNewSessionRequested = false; } else { state = await state.ContinueWithAsync(line, options, cancellationToken : cts.Token); } } catch (CompilationErrorException ex) { PrintErrorMessage(ex.Message); continue; } if (state.Exception != null) { PrintErrorMessage(state.Exception.ToString()); continue; } switch (state.ReturnValue) { case SymbolicExpression expr: Console.WriteLine(expr); break; case SymbolicEquation eq: Console.WriteLine(eq); break; case SymbolicEquationSystem eqs: break; case Vector2 v: Console.WriteLine(v); break; case Vector3 v: Console.WriteLine(v); break; case string s: Console.WriteLine(@"""" + s.Replace(@"""", @"""""") + @""""); break; default: Console.WriteLine(state.ReturnValue.GetType().ToString() + ":"); Console.WriteLine(state.ReturnValue.ToString()); break; case null: break; } } }
static void Main(string[] args) { string[] wait = new[] { "o....", ".o...", "..o..", "...o.", "....o" }; Func <Task <ScriptState <object> >, ScriptState> Execute = t => { CancellationTokenSource cts = new CancellationTokenSource(); t.ContinueWith(_ => { cts.Cancel(); }); CancellationToken cancellationToken = cts.Token; int index = 0; while (!cancellationToken.IsCancellationRequested) { Console.Write("\r{0}", wait[index]); index = (index + 1) % wait.Length; try { Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).GetAwaiter().GetResult(); } catch (TaskCanceledException) { } } Console.Write("\r{0}\r", new string(' ', 20)); return(t.Result); }; ScriptOptions scriptOptions = ScriptOptions.Default; scriptOptions = scriptOptions.WithReferences("System"); ScriptState scriptState = Execute(CSharpScript.RunAsync("using System;", scriptOptions)); while (true) { Console.Write("? "); string line = Console.ReadLine(); try { if (line.StartsWith("#")) { if (line.StartsWith("#reference")) { scriptOptions = scriptOptions.WithReferences(line.Substring("#reference".Length).Trim()); } if (line == "#quit") { break; } continue; } scriptState = Execute(scriptState.ContinueWithAsync(line, scriptOptions)); } catch (Exception e) { Console.WriteLine(e.Message); continue; } if (scriptState.ReturnValue != null) { Console.WriteLine(scriptState.ReturnValue); } } }
public void TestRunScript() { var result = CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, result.ReturnValue.Result); }
public void RunScript(string comPort, string host, string path) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; string[] template = File.ReadAllLines(TemplateFile); string[] script = File.ReadAllLines(path); List <string> builder = new List <string>(); bool skip = false; int offset = 0; int count = 0; foreach (var line in template) { string trimed = line.Trim().ToUpper(); if (trimed.StartsWith("//[*")) { skip = true; } else if (trimed.StartsWith("//*]")) { skip = false; } else if (trimed.StartsWith("//[SCRIPT]")) { offset = count; builder.AddRange(script); } else { if (!skip) { count++; builder.Add(line); } } } string text = string.Join("\r\n", builder) + $"\r\nnew {Template}(\"{comPort}\",\"{host}\")"; try { ScriptOptions options = ScriptOptions.Default .WithImports("System", "System.Text", "System.Math", "System.Collections.Generic", "System.Net", "Codeplex.Data", "System.IO.Ports", "System.Timers", "System.Threading", "System.Threading.Tasks", "MQTTnet", "MQTTnet.Client", "MQTTnet.Client.Options" ) .WithReferences( "System.IO.Ports.dll", Path.GetFullPath(@"MQTTnet.dll"), Path.GetFullPath(@"Serial2MQTT.dll") ); var task = CSharpScript.RunAsync(text, options); task.Wait(); }catch (Exception ex) { string message = ex.Message; var regex = new Regex(@"\((\d+),(\d+)\)(.*)"); var match = regex.Match(message); if (match.Success) { int line = Convert.ToInt32(match.Groups[1].Value); int col = Convert.ToInt32(match.Groups[2].Value); string body = match.Groups[3].Value; string cursor = (new string(' ', col - 1)) + "^"; int scriptLine = line - offset; message = $"{path} ({line-offset},{col}){body}\r\n{builder[line-1]}\r\n{cursor}"; } Console.WriteLine(message); Environment.Exit(-1); } }
async static Task HandleConnection(Socket conn) { try { NetworkStream ns = new NetworkStream(conn, true); byte[] buf = new byte[RequestHeader.Size]; if (!await ReadExact(ns, buf)) { Console.Error.WriteLine("early eof while reading header"); return; } RequestHeader h = RequestHeader.FromBytes(buf); buf = new byte[h.ContextKeyLength + h.CodeLength]; if (!await ReadExact(ns, buf)) { Console.Error.WriteLine("early eof while reading body"); return; } string conkey = Encoding.UTF8.GetString(buf, 0, (int)h.ContextKeyLength); string code = Encoding.UTF8.GetString(buf, (int)h.ContextKeyLength, (int)h.CodeLength); // TODO string resp = "unknown error"; ScriptState <object> res = _contexts.GetValueOrDefault(conkey, null); try { Task <ScriptState <Object> > tres; if (res != null) { tres = res.ContinueWithAsync(code, SCRIPT_OPTIONS); } else { tres = CSharpScript.RunAsync(code, SCRIPT_OPTIONS); } res = await tres; if (res == null) { resp = "null result?"; } else if (res.Exception != null) { resp = CSharpObjectFormatter.Instance.FormatException(res.Exception); } else if (res.ReturnValue != null) { resp = CSharpObjectFormatter.Instance.FormatObject(res.ReturnValue, PRINT_OPTIONS); } else { resp = ""; } _contexts[conkey] = res; } catch (Exception e) { resp = CSharpObjectFormatter.Instance.FormatException(e); } byte[] respbytes = Encoding.UTF8.GetBytes(resp); await ns.WriteAsync(IntToBytes(respbytes.Length), 0, 4, CancellationToken.None).ConfigureAwait(false); await ns.WriteAsync(respbytes, 0, respbytes.Length, CancellationToken.None).ConfigureAwait(false); } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e); } }
private async Task HandleSubmitCode( SubmitCode submitCode, KernelInvocationContext context) { var codeSubmissionReceived = new CodeSubmissionReceived( submitCode.Code, submitCode); context.OnNext(codeSubmissionReceived); var code = submitCode.Code; context.OnNext(new CompleteCodeSubmissionReceived(submitCode)); Exception exception = null; using var console = await ConsoleOutput.Capture(); using var _ = console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode)); try { if (_scriptState == null) { _scriptState = await CSharpScript.RunAsync( code, ScriptOptions); } else { _scriptState = await _scriptState.ContinueWithAsync( code, ScriptOptions, e => { exception = e; return(true); }); } } catch (Exception e) { exception = e; } if (exception != null) { string message = null; if (exception is CompilationErrorException compilationError) { message = string.Join(Environment.NewLine, compilationError.Diagnostics.Select(d => d.ToString())); } context.OnNext(new CommandFailed(exception, submitCode, message)); context.OnError(exception); } else { if (HasReturnValue) { var formattedValues = FormattedValue.FromObject(_scriptState.ReturnValue); context.OnNext( new ValueProduced( _scriptState.ReturnValue, submitCode, true, formattedValues)); } context.OnNext(new CodeSubmissionEvaluated(submitCode)); context.OnCompleted(); } }
public async Task TestRunScriptWithSpecifiedReturnType() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); }
public async Task <(int, string)> EvalAsync(string code, object ctx) { if (code[code.Length - 1] != ';') { code += ";"; } string[] imports = { "System", "System.IO", "System.Collections", "System.Collections.Generic", "System.Linq", "System.Reflection", "System.Text", "System.Threading.Tasks", "Discord", "Discord.Net", "Discord.Rest", "Discord.WebSocket", "Energize", "Energize.Essentials", "Energize.Services", "Energize.Interfaces", "System.Text.RegularExpressions", "System.Diagnostics" }; ScriptOptions options = ScriptOptions.Default .WithImports(imports) .WithReferences(AppDomain.CurrentDomain .GetAssemblies() .Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location))); try { ScriptState state = await CSharpScript.RunAsync(code, options, ctx); if (state?.ReturnValue != null) { string ret = state.ReturnValue.ToString(); if (!string.IsNullOrWhiteSpace(ret)) { if (ret.Length > 2000) { ret = $"{ret.Substring(0, 1980)}... \n**[{(ret.Length - 2020)}\tCHARS\tLEFT]**"; } return(1, ret); } else { return(2, "⚠ (string was null or empty)"); } } else { return(1, "👌 (nothing or null was returned)"); } } catch (Exception ex) { return(0, $"```\n{ex.Message.Replace("`", "")}```"); } }
private static void Run() { var code = File.ReadAllText(GetScriptTestFile("test1.csx")); CSharpScript.RunAsync(code, ScriptOptions.Default).GetAwaiter().GetResult(); }
private async void StartExecution() { //Initializes Execution state state = await CSharpScript.RunAsync("", ScriptOptions.Default.WithImports("System.IO")); }
/// <summary> /// Executes the specified code. /// </summary> /// <param name="code">The code.</param> private void Execute(string code) { try { InteractiveScriptBase.Current = scriptBase; scriptBase._ScriptState_ = scriptState; scriptBase._CodeGenCode_ = scriptBase._CodeGenCode_ ?? new List <ImportUserTypeCode>(); scriptBase._CodeResolver_ = sourceResolver; scriptBase._CodeGenAssemblies_ = scriptBase._CodeGenAssemblies_ ?? new List <ImportUserTypeAssembly>(); scriptBase._AssemblyResolver_ = metadataResolver; scriptState = scriptState.ContinueWithAsync(code).Result; importedCode = ExtractImportedCode(scriptState.Script, importedCode); UpdateUsings(scriptState.Script, usings); UpdateReferences(scriptState.Script, references); scriptBase.Dump(scriptState.ReturnValue); if (scriptBase._InteractiveScriptBaseType_ != null && scriptBase._InteractiveScriptBaseType_ != scriptBase.GetType()) { var oldScriptBase = scriptBase; scriptBase = (InteractiveScriptBase)Activator.CreateInstance(scriptBase._InteractiveScriptBaseType_); scriptBase.ObjectWriter = oldScriptBase.ObjectWriter; scriptBase._InternalObjectWriter_ = oldScriptBase._InternalObjectWriter_; // TODO: Changing globals, but we need to store previous variables scriptState = CSharpScript.RunAsync(string.Join("\n", ScriptCompiler.DefaultAliases.Select(s => $"using {s};")), scriptState.Script.Options, scriptBase).Result; } if (scriptBase._ExtractedUserTypeMetadata_.Count > 0) { Context.SetUserTypeMetadata(scriptBase._ExtractedUserTypeMetadata_.Concat(Context.UserTypeMetadata).ToArray()); scriptBase._ExtractedUserTypeMetadata_.Clear(); } if (scriptBase._CodeGenCode_.Count > 0) { foreach (ImportUserTypeCode codeGenCode in scriptBase._CodeGenCode_) { scriptState = scriptState.ContinueWithAsync(codeGenCode.Code).Result; sourceResolver.AddCode(codeGenCode); } importedCode = ExtractImportedCode(scriptState.Script, importedCode); UpdateUsings(scriptState.Script, usings); UpdateReferences(scriptState.Script, references); scriptBase._CodeGenCode_.Clear(); } if (scriptBase._CodeGenAssemblies_.Count > 0) { foreach (ImportUserTypeAssembly assembly in scriptBase._CodeGenAssemblies_) { metadataResolver.AddAssembly(assembly); } List <MetadataReference> originalReferences = scriptState.Script.Options.MetadataReferences.ToList(); ScriptOptions options = scriptState.Script.Options .WithReferences(originalReferences) .AddReferences(scriptBase._CodeGenAssemblies_.Select(a => a.AssemblyPath)); scriptState = scriptState.Script.ContinueWith("", options).RunFromAsync(scriptState).Result; importedCode = ExtractImportedCode(scriptState.Script, importedCode); UpdateUsings(scriptState.Script, usings); UpdateReferences(scriptState.Script, references); scriptBase._CodeGenAssemblies_.Clear(); } } finally { InteractiveScriptBase.Current = null; } }
public async Task <bool> InitScript(CancellationToken token = default) { using (await _scriptStateLock.LockAsync(token)) { if (_scriptState != null) { return(true); } try { var options = ScriptOptions.Default .WithReferences(_references.ToArrayLocked(_lockReferences)) .WithImports(_usings.ToArrayLocked(_lockUsings)); var globals = _globals.ToDictionaryLocked(_lockGlobals); if (globals.Any()) { var createGlobalsScript = CSharpScript.Create(CreateGlobalsType(), options); var image = createGlobalsScript.GetCompilation(); var stream = new MemoryStream(); var result = image.Emit(stream, cancellationToken: token); if (!result.Success) { var scriptResult = new ScriptResult { Result = string.Join("\n", result.Diagnostics.Select(d => d.GetMessage())), IsError = true }; Results.Add(scriptResult); ScriptResultReceived?.Invoke(this, scriptResult); return(false); } var imageArray = ImmutableArray.Create(stream.ToArray()); var portableReference = MetadataReference.CreateFromImage(imageArray); var libAssembly = Assembly.Load(imageArray.ToArray()); var globalsType = libAssembly.GetTypes().FirstOrDefault(t => t.Name == "ScriptGlobals"); var globalsInstance = Activator.CreateInstance(globalsType); foreach (var propInfo in globalsType.GetFields()) { propInfo.SetValue(globalsInstance, globals[propInfo.Name]); } using (var loader = new InteractiveAssemblyLoader()) { loader.RegisterDependency(libAssembly); var script = CSharpScript.Create(string.Empty, options.AddReferences(portableReference), globalsType, loader); _scriptState = await script.RunAsync(globalsInstance, cancellationToken : token); } } else { _scriptState = await CSharpScript.RunAsync(string.Empty, options, cancellationToken : token); } } catch (OperationCanceledException) { _scriptState = null; } } return(_scriptState != null); }
private async Task HandleSubmitCode( SubmitCode submitCode, KernelInvocationContext context) { var codeSubmissionReceived = new CodeSubmissionReceived( submitCode.Code, submitCode); context.OnNext(codeSubmissionReceived); var(shouldExecute, code) = IsBufferACompleteSubmission(submitCode.Code); if (shouldExecute) { context.OnNext(new CompleteCodeSubmissionReceived(submitCode)); Exception exception = null; using var console = await ConsoleOutput.Capture(); using var _ = console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode)); try { if (_scriptState == null) { _scriptState = await CSharpScript.RunAsync( code, ScriptOptions); } else { _scriptState = await _scriptState.ContinueWithAsync( code, ScriptOptions, e => { exception = e; return(true); }); } } catch (Exception e) { exception = e; } if (exception != null) { var message = string.Join("\n", (_scriptState?.Script?.GetDiagnostics() ?? Enumerable.Empty <Diagnostic>()).Select(d => d.GetMessage())); context.OnNext(new CodeSubmissionEvaluationFailed(exception, message, submitCode)); context.OnError(exception); } else { if (HasReturnValue) { var returnValueType = _scriptState.ReturnValue?.GetType(); var mimeType = MimeTypeFor(returnValueType); var formatted = _scriptState.ReturnValue.ToDisplayString(mimeType); var formattedValues = new List <FormattedValue> { new FormattedValue(mimeType, formatted) }; context.OnNext( new ValueProduced( _scriptState.ReturnValue, submitCode, true, formattedValues)); } context.OnNext(new CodeSubmissionEvaluated(submitCode)); context.OnCompleted(); } } else { context.OnNext(new IncompleteCodeSubmissionReceived(submitCode)); context.OnNext(new CodeSubmissionEvaluated(submitCode)); context.OnCompleted(); } }
public async void TestRunScript() { var state = await CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, state.ReturnValue); }
public async Task SharedLibCopy_SameVersion_StrongDifferentPKT_DifferentContent() { string libBaseName = "LibBase_" + Guid.NewGuid(); string lib1Name = "Lib1_" + Guid.NewGuid(); string lib2Name = "Lib2_" + Guid.NewGuid(); var libBase1 = CreateCSharpCompilation(@" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class LibBase { public readonly int X = 1; } ", new[] { Net451.mscorlib }, libBaseName, s_signedDll); var libBase2 = CreateCSharpCompilation(@" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class LibBase { public readonly int X = 2; } ", new[] { Net451.mscorlib }, libBaseName, s_signedDll2); var lib1 = CreateCSharpCompilation(@" public class Lib1 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib1Name); var lib2 = CreateCSharpCompilation(@" public class Lib2 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib2Name); var libBase1Image = libBase1.EmitToArray(); var libBase2Image = libBase2.EmitToArray(); var lib1Image = lib1.EmitToArray(); var lib2Image = lib2.EmitToArray(); var root = Temp.CreateDirectory(); var dir1 = root.CreateDirectory("1"); var file1 = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image); var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase1Image); var dir2 = root.CreateDirectory("2"); var file2 = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image); var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase2Image); var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}"""); var s1 = await s0.ContinueWithAsync($@"new Lib1().libBase.X"); var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}"""); bool exceptionSeen = false; try { await s2.ContinueWithAsync($@"new Lib2().libBase.X"); } catch (FileLoadException fileLoadEx) when(fileLoadEx.InnerException is InteractiveAssemblyLoaderException) { exceptionSeen = true; } Assert.True(exceptionSeen); }
public void TestRunStatementFollowedBySpace() { var state = CSharpScript.RunAsync(@"System.Console.WriteLine(true) ", globals: new ScriptTests()); Assert.Null(state.Exception); }
public async void runScript() { var state = await CSharpScript.RunAsync <int>(Content); ReturnValue = state.ReturnValue.ToString(); }
public async Task ContinueAsync_Error1() { var state = await CSharpScript.RunAsync("X + Y", globals : new Globals()); await Assert.ThrowsAsync <ArgumentNullException>("previousState", () => state.Script.RunFromAsync(null)); }
public async Task ContinueAsync_Error1() { var state = await CSharpScript.RunAsync("X + Y", globals : new Globals()); AssertEx.ThrowsArgumentNull("previousState", () => state.Script.ContinueAsync(null)); }
static void Main(string[] args) { Dictionary <string, string> inputVariables = new Dictionary <string, string>(); inputVariables.Add("x", "30"); inputVariables.Add("y", "40"); Dictionary <string, string> calculatedVariables = new Dictionary <string, string>(); calculatedVariables.Add("area", "x * y"); string[] rules = { "area > 1000 && x < 2 * y", "area < 1000", "area > 1000 && y > 500" }; Task.Run(async() => { /// Code for the solution using Roslyn state Console.WriteLine("Using Roslyn state:"); try { var state = await CSharpScript.RunAsync(""); // Declare input variables foreach (var item in inputVariables) { state = await state.ContinueWithAsync(String.Format("var {0} = {1};", item.Key, item.Value)); } // Declare and calculate calculated variables foreach (var item in calculatedVariables) { state = await state.ContinueWithAsync(String.Format("var {0} = {1};", item.Key, item.Value)); } // Evaluate each condition foreach (var rule in rules) { state = await state.ContinueWithAsync(rule); Console.WriteLine(String.Format("Rule '{0}' was evaluated as {1}", rule, (bool)state.ReturnValue)); } } catch (CompilationErrorException e) { Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics)); } Console.WriteLine(Environment.NewLine); /// Code using replacing and evaluation of formulas Console.WriteLine("Using replacing and Roslyn evaluation of formulas:"); try { List <string> keys = new List <string>(calculatedVariables.Keys); foreach (var key in keys) { foreach (var item in inputVariables) { calculatedVariables[key] = calculatedVariables[key].Replace(item.Key, item.Value); } ; calculatedVariables[key] = (await CSharpScript.EvaluateAsync(calculatedVariables[key])).ToString(); } for (var i = 0; i < rules.Length; i++) { foreach (var item in inputVariables) { rules[i] = rules[i].Replace(item.Key, item.Value); } foreach (var item in calculatedVariables) { rules[i] = rules[i].Replace(item.Key, item.Value); } bool isRuleTrue = await CSharpScript.EvaluateAsync <bool>(rules[i]); Console.WriteLine(String.Format("Rule '{0}' was evaluated as {1}", rules[i], isRuleTrue)); } } catch (CompilationErrorException e) { Console.WriteLine(string.Join(Environment.NewLine, e.Diagnostics)); } }).GetAwaiter().GetResult(); Console.ReadKey(); }
public async Task TestRunVoidScript() { var state = await CSharpScript.RunAsync("System.Console.WriteLine(0);"); Assert.Null(state.ReturnValue); }
public App() { Configuration config1 = null; string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); if (Directory.Exists(directory)) { string filename = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config", SearchOption.TopDirectoryOnly) where filename.Equals(Path.GetFileNameWithoutExtension(s)) select s) { ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap(); exeConfigurationFileMap.ExeConfigFilename = s; config1 = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None); } } if (config1 == null) { config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config1.AppSettings.Settings["Scripts"] != null) { ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly()); List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >(); foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value) ? config1.AppSettings.Settings["Scripts"].Value : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly)) { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions)); } } Task <ScriptState <object> > .WaitAll(taskList.ToArray()); } if (config1.AppSettings.Settings["Extensions"] != null) { List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>(); foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Extensions"].Value) ? config1.AppSettings.Settings["Extensions"].Value : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly)) { assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename)); } if (assemblyList.Count > 0) { using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer()) { this.Extensions = container.GetExports <IExtension>(); } Script.Instance.Start += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Attach(); } }); Script.Instance.Stop += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Detach(); } }); } } } else { Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config1.AppSettings.Settings["Scripts"] == null) { if (config2.AppSettings.Settings["Scripts"] != null) { if (Path.IsPathRooted(config2.AppSettings.Settings["Scripts"].Value)) { ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly()); List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >(); foreach (string filename in Directory.EnumerateFiles(config2.AppSettings.Settings["Scripts"].Value, "*.csx", SearchOption.TopDirectoryOnly)) { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions)); } } Task <ScriptState <object> > .WaitAll(taskList.ToArray()); } else { string path = Path.Combine(directory, config2.AppSettings.Settings["Scripts"].Value); ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly()); List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >(); foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config2.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly)) { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions)); } } Task <ScriptState <object> > .WaitAll(taskList.ToArray()); } } } else if (Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value)) { ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly()); List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >(); foreach (string filename in Directory.EnumerateFiles(config1.AppSettings.Settings["Scripts"].Value, "*.csx", SearchOption.TopDirectoryOnly)) { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions)); } } Task <ScriptState <object> > .WaitAll(taskList.ToArray()); } else { string path = Path.Combine(directory, config1.AppSettings.Settings["Scripts"].Value); ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly()); List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >(); foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly)) { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader sr = new StreamReader(fs)) { taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions)); } } Task <ScriptState <object> > .WaitAll(taskList.ToArray()); } if (config1.AppSettings.Settings["Extensions"] == null) { if (config2.AppSettings.Settings["Extensions"] != null) { List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>(); if (Path.IsPathRooted(config2.AppSettings.Settings["Extensions"].Value)) { foreach (string filename in Directory.EnumerateFiles(config2.AppSettings.Settings["Extensions"].Value, "*.dll", SearchOption.TopDirectoryOnly)) { assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename)); } } else { string path = Path.Combine(directory, config2.AppSettings.Settings["Extensions"].Value); foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config2.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly)) { assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename)); } } if (assemblyList.Count > 0) { using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer()) { this.Extensions = container.GetExports <IExtension>(); } Script.Instance.Start += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Attach(); } }); Script.Instance.Stop += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Detach(); } }); } } } else { List <System.Reflection.Assembly> assemblyList = new List <System.Reflection.Assembly>(); if (Path.IsPathRooted(config1.AppSettings.Settings["Extensions"].Value)) { foreach (string filename in Directory.EnumerateFiles(config1.AppSettings.Settings["Extensions"].Value, "*.dll", SearchOption.TopDirectoryOnly)) { assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename)); } } else { string path = Path.Combine(directory, config1.AppSettings.Settings["Extensions"].Value); foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config1.AppSettings.Settings["Extensions"].Value), "*.dll", SearchOption.TopDirectoryOnly)) { assemblyList.Add(System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(filename)); } } if (assemblyList.Count > 0) { using (System.Composition.Hosting.CompositionHost container = new System.Composition.Hosting.ContainerConfiguration().WithAssemblies(assemblyList).CreateContainer()) { this.Extensions = container.GetExports <IExtension>(); } Script.Instance.Start += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Attach(); } }); Script.Instance.Stop += new EventHandler <EventArgs>(delegate { foreach (IExtension extension in this.Extensions) { extension.Detach(); } }); } } } }
public async void Init() { SymbolCount = 1; Globals = new Globals(); List <MetadataReference> references = new List <MetadataReference>(); foreach (var assembly in Inspector.GetReferencableAssemblies()) { references.Add(MetadataReference.CreateFromFile(assembly.Location)); } /* For easier debugging * references.Add(MetadataReference.CreateFromFile(typeof(Evaluator).Assembly.Location)); * references.Add(MetadataReference.CreateFromFile(typeof(UnityEditor.BuildOptions).Assembly.Location)); * references.Add(MetadataReference.CreateFromFile(typeof(UnityEngine.Application).Assembly.Location)); */ var options = ScriptOptions.Default.WithReferences(references); ScriptState = await CSharpScript.RunAsync("", options, globals : Globals); // Set some default common namespaces for easier debugging await AddNamespace(new List <string> { "UnityEngine", "UnityEditor", "System", "System.Collections", "System.Collections.Generic", "System.Linq" }); /* Test using workspaces * string _text = * @"using System;using UnityE * namespace TEST * { * public class MyClass * { * public static void Print() * { * Console.WriteLine(""Hello World""); * } * } * }"; * Workspace = new AdhocWorkspace(); * string projName = "Immediate Window"; * ProjectId projId = ProjectId.CreateNewId(); * VersionStamp versionStamp = VersionStamp.Create(); * ProjectInfo projInfo = ProjectInfo.Create(projId, versionStamp, projName, projName, LanguageNames.CSharp); * SourceText sourceText = SourceText.From(_text); * * projInfo = projInfo.WithMetadataReferences(references); * Workspace.AddProject(projInfo); * Document doc = Workspace.AddDocument(Workspace.CurrentSolution.ProjectIds[0], "console.cs", sourceText); * * SemanticModel semanticModel = doc.GetSemanticModelAsync().Result; * * IEnumerable<Diagnostic> diagnostics = semanticModel.GetDiagnostics(); * IEnumerable<ISymbol> symbols = Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, 25, Workspace).Result; * foreach (var symbol in symbols) * { * Debug.Log($"Symbol: {symbol.Name}"); * } */ }
private Task CompileAndRunAsync(string sourceCode) { Assert.Equal(0, stringList.Count); return(CSharpScript.RunAsync(sourceCode, globals: this)); }
async void makro1a(object sender, RoutedEventArgs e) { var state = await CSharpScript.RunAsync <int>(tretitext.Text); Vysledek.Content = state.ReturnValue; }
public async Task SharedLibCopy_DifferentVersion_Strong() { string libBaseName = "LibBase_" + Guid.NewGuid(); string lib1Name = "Lib1_" + Guid.NewGuid(); string lib2Name = "Lib2_" + Guid.NewGuid(); var libBase1 = CreateCSharpCompilation(@" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class LibBase { public readonly int X = 1; } ", new[] { Net451.mscorlib }, libBaseName, s_signedDll); var libBase2 = CreateCSharpCompilation(@" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class LibBase { public readonly int X = 2; } ", new[] { Net451.mscorlib }, libBaseName, s_signedDll); var lib1 = CreateCSharpCompilation(@" public class Lib1 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase1.ToMetadataReference() }, lib1Name); var lib2 = CreateCSharpCompilation(@" public class Lib2 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase2.ToMetadataReference() }, lib2Name); var libBase1Image = libBase1.EmitToArray(); var libBase2Image = libBase2.EmitToArray(); var lib1Image = lib1.EmitToArray(); var lib2Image = lib2.EmitToArray(); var root = Temp.CreateDirectory(); var dir1 = root.CreateDirectory("1"); var file1 = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image); var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase1Image); var dir2 = root.CreateDirectory("2"); var file2 = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image); var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBase2Image); var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}"""); var s1 = await s0.ContinueWithAsync($@"new Lib1().libBase.X"); Assert.Equal(1, s1.ReturnValue); var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}"""); var s3 = await s2.ContinueWithAsync($@"new Lib2().libBase.X"); Assert.Equal(2, s3.ReturnValue); }
private async Task HandleSubmitCode( SubmitCode submitCode, KernelInvocationContext context) { CancellationTokenSource cancellationSource; lock (_cancellationSourceLock) { cancellationSource = _cancellationSource; } var codeSubmissionReceived = new CodeSubmissionReceived(submitCode); context.Publish(codeSubmissionReceived); var code = submitCode.Code; var isComplete = await IsCompleteSubmissionAsync(submitCode.Code); if (isComplete) { context.Publish(new CompleteCodeSubmissionReceived(submitCode)); } else { context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); } if (submitCode.SubmissionType == SubmissionType.Diagnose) { return; } Exception exception = null; using var console = await ConsoleOutput.Capture(); using (console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode))) using (console.SubscribeToStandardError(std => PublishError(std, context, submitCode))) { if (!cancellationSource.IsCancellationRequested) { ScriptOptions = ScriptOptions.WithMetadataResolver( ScriptMetadataResolver.Default.WithBaseDirectory( Directory.GetCurrentDirectory())); try { if (ScriptState == null) { ScriptState = await CSharpScript.RunAsync( code, ScriptOptions, cancellationToken : cancellationSource.Token) .UntilCancelled(cancellationSource.Token); } else { ScriptState = await ScriptState.ContinueWithAsync( code, ScriptOptions, catchException : e => { exception = e; return(true); }, cancellationToken : cancellationSource.Token) .UntilCancelled(cancellationSource.Token); } } catch (CompilationErrorException cpe) { exception = new CodeSubmissionCompilationErrorException(cpe); } catch (Exception e) { exception = e; } } } if (!cancellationSource.IsCancellationRequested) { if (exception != null) { string message = null; if (exception is CodeSubmissionCompilationErrorException compilationError) { message = string.Join(Environment.NewLine, (compilationError.InnerException as CompilationErrorException)?.Diagnostics.Select(d => d.ToString()) ?? Enumerable.Empty <string>()); } context.Fail(exception, message); } else { if (ScriptState != null && HasReturnValue) { var formattedValues = FormattedValue.FromObject(ScriptState.ReturnValue); context.Publish( new ReturnValueProduced( ScriptState.ReturnValue, submitCode, formattedValues)); } } } else { context.Fail(null, "Command cancelled"); } }
public async Task SharedLibCopy_Identical_Strong() { string libBaseName = "LibBase_" + Guid.NewGuid(); string lib1Name = "Lib1_" + Guid.NewGuid(); string lib2Name = "Lib2_" + Guid.NewGuid(); var libBase = CreateCSharpCompilation(@" public class LibBase { public readonly int X = 1; } ", new[] { Net451.mscorlib }, libBaseName, s_signedDll); var lib1 = CreateCSharpCompilation(@" public class Lib1 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase.ToMetadataReference() }, lib1Name); var lib2 = CreateCSharpCompilation(@" public class Lib2 { public LibBase libBase = new LibBase(); } ", new MetadataReference[] { Net451.mscorlib, libBase.ToMetadataReference() }, lib2Name); var libBaseImage = libBase.EmitToArray(); var lib1Image = lib1.EmitToArray(); var lib2Image = lib2.EmitToArray(); var root = Temp.CreateDirectory(); var dir1 = root.CreateDirectory("1"); var file1 = dir1.CreateFile(lib1Name + ".dll").WriteAllBytes(lib1Image); var fileBase1 = dir1.CreateFile(libBaseName + ".dll").WriteAllBytes(libBaseImage); var dir2 = root.CreateDirectory("2"); var file2 = dir2.CreateFile(lib2Name + ".dll").WriteAllBytes(lib2Image); var fileBase2 = dir2.CreateFile(libBaseName + ".dll").WriteAllBytes(libBaseImage); var s0 = await CSharpScript.RunAsync($@"#r ""{file1.Path}"""); var s1 = await s0.ContinueWithAsync($@"var l1 = new Lib1();"); var s2 = await s1.ContinueWithAsync($@"#r ""{file2.Path}"""); var s3 = await s2.ContinueWithAsync($@"var l2 = new Lib2();"); var s4 = await s3.ContinueWithAsync($@"l2.libBase.X"); var c4 = s4.Script.GetCompilation(); c4.VerifyAssemblyAliases( lib2Name, lib1Name, "mscorlib", libBaseName + ": <implicit>,global"); var libBaseRefAndSymbol = c4.GetBoundReferenceManager().GetReferencedAssemblies().ToArray()[3]; Assert.Equal(fileBase1.Path, ((PortableExecutableReference)libBaseRefAndSymbol.Key).FilePath); }
public void TestRunScriptWithSpecifiedReturnType() { var result = CSharpScript.RunAsync("1 + 2"); Assert.Equal(3, result.ReturnValue.Result); }
protected override ScriptState GetScriptState(string code, object globals) { return(CSharpScript.RunAsync(code, ScriptOptions, globals).GetAwaiter().GetResult()); }