public TrivialSyntaxTree(string fileName, SyntaxNode rootNode, ParseOptions options) { this.fileName = fileName; this.rootNode = rootNode; this.options = options; // TODO: HACK HACK HACK HACK HACK HACK: look away, for this is terribly inefficient this.text = new StringText(rootNode.GetFullText()); }
public ScriptManager(ICompletionService completionService, IScriptWorkspace scriptWorkspace) { _completionService = completionService; _scriptWorkspace = scriptWorkspace; _compilationOptions = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary); _parseOptions = new ParseOptions(CompatibilityMode.None, LanguageVersion.CSharp6, true, SourceCodeKind.Script); var metadataFileProvider = _scriptWorkspace.CurrentSolution.MetadataFileProvider; _references = AssemblyTypes.Select(type => GetReference(metadataFileProvider, type)); }
private static Type BuildAndLoadModelTypesIntoAppDomain(string modelSourceCode) { var parseOptions = new ParseOptions( compatibility: CompatibilityMode.None, languageVersion: LanguageVersion.CSharp5, preprocessorSymbols: new string[] {}); var syntaxTree = SyntaxTree.ParseText(modelSourceCode, options: parseOptions); if (syntaxTree.GetDiagnostics().Any()) { ThrowError("Parsing failed", syntaxTree.GetDiagnostics()); } var references = new[] { MetadataReference.CreateAssemblyReference(typeof(object).Assembly.FullName) }; var modelDllName = string.Format("Model.{0}.dll", Guid.NewGuid()); var compilation = Compilation.Create( outputName: modelDllName, options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] {syntaxTree}, references: references); if (compilation.GetDiagnostics().Any()) { ThrowError("Compilation failed", compilation.GetDiagnostics()); } using (var stream = new FileStream(modelDllName, FileMode.OpenOrCreate)) { var compileResult = compilation.Emit(stream); if (!compileResult.Success) { ThrowError("Compilation emit failed", compileResult.Diagnostics); } } var compiledAssembly = Assembly.LoadFrom(Path.GetFullPath(modelDllName)); return compiledAssembly.GetTypes().Single(type => type.Name == "ProcessingModel"); }
// http://stackoverflow.com/questions/13601412/compilation-errors-when-dealing-with-c-sharp-script-using-roslyn public override CommonSyntaxTree ParseSyntaxTree(string code) { var options = new ParseOptions(CompatibilityMode.None, LanguageVersion.CSharp6, true,SourceCodeKind.Regular, null); var tree = ParseSyntaxTree(code, options); return tree; }
public void WriteCode(string line) { var options = new ParseOptions( CompatibilityMode.None, LanguageVersion.CSharp4, true, SourceCodeKind.Interactive, default(ReadOnlyArray<string>)); var tree = SyntaxTree.ParseText(line, options: options); var root = tree.GetRoot(); foreach (var item in root.DescendantTokens()) { this.ForegroundColor = ConsoleColor.White; [email protected](item.LeadingTrivia); if (item.IsKeyword() || item.IsReservedKeyword()) { this.ForegroundColor = ConsoleColor.Yellow; [email protected](item); } else if (item.Kind == SyntaxKind.StringLiteralToken) { this.ForegroundColor = ConsoleColor.Green; [email protected](item); } else if (item.Kind == SyntaxKind.NumericLiteralToken) { this.ForegroundColor = ConsoleColor.Green; [email protected](item); } else { [email protected](item); } [email protected](item.TrailingTrivia); } }
public virtual ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); _logger.Info("Starting to create execution components"); _logger.Debug("Creating script host"); var session = GetSession(references, namespaces, scriptPackSession); _logger.Info("Starting execution"); var fileName = new FileInfo(FileName).Name + ".dll"; var codeDir = Path.Combine(_fileSystem.CurrentDirectory, "code"); var dllPath = Path.Combine(codeDir, fileName); var dllExists = _fileSystem.FileExists(dllPath); if (!_fileSystem.DirectoryExists(codeDir)) _fileSystem.CreateDirectory(codeDir); var scriptResult = new ScriptResult(); if (!dllExists) { _logger.Debug("Compiling submission"); var referencesForCompilation = session.References.Union(new[] { "mscorlib", "System", "System.Core", "Microsoft.CSharp" }).Distinct().Select(MetadataReference.CreateAssemblyReference).ToList(); var namespacesForCompilation = ReadOnlyArray<string>.CreateFrom(session.Namespaces); var parseOptions = new ParseOptions(CompatibilityMode.None, LanguageVersion.CSharp6, true, SourceCodeKind.Script); var syntaxTree = SyntaxTree.ParseText(code, options: parseOptions); var options = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithUsings(namespacesForCompilation.ToList()); var compilation = Compilation.Create(AssemblyNamePrefix, options, new[] { syntaxTree }, referencesForCompilation); using (var exeStream = new MemoryStream()) { var result = compilation.Emit(exeStream); if (result.Success) { _logger.Debug("Compilation was successful."); var exeBytes = exeStream.ToArray(); _fileSystem.WriteAllBytes(dllPath, exeBytes); dllExists = true; } else { var errors = String.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString())); _logger.ErrorFormat("Error occurred when compiling: {0})", errors); scriptResult.CompileException = new CompilationException(result.Diagnostics); } } } if (dllExists) { _logger.Debug("Creating Executify Sandbox AppDomain"); var evidence = new Evidence(); evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted)); var permissions = SecurityManager.GetStandardSandbox(evidence); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permissions.AddPermission(new WebPermission(PermissionState.Unrestricted)); permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted)); permissions.AddPermission(new NetworkInformationPermission(NetworkInformationAccess.Ping)); var setup = AppDomain.CurrentDomain.SetupInformation; var domain = AppDomain.CreateDomain("ExecutifySandbox", evidence, setup, permissions, null); _logger.Debug("Retrieving compiled script method (reflection)."); try { _logger.Debug("Invoking method."); Activator.CreateInstanceFrom(domain, dllPath, "Script"); scriptResult.ReturnValue = null; } catch (Exception exc) { _logger.Error("An error occurred when executing the scripts."); _logger.ErrorFormat("Exception Message: {0} {1}Stack Trace:{2}", exc.InnerException.Message, Environment.NewLine, exc.InnerException.StackTrace); scriptResult.ExecuteException = exc; } } return scriptResult; }
private static bool IsCompleteSubmission(string code) { var options = new ParseOptions( CompatibilityMode.None, LanguageVersion.CSharp4, true, SourceCodeKind.Interactive, default(ReadOnlyArray<string>)); var syntaxTree = SyntaxTree.ParseText(code, options: options); return Syntax.IsCompleteSubmission(syntaxTree); }
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"; }
protected static bool IsCompleteSubmission(string code) { var options = new ParseOptions( CompatibilityMode.None, LanguageVersion.CSharp4, true, SourceCodeKind.Interactive); var syntaxTree = SyntaxTree.ParseText(code, options: options); return Syntax.IsCompleteSubmission(syntaxTree); }
// http://stackoverflow.com/questions/13601412/compilation-errors-when-dealing-with-c-sharp-script-using-roslyn protected CommonSyntaxTree ParseSyntaxTree(string code, ParseOptions parseOptions) { var tree = SyntaxTree.ParseText(code, "", parseOptions); return tree; }