public ScriptEvaluator Compile () { Message = null; HasError = false; var reportWriter = new System.IO.StringWriter (); try { var settings = new Mono.CSharp.CompilerSettings (); settings.GenerateDebugInfo = false; settings.LoadDefaultReferences = true; settings.Optimize = true; settings.WarningsAreErrors = false; var reporter = new Mono.CSharp.ConsoleReportPrinter (reportWriter); var ctx = new Mono.CSharp.CompilerContext (settings, reporter); var scriptEngine = new Mono.CSharp.Evaluator (ctx); AddReference (this.GetType ()); // add assemblies for (int i = 0; i < _assemblies.Count; i++) { scriptEngine.ReferenceAssembly (_assemblies[i]); } if (String.IsNullOrWhiteSpace (Script)) throw new ArgumentNullException ("Expression"); if (!scriptEngine.Run (Script)) throw new Exception (reportWriter.ToString ()); if (reporter.ErrorsCount > 0) { throw new Exception (reportWriter.ToString ()); } _createMethod = scriptEngine.Compile ("new " + MainClassName + "()"); if (reporter.ErrorsCount > 0) { throw new Exception (reportWriter.ToString ()); } if (_createMethod == null) { throw new Exception ("script method could be created"); } } catch (Exception e) { Message = e.Message; HasError = true; } return this; }
static private void ReferenceAllAssemblies() { // See the detailed information about this hack at: // http://forum.unity3d.com/threads/mono-csharp-evaluator.102162/ // not relevant for new Mono.CSharp and Unity // for (int n = 0; n < 2;) { foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { if (assembly == null) { continue; } // Mono.CSharp.Evaluator.ReferenceAssembly(assembly); evaluatorInstance.ReferenceAssembly(assembly); } // Mono.CSharp.Evaluator.Evaluate("null;"); evaluatorInstance.Evaluate("null;"); // n++; // } }
static Assembly CompileCode( string classname, string code, string filename, string[] extra ) { #if USE_ROSLYN_COMPILATION Microsoft.CodeAnalysis. using( var ms = new MemoryStream() ) { string assemblyFileName = "gen" + Guid.NewGuid().ToString().Replace( "-", "" ) + ".dll"; CSharpCompilation compilation = CSharpCompilation.Create( assemblyFileName, new[] { CSharpSyntaxTree.ParseText( fooSource ) }, new[] { new MetadataFileReference(typeof (object).Assembly.Location) }, new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary ) ); compilation.Emit( ms ); Assembly assembly = Assembly.Load( ms.GetBuffer() ); return assembly; } #endif #if USE_MONO_CSHARP { if( sw == null ) sw = new StringWriter(); if( rp == null ) rp = new Mono.CSharp.StreamReportPrinter( sw ); if( cc == null ) cc = new Mono.CSharp.CompilerContext( new Mono.CSharp.CompilerSettings(), rp ); if( r == null ) r = new Mono.CSharp.Report( cc, rp ); if( e == null ) { e = new Mono.CSharp.Evaluator( cc ); e.ReferenceAssembly( Assembly.GetCallingAssembly() ); } Mono.CSharp.CompiledMethod m; long now; now = DateTime.Now.Ticks; Log.log( "About to compile" + (DateTime.Now.Ticks - now )); String s = e.Compile( code, out m ); Log.log( "did compile " + (DateTime.Now.Ticks - now ) ); s = sw.ToString(); if( !s.Contains( "error" ) ) { Assembly asm = ( (Type)e.Evaluate( "typeof(" + classname + ");" ) ).Assembly; Log.log( "got types " + ( DateTime.Now.Ticks - now ) ); return asm; } else Log.log( "Compile Failure: " + s ); } #endif #if USE_EXTERNAL_COMPILER //code = "using System; using Voxelarium.Core; using Voxelarium.Core.Voxels;\nnamespace Voxelarium.Core.Voxels { " + code + "}"; string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder( codeBase ); string path = Uri.UnescapeDataString( uri.Path ); string codeBase_common = Assembly.GetAssembly( typeof( Log ) ).CodeBase; UriBuilder uri_common = new UriBuilder( codeBase_common ); string path_common = Uri.UnescapeDataString( uri_common.Path ); using( Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider() ) { string[] externals; if( extra != null ) { externals = new string[2 + extra.Length]; externals[0] = path; externals[1] = path_common; for( int i = 0; i < extra.Length; i++ ) externals[i + 1] = extra[i]; } else { externals = new string[2]; externals[0] = path; externals[1] = path_common; } CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters( externals ) { // debug info doesn't load anyway? IncludeDebugInformation = true , GenerateInMemory = false , TempFiles = new TempFileCollection( Environment.GetEnvironmentVariable( "TEMP" ), true ) , CompilerOptions = "/debug:pdbonly" }; // already part of the TempFileCollection //parameters.TempFiles.KeepFiles = true; string fileExtension = "pdb"; if( ( parameters.CompilerOptions != null ) && ( CultureInfo.InvariantCulture.CompareInfo.IndexOf( parameters.CompilerOptions, "/debug:pdbonly", CompareOptions.IgnoreCase ) != -1 ) ) { //parameters.TempFiles.AddExtension( fileExtension, true ); } else { //parameters.TempFiles.AddExtension( fileExtension ); } CompilerResults res = foo.CompileAssemblyFromSource( parameters, code ); if( res.Errors.Count == 0 ) { if( AllowAssembly( res.CompiledAssembly ) ) { return res.CompiledAssembly; } } else { StringBuilder sb = new StringBuilder(); foreach( CompilerError err in res.Errors ) { sb.Append( filename + "(" + err.Line + ":" + err.Column + "):" ); sb.Append( err.ErrorText ); sb.Append( "\n" ); } MessageBox.Show( sb.ToString() ); Log.log( sb.ToString() ); } } #endif return null; }
void LoadGame( Context context ) { if( displayInterface != null ) return; //System.Reflection.Emit.AssemblyBuilder //Mono.Runtime. DataTable dt = new DataTable(); Socket sock = null; Environment.CurrentDirectory = Environment.GetFolderPath( Environment.SpecialFolder.UserProfile ); try { sock = new Socket( SocketType.Dgram, ProtocolType.IPv6 ); } catch { try { sock = new Socket( SocketType.Dgram, ProtocolType.IP ); } catch{ } } string save_path = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal ); //Application.Context.Assets. string[] files = { "BEPUphysics.dll" , "protobuf-net.dll" , "TrueTypeSharp.dll" , "Voxelarium.Common.dll" , "Voxelarium.Core.dll" }; string[] slist = context.Assets.List( "" ); if (!File.Exists ( save_path + "/assets3.exported" ) ) { foreach (string file in files) { Stream input = context.Assets.Open (file); Stream output = File.Create (save_path + "/" + file); int size = 0;// = (int)input.Length; byte[] data = new byte[4096]; while( ( size = input.Read( data, 0, 4096 ) ) > 0 ) { output.Write( data, 0, size ); } output.Dispose(); input.Dispose(); } //Stream output2 = File.Create( save_path + "/assets3.exported" ); //output2.Dispose(); } //Assembly a = Assembly.LoadFile( save_path + "/Voxelarium.Core.dll" ); { if( sw == null ) sw = new StringWriter(); if( rp == null ) rp = new Mono.CSharp.StreamReportPrinter( sw ); if( cc == null ) cc = new Mono.CSharp.CompilerContext( new Mono.CSharp.CompilerSettings(), rp ); if( r == null ) r = new Mono.CSharp.Report( cc, rp ); if( e == null ) { e = new Mono.CSharp.Evaluator( cc ); e.ReferenceAssembly( typeof(GLView1).Assembly ); } Mono.CSharp.CompiledMethod m; long now; now = DateTime.Now.Ticks; //Log.log( "About to compile" + (DateTime.Now.Ticks - now )); String s = e.Compile( @" using System; using System.Reflection; using Voxelarium.Android; namespace MyLoader { public class Loader{ static Loader() { } public Loader( string save_path, DisplayInterface ii, object dataTableRef, object socketRef ) { Assembly a = Assembly.LoadFile( save_path + ""/Voxelarium.Core.dll"" ); //Console.WriteLine( ""a is "" + a ); Type gameType = null; Type displayType = null; Type[] types = a.GetTypes(); foreach( Type t in types ) { if( String.Compare( t.ToString(), ""Voxelarium.Core.UI.Display"" ) == 0 ) displayType = t; if( String.Compare( t.ToString(), ""Voxelarium.Core.VoxelGameEnvironment"" ) == 0 ) gameType = t; } object gameObject = Activator.CreateInstance( gameType ); object displayObject = Activator.CreateInstance( displayType, new object[] { gameObject }, null ); MethodInfo mi = displayType.GetMethod( ""Display_UpdateFrame"" ); ii.updateMethod = (UpdateMethod)mi.CreateDelegate( typeof(UpdateMethod), displayObject ); mi = displayType.GetMethod( ""Display_RenderFrame"" ); ii.displayMethod = (UpdateMethod)mi.CreateDelegate( typeof(UpdateMethod), displayObject ); mi = displayType.GetMethod( ""Display_InvalidateContext"" ); ii.invalidateContext = (UpdateMethod)mi.CreateDelegate( typeof(UpdateMethod), displayObject ); mi = displayType.GetMethod( ""Display_SetExit"" ); ii.setExit = (SetExit)mi.CreateDelegate( typeof(SetExit), displayObject ); mi = displayType.GetMethod( ""Display_KeyDown"" ); ii.onKeyDown = (KeyEvent)mi.CreateDelegate( typeof(KeyEvent), displayObject ); mi = displayType.GetMethod( ""Display_KeyUp"" ); ii.onKeyUp = (KeyEvent)mi.CreateDelegate( typeof(KeyEvent), displayObject ); mi = displayType.GetMethod( ""Display_OnTouchEvent"" ); ii.onTouchEvent = (TouchEvent)mi.CreateDelegate( typeof(TouchEvent), displayObject ); mi = displayType.GetMethod( ""Display_SetDisplayParams"" ); ii.setDisplayParams = (SetDisplayParams)mi.CreateDelegate( typeof(SetDisplayParams), displayObject ); //Console.WriteLine( ""Success?"" ); } }}", out m ); //Log.log( "did compile " + (DateTime.Now.Ticks - now ) ); s = sw.ToString(); if( !s.Contains( "error" ) ) { object val = e.Evaluate( "typeof( MyLoader.Loader );" ); if( val != null ) { displayInterface = new DisplayInterface(); looderObject = Activator.CreateInstance( (Type)val, new object[] { save_path, displayInterface, dt, sock }, null ); displayInterface.setExit( this, typeof( GLView1 ).GetMethod( "Exit" ) ); //displayInterface.setDevices( Keyboard, Mouse ); } } //else // Log.log( "Compile Failure: " + s ); } string command = Environment.CommandLine; }
public ScriptEvaluator CompileAndCreateModel() { Message = null; HasError = false; Result = false; var reportWriter = new System.IO.StringWriter(); try { var settings = new Mono.CSharp.CompilerSettings(); settings.GenerateDebugInfo = false; settings.LoadDefaultReferences = true; settings.Optimize = true; settings.WarningsAreErrors = false; var reporter = new Mono.CSharp.ConsoleReportPrinter(reportWriter); var ctx = new Mono.CSharp.CompilerContext(settings, reporter); var scriptEngine = new Mono.CSharp.Evaluator(ctx); scriptEngine.ReferenceAssembly(this.GetType().Assembly); scriptEngine.ReferenceAssembly(typeof(BigDataPipeline.Interfaces.Record).Assembly); scriptEngine.ReferenceAssembly(typeof(Newtonsoft.Json.JsonConvert).Assembly); scriptEngine.ReferenceAssembly(typeof(System.Data.Common.DbConnection).Assembly); scriptEngine.ReferenceAssembly(typeof(Dapper.SqlMapper).Assembly); scriptEngine.ReferenceAssembly(typeof(Npgsql.NpgsqlConnection).Assembly); scriptEngine.ReferenceAssembly(typeof(Amazon.S3.AmazonS3Client).Assembly); if (String.IsNullOrWhiteSpace(Script)) { throw new ArgumentNullException("Expression"); } if (!scriptEngine.Run(Script)) { throw new Exception(reportWriter.ToString()); } if (reporter.ErrorsCount > 0) { throw new Exception(reportWriter.ToString()); } object model = scriptEngine.Evaluate("new EvaluatorDynamicScript();"); if (reporter.ErrorsCount > 0) { throw new Exception(reportWriter.ToString()); } Model = model as IAWSRedshiftPluginDynamicScript; //Mono.CSharp.CompiledMethod method = scriptEngine.Compile ("myClass.Test1 ();"); //if (reporter.ErrorsCount > 0) //{ // throw new Exception (reportWriter.ToString ()); //} //if (method == null) //{ // throw new Exception ("script method not found"); //} // execute method //object result = null; //method (ref result); //// check result //if (result is bool) // Result = (bool)result; //else // Result = false; } catch (Exception e) { Message = e.Message; HasError = true; } return(this); }