public CompilerErrorCollection RunSource( string source, ref ScriptContext context ) { bool compilationSucceeded = true; CompilerErrorCollection compilationErrors = new CompilerErrorCollection ( ); CSharpCodeProvider provider = new CSharpCodeProvider ( ); // Build the parameters for source compilation. CompilerParameters cp = new CompilerParameters ( ); cp.TreatWarningsAsErrors = false; // Add assembly references. cp.ReferencedAssemblies.AddRange ( DEFAULT_ASSEMBLIES ); cp.ReferencedAssemblies.AddRange ( ReferencedAssemblies.ToArray ( ) ); cp.GenerateInMemory = true; // Add using statements. StringBuilder script = new StringBuilder ( ); foreach ( var usingNamespace in DEFAULT_NAMESPACES ) script.AppendFormat ( "using {0};\r\n", usingNamespace ); foreach ( var additionalUsingNamespace in UsingNamespaces ) script.AppendFormat ( "using {0};\r\n", additionalUsingNamespace ); // Create the script. script.AppendLine ( ); script.AppendLine ( "namespace BlizzetaZero.Kernel.Scripts" ); script.AppendLine ( "{" ); script.AppendFormat ( "\t{0}", source ); script.AppendLine ( "}" ); Console.WriteLine ( script.ToString ( ) ); // Invoke compilation. CompilerResults cr = provider.CompileAssemblyFromSource ( cp, script.ToString ( ) ); if ( cr.Errors.Count > 0 ) { foreach ( CompilerError ce in cr.Errors ) { #if DEBUG Console.WriteLine ( "->\t{0}", ce.ToString ( ) ); Console.WriteLine ( ); #endif ce.Line = ce.Line - 13; compilationErrors.Add ( ce ); if ( !ce.IsWarning ) compilationSucceeded = false; } } if ( compilationSucceeded ) { var ass = cr.CompiledAssembly; var execInstance = ass.CreateInstance ( "BlizzetaZero.Kernel.Scripts.Script" ); var type = execInstance.GetType ( ); var methodInfo = type.GetMethod ( "Load" ); // Execute the code. methodInfo.Invoke ( execInstance, new object[] { context } ); } return compilationErrors; }
public bool Run( string filename, ref ScriptContext context ) { CompilerErrorCollection compilatorErrors = new CompilerErrorCollection ( ); return this.Run ( filename, ref context, out compilatorErrors ); }