public static void Main () { CompilerParameters options = new CompilerParameters (); options.WarningLevel = 4; CodeDomProvider provider = new CSharpCodeProvider (); #if NET_2_0 CompilerResults result = provider.CompileAssemblyFromDom ( options, new CodeSnippetCompileUnit (src)); #else ICodeCompiler compiler = provider.CreateCompiler (); CompilerResults result = compiler.CompileAssemblyFromDom ( options, new CodeSnippetCompileUnit (src)); #endif Assert.IsFalse (result.Errors.HasErrors, "#1"); #if ONLY_1_0 Assert.IsFalse (result.Errors.HasWarnings, "#2"); Assert.AreEqual (0, result.Errors.Count, "#3"); #else Assert.IsTrue (result.Errors.HasWarnings, "#2"); #if MONO Assert.AreEqual (2, result.Errors.Count, "#3"); Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4"); Assert.IsTrue (result.Errors [0].IsWarning, "#5"); Assert.AreEqual ("CS0169", result.Errors [1].ErrorNumber, "#6"); Assert.IsTrue (result.Errors [1].IsWarning, "#7"); #else Assert.AreEqual (1, result.Errors.Count, "#3"); Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4"); Assert.IsTrue (result.Errors [0].IsWarning, "#5"); #endif #endif }
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())}"); } }
object CreateWebServiceFromWsdl(byte[] wsdl) { // generate CodeDom from WSDL ServiceDescription sd = ServiceDescription.Read(new MemoryStream(wsdl)); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ServiceDescriptions.Add(sd); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(""); codeCompileUnit.Namespaces.Add(codeNamespace); importer.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync; importer.Import(codeNamespace, codeCompileUnit); // update web service proxy CodeDom tree to add dynamic support string wsProxyTypeName = FindProxyTypeAndAugmentCodeDom(codeNamespace); // compile CodeDom tree into an Assembly CodeDomProvider provider = CodeDomProvider.CreateProvider("CS"); CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = false; compilerParams.ReferencedAssemblies.Add(typeof(Ops).Assembly.Location); //DLR CompilerResults results = provider.CompileAssemblyFromDom(compilerParams, codeCompileUnit); Assembly generatedAssembly = results.CompiledAssembly; // find the type derived from SoapHttpClientProtocol Type wsProxyType = generatedAssembly.GetType(wsProxyTypeName); if (wsProxyType == null) { throw new InvalidOperationException("Web service proxy type not generated."); } // create an instance of the web proxy type return Activator.CreateInstance(wsProxyType); }
protected override void AddStandardReferences(CompilerParameters parameters) { base.AddStandardReferences(parameters); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, "xunit.core.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, ExecutionHelper.AssemblyFileName)); }
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 void testVb() { try { var baseDir = @"C:\Program Files (x86)\Notepad++\plugins\CSScriptNpp\Roslyn\"; //baseDir = @"E:\Galos\Projects\CS-Script.Npp\CSScript.Npp\src\CSScriptNpp\CSScriptNpp\Roslyn\"; CSSCodeProvider.CompilerPath = baseDir + "vbc.exe"; CSSCodeProvider.ProviderPath = baseDir + "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"; CSSCodeProvider.CompilerServerTimeToLive = 600; CSSCodeProvider.CompilerServerTimeToLive = 6; ICodeCompiler compiler = CSSCodeProvider.CreateCompiler("code.vb"); var compilerParams = new CompilerParameters(); //var file = @"E:\cs-script\samples\Hello.vb"; //compilerParams.ReferencedAssemblies.Add(@"System.Net.Http.Formatting.dll"); //compilerParams.ReferencedAssemblies.Add(@"System.dll"); //var result = compiler.CompileAssemblyFromFile(compilerParams, file); var result = compiler.CompileAssemblyFromSource(compilerParams, @" Imports System Imports System.Windows.Forms Module Module1 Sub Main() Console.WriteLine(""Hello World!(VB)"") End Sub End Module"); bool success = !result.Errors.HasErrors; } catch { } Console.WriteLine("done"); }
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; }
protected override void AddStandardReferences(CompilerParameters parameters) { base.AddStandardReferences(parameters); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, "xunit.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(BasePath, "xunit.extensions.dll")); }
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 CompilingServices(CodeLang codeLang) { this.codeLang = codeLang; this.parameters = new CompilerParameters(); this.filenames = new List<string>(); this.references = new List<string>(); }
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 Build() { CompilerParameters compilerParameters = new CompilerParameters (); compilerParameters.OutputAssembly = kBuildTarget; compilerParameters.ReferencedAssemblies.Add ( ( EditorApplication.applicationContentsPath + "/Frameworks/Managed/UnityEngine.dll" ).Replace ('/', Path.DirectorySeparatorChar) ); List<string> source = GetSource (kSourcePath); CodeDomProvider codeProvider = CodeDomProvider.CreateProvider ("CSharp"); CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource (compilerParameters, source.ToArray ()); if (compilerResults.Errors.Count > 0) { foreach (CompilerError error in compilerResults.Errors) { Debug.LogError (error.ToString ()); } } AssetDatabase.Refresh (); }
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" ); } }
public static bool Compile(string EXE_Name, string Source, string ClientSettings) { CodeDomProvider Compiler = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters Parameters = new CompilerParameters(); CompilerResults cResults = default(CompilerResults); Parameters.GenerateExecutable = true; Parameters.OutputAssembly = EXE_Name; Parameters.ReferencedAssemblies.Add("System.dll"); Parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); Parameters.CompilerOptions = " /target:winexe"; Parameters.TreatWarningsAsErrors = false; cResults = Compiler.CompileAssemblyFromSource(Parameters, new string[] { Source, ClientSettings }); if (cResults.Errors.Count > 0) { foreach (CompilerError CompilerError_loopVariable in cResults.Errors) { CompilerError error = CompilerError_loopVariable; MessageBox.Show("Error: " + error.ErrorText, "", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false; } else if (cResults.Errors.Count == 0) { return true; } return true; }
public static Assembly CompileAssembly(List<GenerateCodeInfo> list) { if ((list == null) || (list.Count == 0)) { throw new ArgumentException("list is null or empty."); } CompilerParameters options = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; Assembly[] assemblyArray = AssemblyHelper.GetAppAssemblys(); foreach (Assembly assembly in assemblyArray) { if (assembly.FullName.StartsWith("Microsoft.GeneratedCode")) continue; GetAllAssembly(assembly, options.ReferencedAssemblies); } GetAllAssembly(typeof(string).Assembly, options.ReferencedAssemblies); GetAllAssembly(typeof(DataTable).Assembly, options.ReferencedAssemblies); GetAllAssembly(typeof(Queryable).Assembly, options.ReferencedAssemblies); GetAllAssembly(typeof(DbContext).Assembly, options.ReferencedAssemblies); string[] sources = Enumerable.Select<GenerateCodeInfo, string>(list, t => { return t.ClassCodeString; }).ToArray<string>(); CompilerResults results = ((CSharpCodeProvider)CodeDomProvider.CreateProvider("CSharp")).CompileAssemblyFromSource(options, sources); if ((results.Errors == null) || !results.Errors.HasErrors) { return results.CompiledAssembly; } Type[] typeArray = Enumerable.Select<GenerateCodeInfo, Type>(list, t => { return t.GenerateParameters.ModelType; }).ToArray<Type>(); throw new CompileException("FastDBEngine's AutoLoader Code Compile Error.", results.Errors, typeArray); }
public static void Compile(string source, string Output, string EFResource, string Icon = null) { CompilerParameters CParams = new CompilerParameters(); CParams.GenerateExecutable = true; CParams.OutputAssembly = Output; string options = "/optimize+ /t:winexe"; if (Icon != null) options += " /win32icon:\"" + Icon + "\""; CParams.CompilerOptions = options; CParams.TreatWarningsAsErrors = false; CParams.ReferencedAssemblies.Add("System.dll"); CParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); CParams.ReferencedAssemblies.Add("System.Drawing.dll"); CParams.ReferencedAssemblies.Add("System.Data.dll"); CParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); CParams.EmbeddedResources.Add(EFResource); Dictionary<string, string> ProviderOptions = new Dictionary<string, string>(); ProviderOptions.Add("CompilerVersion", "v2.0"); CompilerResults Results = new CSharpCodeProvider(ProviderOptions).CompileAssemblyFromSource(CParams, source); if (Results.Errors.Count > 0) { MessageBox.Show(string.Format("The compiler has encountered {0} errors", Results.Errors.Count), "Errors while compiling", MessageBoxButtons.OK, MessageBoxIcon.Error); foreach (CompilerError Err in Results.Errors) { MessageBox.Show(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", Err.ErrorText, Err.Line, Err.Column, Err.FileName), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
protected virtual void AddStandardReferences(CompilerParameters parameters) { 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.Runtime.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); }
private string compilerErrorMessages = ""; // Displayed on the GUI private void Compile(string redBoxerClass, string blueBoxerClass) { try { compilerErrorMessages = ""; // clear any previous messages // ********** Create an instance of the C# compiler //CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CSharpCompiler.CodeCompiler codeCompiler = new CSharpCompiler.CodeCompiler(); // ********** add compiler parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize /warn:0"; compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.IncludeDebugInformation = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Core.dll"); compilerParams.ReferencedAssemblies.Add(Assembly.GetCallingAssembly().Location); string redBoxerSource = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, redBoxerClass) + ".cs"); string blueBoxerSource = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, blueBoxerClass) + ".cs"); // ********** actually compile the code ??????? THIS LINE WORKS IN UNITY EDITOR --- BUT NOT IN BUILD ?????????? CompilerResults resultsRedBoxer = codeCompiler.CompileAssemblyFromSource(compilerParams, redBoxerSource); CompilerResults resultsBlueBoxer = codeCompiler.CompileAssemblyFromSource(compilerParams, blueBoxerSource); // ********** Do we have any compiler errors if (resultsRedBoxer.Errors.Count > 0 || resultsBlueBoxer.Errors.Count > 0) { foreach (CompilerError error in resultsRedBoxer.Errors) { compilerErrorMessages = compilerErrorMessages + error.ErrorText + '\n'; } } else { // ********** get a hold of the actual assembly that was generated Assembly generatedRedAssembly = resultsRedBoxer.CompiledAssembly; Assembly generatedBlueAssembly = resultsBlueBoxer.CompiledAssembly; if (generatedRedAssembly != null && generatedBlueAssembly != null) { // get type of class Calculator from just loaded assembly Type redClassType = generatedRedAssembly.GetType(redBoxerClass); Type blueClassType = generatedBlueAssembly.GetType(blueBoxerClass); RedStrategy = (AbstractBoxingStrategy)Activator.CreateInstance(redClassType); BlueStrategy = (AbstractBoxingStrategy)Activator.CreateInstance(blueClassType); // Say success! compilerErrorMessages = "Success!"; } } } catch (Exception o) { Debug.LogError("" + o.Message + "\n" + o.Source + "\n" + o.StackTrace + "\n"); throw o; } Debug.Log(compilerErrorMessages); }
public string UserFriendlifyAndEvaluate( string inToEval ) { inToEval = inToEval.ToLower(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add( "System.dll" ); //if we want to do more, we have to add UnityEngine and then find our assemblies in the library //kinda overkill for now... cp.GenerateExecutable = false; cp.GenerateInMemory = true; //do weh ave to wrap all the functions we want to work? that's kinda annoying string code = "using System;" + "namespace Evaluator" + "{ " + " public class CreatedEvaluator" + " { " + " public string GetResult()" + " { " + " return (" + inToEval + ").ToString( \"f4\" ); " + " } " + " public double sin( double inD ) { return Math.Sin( inD ); } " + " public double cos( double inD ) { return Math.Cos( inD ); } " + " public double tan( double inD ) { return Math.Tan( inD ); } " + " public double asin( double inD ) { return Math.Asin( inD ); } " + " public double acos( double inD ) { return Math.Acos( inD ); } " + " public double atan( double inD ) { return Math.Atan( inD ); } " + " public double pow( double inA, double inB ) { return Math.Pow( inA, inB ); } " + " public double exp( double inD ) { return Math.Exp( inD ); } " + " public double ln( double inD ) { return Math.Log( inD ); } " + " public double log( double inD ) { return Math.Log10( inD ); } " + " public double pi { get{ return Math.PI; } } " + " } " + "}"; CompilerResults cr = _CSharpProvider.CompileAssemblyFromSource(cp, code ); if (cr.Errors.HasErrors) { StringBuilder errors = new StringBuilder(); errors.Append("Error Calculating: "); foreach( CompilerError ce in cr.Errors ) { errors.AppendLine( ce.ErrorText ); } Debug.LogError( errors.ToString() ); return null; } else { Assembly a = cr.CompiledAssembly; object createdEvaluator = a.CreateInstance( "Evaluator.CreatedEvaluator" ); MethodInfo mi = createdEvaluator.GetType().GetMethod( "GetResult" ); return mi.Invoke( createdEvaluator, null ).ToString(); } }
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 void TestWithInProcCompiler(string asm) { IDictionary<string, string> providerOptions = new Dictionary<string, string>(); providerOptions["CompilerVersion"] = "3.5"; CompilerParameters compilerParams = new CompilerParameters(); compilerParams.ReferencedAssemblies.Add(asm); ICodeCompiler compiler = CodeDomProvider.CreateProvider("C#").CreateCompiler(); var result = compiler.CompileAssemblyFromSource(compilerParams, ""); var erorr = result.Errors[0]; }
private static CompilerParameters CreateCompilerParameters() { var compilerParams = new CompilerParameters { CompilerOptions = "/target:library /optimize", GenerateExecutable = false, GenerateInMemory = true, IncludeDebugInformation = false }; compilerParams.ReferencedAssemblies.Add("System.dll"); return compilerParams; }
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); }
static StringEvaluator() { //deprecated: ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler(); var compiler = CodeDomProvider.CreateProvider("jscript"); var parameters = new CompilerParameters {GenerateInMemory = true}; var results = compiler.CompileAssemblyFromSource(parameters, JscriptSource); var assembly = results.CompiledAssembly; EvaluatorType = assembly.GetType("Evaluator.Evaluator"); Evaluator = Activator.CreateInstance(EvaluatorType); }
protected void Button1_Click(object sender, EventArgs e) { CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); string Output = "Out.exe"; Button ButtonObject = (Button)sender; TextBox3.Text = ""; System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = Output; CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, TextBox2.Text); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { TextBox3.Text = TextBox3.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { TextBox3.Text = "Success!"; #region if (ButtonObject.Text == "EXECUTE") { Process myProcess = new Process(); ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Output); myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); StreamReader myStreamReader = myProcess.StandardOutput; string myString = myStreamReader.ReadLine(); myProcess.WaitForExit(); myProcess.Close(); TextBox3.Text = myString; } #endregion } }
static int Main(string[] args) { var provOptions = new Dictionary<string, string>(); provOptions.Add("CompilerVersion", "v4"); var provider = CodeDomProvider.CreateProvider("CSharp", provOptions); String[] referenceAssemblies = { "System.dll" }; CompilerParameters cp = new CompilerParameters(referenceAssemblies, "wat.exe", false); cp.GenerateExecutable = true; CompilerResults cr = provider.CompileAssemblyFromSource(cp, "class X {}"); foreach (var o in cr.Output) { Console.WriteLine(o); } return 0; }
/// <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); }
private static void CreateResourceFile( string csFile, string resFile, string outputDir, out string sourceHash, out int viewCount) { viewCount = -1; sourceHash = string.Empty; var codeProvider = new CSharpCodeProvider(); var inMemoryCodeCompiler = codeProvider.CreateCompiler(); var parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.Data.Entity.dll"); parameters.GenerateInMemory = true; CompilerResults results = inMemoryCodeCompiler.CompileAssemblyFromFile(parameters, csFile); if (results.Errors.Count == 0) { Assembly resultingAssembly = results.CompiledAssembly; Type[] typeList = resultingAssembly.GetTypes(); foreach (Type type in typeList) { if (type.BaseType == typeof(EntityViewContainer)) { MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); var instance = (EntityViewContainer)Activator.CreateInstance(type); sourceHash = instance.HashOverAllExtentViews; viewCount = instance.ViewCount; using (var resWriter = new ResourceWriter(Path.Combine(outputDir, resFile))) { foreach (MethodInfo method in methodInfo) { if (char.IsDigit(method.Name, method.Name.Length - 1)) { var result = (KeyValuePair<string, string>)method.Invoke(instance, null); resWriter.AddResource(method.Name.Replace("GetView", string.Empty), result); } } resWriter.Generate(); resWriter.Close(); } } } } else { Console.WriteLine("Unable to Generate Resource File"); } }
public static Boolean init; //Check if code is complied, so that it doesn't have to do it everytime #endregion Fields #region Methods /* Compiles the files in the AI sub-dirctory */ public static void initAI() { if (!init) { AIPrograms = new Dictionary<string, AIBase>();//Create the hashmap CSharpCodeCompiler provider = new CSharpCodeCompiler(); //Get the complier CompilerParameters parameters = new CompilerParameters(); foreach (string file in Directory.GetFiles("AI")) { //For every file in the AI directory Debug.Log ("file: " + file); parameters = new CompilerParameters();//Generate new parametes foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { parameters.ReferencedAssemblies.Add(asm.Location);//Link all the assmeblies to this new file that we are compiling } Debug.Log(Path.GetFileNameWithoutExtension(file)); //Read file StreamReader theReader = new StreamReader(file, Encoding.Default); string code = theReader.ReadToEnd(); //Actually compile CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); //Check for errors and print them. It would be good to display these later. if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { Debug.Log("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";"); } } //Create results. Note this will cause a crash if there are errors in scripts. Should change Assembly assembly = results.CompiledAssembly; Debug.Log("Assembly "+assembly); //Get the name of the C# script assembly. Type program = assembly.GetType(Path.GetFileNameWithoutExtension(file)); //Get the constructor for that script to generate a new class ConstructorInfo main = program.GetConstructor(new Type[0]); //Convert it to an AI script AIBase ai = (AIBase)main.Invoke(new System.Object[0]); //Add to hashmap under its name. AIPrograms.Add(Path.GetFileNameWithoutExtension(file), ai); } } }
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 InterpreterResult Eval(string sCSCode, string sSCMethods, string sCustomAssemblies, string sCustomUsings, Dictionary <string, object> arguments, bool safe) { //validate Custom Assemblies string envFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\"; List <string> CustomAssembliesPath = new List <string>(); List <string> CustomAssemblies = new List <string>(); //Perform several replacements as separators sCustomAssemblies = sCustomAssemblies.Replace("\r\n", "|"); sCustomAssemblies = sCustomAssemblies.Replace("\n", "|"); sCustomAssemblies = sCustomAssemblies.Replace(",", "|"); sCustomAssemblies = sCustomAssemblies.Replace(";", "|"); string[] split = sCustomAssemblies.Split("|".ToCharArray()); if (split.Length > 0) { FileInfo file; string path; foreach (string testAssembly in split) { path = envFolder + testAssembly; file = new FileInfo(path); if (file.Exists) { CustomAssembliesPath.Add(path); CustomAssemblies.Add(Path.GetFileNameWithoutExtension(path)); } } } //Perform several replacements as separators sCustomUsings = sCustomUsings.Replace("\r\n", "|"); sCustomUsings = sCustomUsings.Replace("\n", "|"); sCustomUsings = sCustomUsings.Replace(",", "|"); List <string> CustomUsings = TypesHelper.StringSplit(sCustomUsings, "|", true, true); CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.IncludeDebugInformation = true; cp.GenerateInMemory = true; /*cp.GenerateInMemory = false; * cp.OutputAssembly = "InterpreterAssembly.dll";*/ //Custom assemblies foreach (string customPath in CustomAssembliesPath) { cp.ReferencedAssemblies.Add(customPath); } //Generate the code StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using System.Data.SqlClient;\n"); sb.Append("using System.Windows.Forms;\n"); sb.Append("using System.Drawing;\n"); //Custom usings foreach (string customPath in CustomUsings) { sb.Append(customPath + "\n"); } List <string> argNames = new List <string>(arguments.Keys); sb.Append("public class CSCodeEvaler{ \n"); sb.Append(sSCMethods); string argsText = ""; foreach (string argKey in argNames) { argsText += argKey + ","; } if (argsText.Length > 1) { argsText = argsText.Substring(0, argsText.Length - 1); } sb.Append("public object EvalCode(" + argsText + "){\n"); sb.Append(sCSCode + "\n"); if (!sCSCode.Contains("return ")) { sb.Append("return null;"); } sb.Append("} \n"); sb.Append("} \n"); string code = sb.ToString(); CompilerResults cr = c.CompileAssemblyFromSource(cp, code); if (cr.Errors.Count > 0) { return(new InterpreterResult(code, false, cr.Errors)); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("EvalCode"); object[] parameters = new object[argNames.Count]; int cnt = 0; foreach (string argKey in argNames) { parameters[cnt] = arguments[argKey]; cnt++; } object returnedValue = null; try { returnedValue = CSInterpreter.Invoke(mi, o, parameters); } catch (Exception e) { if (!safe) { e.HelpLink += sCSCode; throw; } string msg = e.Message + "\n" + e.StackTrace; if (e.InnerException != null) { msg = e.InnerException.Message + "\n" + e.InnerException.StackTrace; } return(new InterpreterResult(code, false, msg)); } finally { } return(new InterpreterResult(code, true, returnedValue)); }
// Utility method: This method runs a script written in a language for which we have the domain compiler public object Run(string in_lang, string in_source) { string tempPath = System.IO.Path.GetTempPath() + "DotNET-Script-Tmp"; try { if (!CodeDomProvider.IsDefinedLanguage(in_lang)) { // No provider defined for this language string sMsg = "No compiler is defined for " + in_lang; Console.WriteLine(sMsg); return(null); } CodeDomProvider compiler = CodeDomProvider.CreateProvider(in_lang); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.OutputAssembly = tempPath; parameters.MainClass = "Script.Main"; parameters.IncludeDebugInformation = false; parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); 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.Xaml.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll"); string dotNetSDKPath = AppDomain.CurrentDomain.BaseDirectory; //string dotNetSDKPath = System.IO.Path.GetDirectoryName (Assembly.GetAssembly (typeof (MObject)).Location) + @"\"; parameters.ReferencedAssemblies.Add(dotNetSDKPath + "openmayacpp.dll"); parameters.ReferencedAssemblies.Add(dotNetSDKPath + "openmayacs.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(parameters, in_source); if (results.Errors.Count > 0) { string sErrors = "Search Condition is invalid:\n"; foreach (CompilerError err in results.Errors) { sErrors += err.ToString() + "\n"; } sErrors += "\nImportant! because we compile and run code on the fly,\n" + "the current working directory *must* be the Maya directory where resides" + "the Maya API .NET assemblies (I.e. openmayacpp.dll / openmayacs.dll).\n"; MessageBox.Show(sErrors, "DAG Explorer", MessageBoxButton.OK, MessageBoxImage.Error); } else { object o = results.CompiledAssembly.CreateInstance("Script"); Type type = o.GetType(); MethodInfo m = type.GetMethod("Main"); Object Result = m.Invoke(o, null); // Done with the temp assembly if (File.Exists(tempPath)) { File.Delete(tempPath); } return(Result); } } catch (Exception e) { Console.WriteLine(e.ToString()); // Done with the temp assembly if (File.Exists(tempPath)) { File.Delete(tempPath); } } return(null); }
public string _GetResponseFileCmdArgs(CompilerParameters options, string cmdArgs) { return(GetResponseFileCmdArgs(options, cmdArgs)); }
static void Main(string[] args) { try { CmdLineParser cmdLineParser = new CmdLineParser("EosResourceCompiler v1.0"); cmdLineParser.Add(new ArgumentDefinition("source", 1, "Archivo de entrada.", true)); cmdLineParser.Add(new OptionDefinition("O", "Carpeta de salida.")); cmdLineParser.Add(new OptionDefinition("V", "Muestra informacion detallada.")); cmdLineParser.Add(new OptionDefinition("P", "Parametro personalizado.", false, true)); if (args.Length == 0) { Console.WriteLine(cmdLineParser.HelpText); Console.ReadKey(true); } else { CompilerParameters parameters = new CompilerParameters(); string outputFolder = null; string sourceFileName = null; cmdLineParser.Parse(args); foreach (OptionInfo optionInfo in cmdLineParser.Options) { switch (optionInfo.Name) { case "O": outputFolder = optionInfo.Value; break; case "V": parameters.Add("verbose"); break; case "P": parameters.Add(optionInfo.Value); break; } } foreach (ArgumentInfo argumentInfo in cmdLineParser.Arguments) { switch (argumentInfo.Name) { case "source": sourceFileName = argumentInfo.Value; break; } } if (String.IsNullOrEmpty(sourceFileName)) { throw new InvalidOperationException("No se especifico el fichero fuente."); } if (outputFolder == null) { outputFolder = Path.GetDirectoryName(sourceFileName); } ResourcePool resources; using (Stream stream = new FileStream( sourceFileName, FileMode.Open, FileAccess.Read, FileShare.None)) { IResourceReader reader = new ResourceReader(stream); resources = reader.Read(); } IResourceCompiler compiler = new ResourceCompiler(); compiler.Compile(resources, outputFolder, parameters); } } catch (Exception e) { while (e != null) { Console.WriteLine(e.Message); e = e.InnerException; } Console.ReadKey(true); } }
private void buttonTestCode_Click(object sender, EventArgs ev) { WriteLine($"Compiling code ...", Color.Black); string code = ""; // We are running code in a normal way if (GlobalCode != null) { code = TrainProgramEvent.Code.Replace("%Code%", CodeEvent.CodeToRun.Replace("Wait(", "await Task.Delay(")); code = code.Replace("/*%GlobalCode%*/", GlobalCode.CodeToRun.Replace("Wait(", "await Task.Delay(")); } // We are editing the global code else { code = TrainProgramEvent.Code.Replace("%Code%", ""); code = code.Replace("/*%GlobalCode%*/", CodeEvent.CodeToRun.Replace("Wait(", "await Task.Delay(")); } //var options = new Dictionary<string, string> { { "CompilerVersion", "v5.0" } }; CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); // Reference to System.Drawing library parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("LegoTrainProject.exe"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.ReferencedAssemblies.Add("System.Drawing.dll"); // True - memory generation, false - external file generation parameters.GenerateInMemory = true; // True - exe file generation, false - dll file generation parameters.GenerateExecutable = false; // Run the code! CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); WriteLine($"Compiling failed.", Color.Red); foreach (CompilerError error in results.Errors) { WriteLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText), Color.Red); } } else { WriteLine($"Compiling successful!", Color.Green); // We don't run the code if we are editing the global code itself. if (GlobalCode != null) { Assembly assembly = results.CompiledAssembly; Type program = assembly.GetType("LegoTrainProject.DynamicCode"); MethodInfo main = program.GetMethod("ExecuteCode"); WriteLine($"Executing code ...", Color.Black); try { main.Invoke(null, new object[] { CodeEvent, hubs, sections }); } catch (Exception ex) { WriteLine("Exception while executing your sequence: " + ex.Message, Color.Red); return; } WriteLine($"Executing completed!", Color.Green); } } }
public void compile(string path) { string basecode = Properties.Resources.Code; basecode = BuildBase(basecode); List <string> code = new List <string>(); code.Add(basecode); string manifest = @"<?xml version=""1.0"" encoding=""utf-8""?> <assembly manifestVersion=""1.0"" xmlns=""urn:schemas-microsoft-com:asm.v1""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""highestAvailable"" uiAccess=""false"" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1""> <application> </application> </compatibility> </assembly> "; File.WriteAllText(Application.StartupPath + @"\manifest.manifest", manifest); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters compars = new CompilerParameters(); compars.ReferencedAssemblies.Add("System.Net.dll"); compars.ReferencedAssemblies.Add("System.Net.Http.dll"); compars.ReferencedAssemblies.Add("System.dll"); compars.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compars.ReferencedAssemblies.Add("System.Drawing.dll"); compars.ReferencedAssemblies.Add("System.Management.dll"); compars.ReferencedAssemblies.Add("System.IO.dll"); compars.ReferencedAssemblies.Add("System.IO.compression.dll"); compars.ReferencedAssemblies.Add("System.IO.compression.filesystem.dll"); compars.ReferencedAssemblies.Add("System.Core.dll"); compars.ReferencedAssemblies.Add("System.Security.dll"); compars.ReferencedAssemblies.Add("System.Diagnostics.Process.dll"); string ospath = Path.GetPathRoot(Environment.SystemDirectory); string tempPath = ospath + "Temp"; compars.GenerateExecutable = true; compars.OutputAssembly = path; compars.GenerateInMemory = false; compars.TreatWarningsAsErrors = false; compars.CompilerOptions += "/t:winexe /unsafe /platform:x86"; if (!string.IsNullOrEmpty(metroTextBox7.Text) || !string.IsNullOrWhiteSpace(metroTextBox7.Text) && metroTextBox7.Text.Contains(@"\") && metroTextBox7.Text.Contains(@":") && metroTextBox7.Text.Length >= 7) { compars.CompilerOptions += " /win32icon:" + @"""" + metroTextBox7.Text + @""""; } else if (string.IsNullOrEmpty(metroTextBox7.Text) || string.IsNullOrWhiteSpace(metroTextBox7.Text)) { } System.Threading.Thread.Sleep(100); CompilerResults res = provider.CompileAssemblyFromSource(compars, code.ToArray()); if (res.Errors.Count > 0) { try { File.Delete(Application.StartupPath + @"\manifest.manifest"); } catch { } foreach (CompilerError ce in res.Errors) { MessageBox.Show(ce.ToString()); } } else { try { File.Delete(Application.StartupPath + @"\manifest.manifest"); } catch { } try { File.Delete(tempPath + @"\ConfuserEx.zip"); Directory.Delete(tempPath + @"\ConfuserEx", true); File.Delete(Path.GetDirectoryName(path) + "\\Names.txt"); } catch { } MessageBox.Show("Stealer compiled!"); } }
/* goodB2G1() - use badsource and goodsink by changing second IO.staticTrue to IO.staticFalse */ private void GoodB2G1() { string data; if (IO.staticTrue) { data = ""; /* Initialize data */ { try { /* read string from file into data */ using (StreamReader sr = new StreamReader("data.txt")) { /* POTENTIAL FLAW: Read data from a file */ /* This will be reading the first "line" of the file, which * could be very long if there are little or no newlines in the file */ data = sr.ReadLine(); } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
protected override CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { return(FromDomWorker(options, ea)); }
protected override CompilerResults FromSource(CompilerParameters options, string source) { return(FromSourceWorker(options, source)); }
protected override CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { return(FromSourceWorker(options, sources)); }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void GoodB2G2() { string data; if (IO.STATIC_READONLY_FIVE == 5) { data = ""; /* Initialize data */ /* read input from WebClient */ { try { using (WebClient client = new WebClient()) { using (StreamReader sr = new StreamReader(client.OpenRead("http://www.example.org/"))) { /* POTENTIAL FLAW: Read data from a web server with WebClient */ /* This will be reading the first "line" of the response body, * which could be very long if there are no newlines in the HTML */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.STATIC_READONLY_FIVE == 5) { int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
static void ExtractClientDBData() { Console.WriteLine("Searching for available ClientDB (dbc & db2) files..."); var fileList = new List <string>(); var wowBin = cascHandler.BasePath + "/Wow.exe"; var wowBBin = cascHandler.BasePath + "/WowB.exe"; var wowTBin = cascHandler.BasePath + "/WowT.exe"; var wowXBin = appFolder + "/Contents/MacOS/World of Warcraft"; var bin = ""; if (File.Exists(wowBin)) { bin = wowBin; } else if (File.Exists(wowTBin)) { bin = wowTBin; } else if (File.Exists(wowXBin)) { bin = wowXBin; } else if (File.Exists(wowBBin)) { bin = wowBBin; } else { Console.WriteLine("No valid World of Warcraft version found."); Console.ReadKey(); return; } appFolder = wowBin; // Get dbc files from wow bin using (var sr = new StreamReader(bin)) { var text = sr.ReadToEnd(); foreach (Match dbc in Regex.Matches(text, @"DBFilesClient\\([A-Za-z0-9\-_]+)\.(dbc|db2)")) { fileList.Add(dbc.Value.Replace(@"\\", @"\")); } } // add missing dbc/db2 file names. FileList.ClientDBFileNames.ForEach(f => { if (!fileList.Contains(f)) { fileList.Add(f); } }); Console.WriteLine("Getting available locales..."); var locales = new Dictionary <string, Locales>(); if (!string.IsNullOrEmpty(Program.locale)) { locales.Add(Program.locale, (Locales)Enum.Parse(typeof(Locales), Program.locale)); } else { var buildInfo = File.ReadAllText(cascHandler.BasePath + "/.build.info").Split(new[] { '|' })[21]; var buildInfoLocales = Regex.Matches(buildInfo, " ([A-Za-z]{4}) speech"); foreach (Match m in buildInfoLocales) { var flagString = m.Value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]; var localFlag = (Locales)Enum.Parse(typeof(Locales), flagString); if (!locales.ContainsKey(flagString)) { locales.Add(flagString, localFlag); Console.WriteLine($"Found locale '{flagString}'."); } } } Directory.CreateDirectory(Directory.GetParent(appFolder) + "/Project-WoW/ClientDB/SQL"); Directory.CreateDirectory(Directory.GetParent(appFolder) + "/Project-WoW/ClientDB/Files"); /// Files Console.WriteLine("Extracting files..."); var fileCtr = 0; var fileErrors = new List <string>(); foreach (var file in fileList) { var nameOnly = file.Replace(@"\\", "").Replace(@"DBFilesClient\", ""); foreach (var locale in locales) { var dbStream = cascHandler.ReadFile(file, locale.Value); Console.Write($"Writing file {nameOnly} ({locale.Key})..."); if (dbStream != null) { Directory.CreateDirectory($"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/Files/{locale.Key}"); Task.Run(() => FileWriter.WriteFile(dbStream, $"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/Files/{locale.Key}/{nameOnly}")); Console.ForegroundColor = ConsoleColor.Green; Console.Write("Done."); Console.WriteLine(); fileCtr++; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error."); fileErrors.Add($"{nameOnly} ({locale.Key})"); } Console.ForegroundColor = ConsoleColor.Gray; } } Console.WriteLine($"Extracted {fileCtr} files."); Console.WriteLine(); Console.WriteLine("Getting structures..."); var existingStructList = new List <string>(); var structsPath = cascHandler.BasePath + "/Structures/"; if (!Directory.Exists(structsPath)) { Directory.CreateDirectory(structsPath); } var structureNames = Directory.GetFiles(structsPath); var structureNameList = new List <string>(structureNames.Length); foreach (var s in structureNames) { structureNameList.Add(Path.GetFileNameWithoutExtension(s)); } foreach (var s in fileList) { var nameOnly = s.Replace(@"\\", "").Replace(@"DBFilesClient\", "").Replace(@".dbc", "").Replace(@".db2", ""); if (structureNameList.Contains(nameOnly)) { existingStructList.Add(s); } } Console.WriteLine($"Found {existingStructList.Count} structures."); Console.WriteLine(); Console.WriteLine("Generating SQL data..."); Console.WriteLine(); var fileLock = new object(); var generatedTables = new List <string>(); var counter = 0; var noLocaleMSSQL = new StreamWriter($"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/SQL/DataDB.MSSQL.sql"); var noLocaleMYSQL = new StreamWriter($"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/SQL/DataDB.MYSQL.sql"); foreach (var locale in locales) { var localeMSSQL = new StreamWriter($"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/SQL/{locale.Key}_DataDB.MSSQL.sql"); var localeMYSQL = new StreamWriter($"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/SQL/{locale.Key}_DataDB.MYSQL.sql"); foreach (var file in existingStructList) { var nameOnly = file.Replace(@"\\", "").Replace(@"DBFilesClient\", ""); var path = $"{Directory.GetParent(appFolder)}/Project-WoW/ClientDB/Files/{locale.Key}/{nameOnly}"; if (!File.Exists(path)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{path} doesn't exist."); Console.WriteLine("Skip it."); continue; } var dbStream = new MemoryStream(File.ReadAllBytes(path)); if (dbStream != null) { nameOnly = nameOnly.Replace(@".dbc", "").Replace(@".db2", ""); var ccp = new CSharpCodeProvider(); var paramss = new CompilerParameters(); paramss.GenerateExecutable = false; paramss.GenerateInMemory = true; paramss.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); var file1 = File.ReadAllText(structsPath + nameOnly + ".cs"); var code = new[] { file1 }; var result = ccp.CompileAssemblyFromSource(paramss, code); var type = result.CompiledAssembly.GetTypes()[0]; var hasStringProperties = type.GetProperties().Any(p => p.PropertyType == typeof(string)); var pluralized = nameOnly.Replace(@".dbc", "").Replace(@".db2", ""); pluralized.Insert(0, pluralized[0].ToString().ToUpperInvariant()); pluralized.Remove(1); if (hasStringProperties) { pluralized = pluralized + "_" + locale.Key; } if (!generatedTables.Contains(pluralized)) { generatedTables.Add(pluralized); if (hasStringProperties) { Console.Write($"Generating SQL data for {pluralized} ({locale.Key})..."); } else { Console.Write($"Generating SQL data for {pluralized}..."); } var dbTable = DBReader.Read(dbStream, type); lock (fileLock) { if (hasStringProperties) { localeMYSQL.Write(GenerateMYSQLData(nameOnly, pluralized, dbTable)); localeMSSQL.Write(GenerateMSSQLData(pluralized, dbTable)); } else { noLocaleMYSQL.Write(GenerateMYSQLData(nameOnly, pluralized, dbTable)); noLocaleMSSQL.Write(GenerateMSSQLData(pluralized, dbTable)); } } counter++; Console.ForegroundColor = ConsoleColor.Green; Console.Write("Done."); Console.WriteLine(); } } Console.ForegroundColor = ConsoleColor.Gray; } localeMSSQL.Dispose(); localeMYSQL.Dispose(); } noLocaleMSSQL.Dispose(); noLocaleMYSQL.Dispose(); Console.WriteLine("Generated Sql data for {0} ClientDB(s).", existingStructList.Count); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(); if (fileErrors.Count > 0) { Console.WriteLine("ERROS WHILE EXTRACTING:"); foreach (var s in fileErrors) { Console.WriteLine(s); } } Console.ForegroundColor = ConsoleColor.Gray; }
public void CompileCode() { if (!Options.CompileCode) { return; } var assemblyFile = string.IsNullOrEmpty(Options.LibraryName) ? "out.dll" : Options.LibraryName + ".dll"; var docFile = Path.ChangeExtension(Path.GetFileName(assemblyFile), ".xml"); var compilerOptions = new StringBuilder(); compilerOptions.Append(" /doc:" + docFile); compilerOptions.Append(" /debug:pdbonly"); compilerOptions.Append(" /unsafe"); var compilerParameters = new CompilerParameters { GenerateExecutable = false, TreatWarningsAsErrors = false, OutputAssembly = assemblyFile, GenerateInMemory = false, CompilerOptions = compilerOptions.ToString() }; // add a reference to System.Core compilerParameters.ReferencedAssemblies.Add(typeof(Enumerable).Assembly.Location); var location = Assembly.GetExecutingAssembly().Location; var outputDir = Path.GetDirectoryName(location); var locationRuntime = Path.Combine(outputDir, "CppSharp.Runtime.dll"); compilerParameters.ReferencedAssemblies.Add(locationRuntime); compilerParameters.ReferencedAssemblies.AddRange(Symbols.Libraries.SelectMany( lib => lib.Dependencies.Where( d => libraryMappings.ContainsKey(d) && !compilerParameters.ReferencedAssemblies.Contains(libraryMappings[d])) .Select(l => libraryMappings[l])).ToArray()); var codeProvider = new CSharpCodeProvider( new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); var compilerResults = codeProvider.CompileAssemblyFromFile( compilerParameters, Options.CodeFiles.ToArray()); var errors = compilerResults.Errors.Cast <CompilerError>(); foreach (var error in errors.Where(error => !error.IsWarning)) { Diagnostics.Error(error.ToString()); } if (compilerResults.Errors.Count == 0) { var wrapper = Path.Combine(outputDir, assemblyFile); foreach (var library in Options.Libraries) { libraryMappings[library] = wrapper; } } }
public override void Bad() { string data; if(IO.StaticReturnsTrueOrFalse()) { /* get environment variable ADD */ /* POTENTIAL FLAW: Read data from an environment variable */ data = Environment.GetEnvironmentVariable("ADD"); } else { /* FIX: Set data to an integer represented as a string */ data = "10"; } if(IO.StaticReturnsTrueOrFalse()) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */ CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } else { int? parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
static Delegate CreateDelegate(string value) { if (value.ToLower().StartsWith("code:")) { // compile with CodeDom, return Action<UIConstructor> string source = #region source @"using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Xact; using PoroCYon.XnaExtensions; using TAPI.SDK.GUI.Controls; namespace TAPI.SDK.GUI { public static class UIConstructorScript { public static Action<UIConstructor> ScriptAction { get { return ExecuteScript; } } static void ExecuteScript(UIConstructor ui) { " + value + @" } } } "; #endregion CodeDomProvider cdp = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true, CompilerOptions = "/optimize", IncludeDebugInformation = false, OutputAssembly = "TAPI.SDK.GUI.ScriptAssembly" }; cp.ReferencedAssemblies.AddRange(new string[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Numerics.dll", "Microsoft.Xna.Framework.dll", "Microsoft.Xna.Framework.Game.dll", "Microsoft.Xna.Framework.Graphics.dll", "Microsoft.Xna.Framework.Xact.dll", "PoroCYon.XnaExtensions.dll", "tAPI.exe", "TAPI.SDK.dll", Assembly.GetCallingAssembly().FullName }); CompilerResults cr = cdp.CompileAssemblyFromSource(cp, source); if (cr.Errors.HasErrors) { for (int i = 0; i < cr.Errors.Count; i++) { TConsole.Print(cr.Errors[i]); } return(null); } return((Action <XmlUIConstructor>)cr.CompiledAssembly .GetType("TAPI.SDK.GUI.UIConstructorScript", true, true) .GetProperty("ScriptAction", BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static) .GetValue(null, null)); } string[] split = value.Split('.'); string @class = split[0]; for (int i = 1; i < split.Length; i++) { @class += "." + split[i]; } string method = split[split.Length - 1]; Type t = Type.GetType(@class, false, true); if (t == null) { return(null); } MethodInfo mi = t.GetMethod(method, BindingFlags.IgnoreCase | BindingFlags.Static); if (mi == null) { return(null); } return(Delegate.CreateDelegate(Expression.GetDelegateType((from p in mi.GetParameters() select p.ParameterType) .Concat(new Type[1] { mi.ReturnType }).ToArray()), null, method, true, false)); }
protected override CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { return(FromDomWorker(options, e)); }
private static void AddReferencesFromFile(CompilerParameters compilerParams, string nrfFile) { AddReferencesFromFile(compilerParams, File.OpenRead(nrfFile)); }
public CompilerResults _FromSourceBatch(CompilerParameters options, string[] sources) { return(FromSourceBatch(options, sources)); }
public void CompileFromFileBatch_Library_InMemory() { // create source file string sourceFile1 = Path.Combine(_tempDir, "file1." + _codeProvider.FileExtension); using (FileStream f = new FileStream(sourceFile1, FileMode.Create)) { using (StreamWriter s = new StreamWriter(f)) { s.Write(_sourceLibrary1); s.Close(); } f.Close(); } string sourceFile2 = Path.Combine(_tempDir, "file2." + _codeProvider.FileExtension); using (FileStream f = new FileStream(sourceFile2, FileMode.Create)) { using (StreamWriter s = new StreamWriter(f)) { s.Write(_sourceLibrary2); s.Close(); } f.Close(); } CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.TempFiles = new TempFileCollection(_tempDir); #if NET_2_0 options.EmbeddedResources.Add(sourceFile1); options.LinkedResources.Add(sourceFile2); #endif ICodeCompiler compiler = _codeProvider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromFileBatch(options, new string [] { sourceFile1, sourceFile2 }); // verify compilation was successful AssertCompileResults(results, true); Assembly compiledAssembly = results.CompiledAssembly; Assert.IsNotNull(compiledAssembly, "#A1"); Assert.AreEqual(string.Empty, compiledAssembly.Location, "#A2"); Assert.IsNull(results.PathToAssembly, "#A3"); Assert.IsNotNull(options.OutputAssembly, "#A4"); Assert.AreEqual(".dll", Path.GetExtension(options.OutputAssembly), "#A5"); Assert.AreEqual(_tempDir, Path.GetDirectoryName(options.OutputAssembly), "#A6"); Assert.IsFalse(File.Exists(options.OutputAssembly), "#A7"); Assert.IsNotNull(compiledAssembly.GetType("Test1"), "#B1"); Assert.IsNotNull(compiledAssembly.GetType("Test2"), "#B2"); // verify we don't cleanup files in temp directory too agressively string [] tempFiles = Directory.GetFiles(_tempDir); Assert.AreEqual(2, tempFiles.Length, "#C1"); Assert.IsTrue(File.Exists(sourceFile1), "#C2"); Assert.IsTrue(File.Exists(sourceFile2), "#C3"); #if NET_2_0 string[] resources = compiledAssembly.GetManifestResourceNames(); Assert.IsNotNull(resources, "#D1"); Assert.AreEqual(2, resources.Length, "#D2"); Assert.IsTrue(resources[0] == "file1.cs" || resources [0] == "file2.cs", "#E1"); Assert.IsNull(compiledAssembly.GetFile("file1.cs"), "#E2"); Assert.IsNotNull(compiledAssembly.GetManifestResourceStream("file1.cs"), "#E3"); ManifestResourceInfo info = compiledAssembly.GetManifestResourceInfo("file1.cs"); Assert.IsNotNull(info, "#E4"); Assert.IsNull(info.FileName, "#E5"); Assert.IsNull(info.ReferencedAssembly, "#E6"); Assert.AreEqual((ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile), info.ResourceLocation, "#E7"); Assert.IsTrue(resources[1] == "file1.cs" || resources [1] == "file2.cs", "#F1"); try { compiledAssembly.GetFile("file2.cs"); Assert.Fail("#F2"); } catch (FileNotFoundException) { } try { compiledAssembly.GetManifestResourceStream("file2.cs"); Assert.Fail("#F3"); } catch (FileNotFoundException) { } info = compiledAssembly.GetManifestResourceInfo("file2.cs"); Assert.IsNotNull(info, "#F4"); Assert.IsNotNull(info.FileName, "#F5"); Assert.AreEqual("file2.cs", info.FileName, "#F6"); Assert.IsNull(info.ReferencedAssembly, "#F7"); Assert.AreEqual((ResourceLocation)0, info.ResourceLocation, "#F8"); #endif }
private static Type BuildTypeCodeDom(Type baseInterface, string className, string fieldsPrefix, params Type[] types) { var compileUnit = new CodeCompileUnit(); CodeNamespace globalNamespace = new CodeNamespace(); globalNamespace.Imports.Add(new CodeNamespaceImport("System")); globalNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); globalNamespace.Imports.Add(new CodeNamespaceImport("System.Linq")); globalNamespace.Imports.Add(new CodeNamespaceImport("System.Text")); var classNamespace = new CodeNamespace("STS.General.Data"); var generatedClass = new CodeTypeDeclaration(className); generatedClass.IsClass = true; generatedClass.Attributes = MemberAttributes.Public; for (int i = 0; i < types.Length; i++) { generatedClass.TypeParameters.Add(new CodeTypeParameter("T" + fieldsPrefix + i)); } if (baseInterface != null) { generatedClass.BaseTypes.Add(baseInterface); } var serializableAttribute = new CodeTypeReference(typeof(System.SerializableAttribute)); generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(serializableAttribute)); classNamespace.Types.Add(generatedClass); compileUnit.Namespaces.Add(globalNamespace); compileUnit.Namespaces.Add(classNamespace); CodeMemberField[] fields = new CodeMemberField[types.Length]; for (int i = 0; i < fields.Length; i++) { fields[i] = new CodeMemberField("T" + fieldsPrefix + i, fieldsPrefix + i); fields[i].Attributes = MemberAttributes.Public; generatedClass.Members.Add(fields[i]); } CodeConstructor defaultConstructor = new CodeConstructor(); defaultConstructor.Attributes = MemberAttributes.Public; generatedClass.Members.Add(defaultConstructor); CodeConstructor constructor = new CodeConstructor(); constructor.Attributes = MemberAttributes.Public; for (int i = 0; i < types.Length; i++) { CodeTypeReference type = new CodeTypeReference("T" + fieldsPrefix + i); constructor.Parameters.Add(new CodeParameterDeclarationExpression(type, fieldsPrefix.ToLower() + i)); } for (int i = 0; i < types.Length; i++) { CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldsPrefix + i); constructor.Statements.Add(new CodeAssignStatement(left, new CodeArgumentReferenceExpression(fieldsPrefix.ToLower() + i))); } generatedClass.Members.Add(constructor); string stsdbAssemblyName = Assembly.GetExecutingAssembly().Location; string[] assemblies = { "System.dll", "mscorlib.dll", stsdbAssemblyName }; CompilerParameters parameters = new CompilerParameters(assemblies); CodeDomProvider runTimeProvider = new Microsoft.CSharp.CSharpCodeProvider(); parameters = new CompilerParameters(assemblies); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = true; parameters.CompilerOptions = "/optimize"; CompilerResults compilerResults = runTimeProvider.CompileAssemblyFromDom(parameters, compileUnit); var generatedType = compilerResults.CompiledAssembly.GetTypes()[0]; return(generatedType.MakeGenericType(types)); }
public static bool CompileVBScripts(bool debug, bool cache, out Assembly assembly) { Console.Write("Scripts: Compiling VB.NET scripts..."); string[] files = GetScripts("*.vb"); if (files.Length == 0) { Console.WriteLine("no files found."); assembly = null; return(true); } if (File.Exists("Scripts/Output/Scripts.VB.dll")) { if (cache && File.Exists("Scripts/Output/Scripts.VB.hash")) { byte[] hashCode = GetHashCode("Scripts/Output/Scripts.VB.dll", files, debug); try { using (FileStream fs = new FileStream("Scripts/Output/Scripts.VB.hash", FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader bin = new BinaryReader(fs)) { byte[] bytes = bin.ReadBytes(hashCode.Length); if (bytes.Length == hashCode.Length) { bool valid = true; for (int i = 0; i < bytes.Length; ++i) { if (bytes[i] != hashCode[i]) { valid = false; break; } } if (valid) { assembly = Assembly.LoadFrom("Scripts/Output/Scripts.VB.dll"); if (!m_AdditionalReferences.Contains(assembly.Location)) { m_AdditionalReferences.Add(assembly.Location); } Console.WriteLine("done (cached)"); return(true); } } } } } catch { } } } DeleteFiles("Scripts.VB*.dll"); using (VBCodeProvider provider = new VBCodeProvider()) { string path = GetUnusedPath("Scripts.VB"); CompilerParameters parms = new CompilerParameters(GetReferenceAssemblies(), path, debug); string options = GetCompilerOptions(debug); if (options != null) { parms.CompilerOptions = options; } if (Core.HaltOnWarning) { parms.WarningLevel = 4; } CompilerResults results = provider.CompileAssemblyFromFile(parms, files); m_AdditionalReferences.Add(path); Display(results); if (results.Errors.Count > 0) { assembly = null; return(false); } if (cache && Path.GetFileName(path) == "Scripts.VB.dll") { try { byte[] hashCode = GetHashCode(path, files, debug); using (FileStream fs = new FileStream("Scripts/Output/Scripts.VB.hash", FileMode.Create, FileAccess.Write, FileShare.None)) { using (BinaryWriter bin = new BinaryWriter(fs)) { bin.Write(hashCode, 0, hashCode.Length); } } } catch { } } assembly = results.CompiledAssembly; return(true); } }
public static string GenerateCSharpCode(object o) { Type type = o.GetType(); string className = type.Name; CSharpCodeProvider provider = new CSharpCodeProvider(); // Build the file name. string sourceFileName; if (provider.FileExtension[0] == '.') { sourceFileName = className + provider.FileExtension; } else { sourceFileName = className + "." + provider.FileExtension; } // Build the parameters for source compilation. CompilerParameters cp = new CompilerParameters(); cp.IncludeDebugInformation = true; // Add assembly references. // ugly hard-refs //cp.ReferencedAssemblies.Add("System.dll"); //cp.ReferencedAssemblies.Add("System.Collections.dll"); //cp.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll"); //cp.ReferencedAssemblies.Add("HotLoadingUserData.dll"); cp.ReferencedAssemblies.Add("C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.0/System.dll"); cp.ReferencedAssemblies.Add("C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.0/System.Core.dll"); //cp.ReferencedAssemblies.Add("C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.0/System.Drawing.dll"); //cp.ReferencedAssemblies.Add("C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.0/System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("C:/Program Files (x86)/Rhinoceros 5/System/rhinocommon.dll"); //cp.ReferencedAssemblies.Add("G:/00 CURRENT/Rhino/ArchivableUserData/ArchivableUserData/packages/Newtonsoft.Json.11.0.2/lib/net40/Newtonsoft.Json.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = false; // ugly hard-link FileInfo sourceFilePath = new FileInfo("../" + sourceFileName); CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFilePath.FullName); string encodedAssembly = ""; if (cr.Errors.Count > 0) { // Display compilation errors. RhinoApp.WriteLine("Errors building {0} into {1}", sourceFileName, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { RhinoApp.WriteLine(" {0}", ce.ToString()); RhinoApp.WriteLine(); } } else { encodedAssembly = Convert.ToBase64String(File.ReadAllBytes(cp.OutputAssembly)); } return(encodedAssembly); }
protected override string CmdArgsFromParameters(CompilerParameters options) { return(String.Empty); }
public void generateAndRunVBObjectTests() { int i = 0; DirectoryInfo d = new DirectoryInfo(Directory.GetCurrentDirectory()); while (true) { i++; if (i >= 20) { throw new ApplicationException("could not get a dir with name GeneratorTests"); } d = d.Parent; if (d.Name == "GeneratorTests") { break; } } string path = d.FullName + "\\VbObjectTestsTmp.cs"; if (File.Exists(path)) { File.Delete(path); } File.Copy(d.FullName + "\\CSharpObjectTests.cs", path); string readText = File.ReadAllText(path); readText = readText.Replace("using CsModelObjects;", "using ModelLibVBGenCode.VbBusObjects;"); readText = readText.Replace("using CsModelMappers;", "using ModelLibVBGenCode.VbBusObjects.DBMappers;"); //readText = readText.Replace("DateTime hireDate=new", "dim hireDate as DateTime=new"); readText = readText.Replace("namespace GeneratorTests {", "namespace GeneratorTests.VB {"); readText = readText.Replace("public class CSharpObjectTests {", "public class VBObjectTests {"); readText = readText.Replace("public void createCsRecords()", "public void createVbRecords()"); readText = readText.Replace("[TestClass]", "[NUnit.Framework.TestFixture]"); readText = readText.Replace("[TestMethod]", "[NUnit.Framework.Test]"); readText = readText.Replace("using Microsoft.VisualStudio.TestTools.UnitTesting;", "using NUnit.Framework;"); readText = readText.Replace("Assert.", "NUnit.Framework.Assert."); readText = readText.Replace("public static void MyClassInitialize(TestContext testContext)", "public static void MyClassInitialize()"); readText = readText.Replace("[ClassInitialize()]", "[NUnit.Framework.SetUp]"); readText = readText.Replace("[ClassCleanup()]", "[NUnit.Framework.TearDown]"); readText = readText.Replace("//NUnit.Framework.NUnit.Framework.Assert.IsTrue(false)", "NUnit.Framework.Assert.IsTrue(false);"); readText = readText.Replace("//DBUtils.Current().ConnString=", "org.model.lib.db.DBUtils.Current().ConnString=\"" + DBUtils.Current().ConnString.Replace("\\", "\\\\") + "\";"); readText = readText.Replace("EnumProjectType.EXTERNAL", "ModelLibVBGenCode.EnumProjectType.EXTERNAL"); readText = readText.Replace("void testCSharp", "void testVBNet"); File.WriteAllText(path, readText); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); // this line is here otherwise ModelLibVBGenCode is not returned // in call to this.GetType().Assembly.GetReferencedAssemblies ModelLibVBGenCode.VbBusObjects.Employee e = null; NUnit.Framework.Guard x = null; // note: DO NOT REMOVE! var assemblies = this.GetType().Assembly.GetReferencedAssemblies().ToList(); var assemblyLocations = assemblies.Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Location); var lstAssemblyLocations = assemblyLocations.Where(a => !a.Contains("Microsoft.VisualStudio.QualityTools.UnitTestFramework")).ToList(); //Assembly.ReflectionOnlyLoad("") cp.ReferencedAssemblies.AddRange(lstAssemblyLocations.ToArray()); cp.GenerateInMemory = false; // True - memory generation, false - external file generation cp.GenerateExecutable = false; // True - exe file generation, false - dll file generation CompilerResults results = provider.CompileAssemblyFromSource(cp, readText); Assert.AreEqual(0, results.Errors.Count, "There should be no compilation errors, first error was:" + (results.Errors.Count > 0 ? results.Errors[0].ErrorText : "")); CoreExtensions.Host.InitializeService(); TestPackage package = new TestPackage(results.CompiledAssembly.Location); RemoteTestRunner remoteTestRunner = new RemoteTestRunner(); remoteTestRunner.Load(package); TestResult result = remoteTestRunner.Run(new NullListener(), TestFilter.Empty, false, LoggingThreshold.All); Assert.IsTrue(result.HasResults, " must have test results "); Assert.IsTrue(result.IsSuccess, "dynamic vb tests must return success "); }
public static CompilerResults Build(string path, Project project) { string code = BuildCode(project); WindowMain.Singleton.OverlayTitle = "Compiling '" + Path.GetFileName(path) + "'"; WindowMain.Singleton.OverlayIsIndeterminate = true; string manifestPath = null; try { bool isManifestResource; manifestPath = Path.GetTempFileName(); byte[] manifestFile; switch (project.Manifest) { case BuildManifest.None: manifestFile = Properties.Resources.FileManifestNone; isManifestResource = true; break; case BuildManifest.AsInvoker: manifestFile = Properties.Resources.FileManifestAsInvoker; isManifestResource = false; break; case BuildManifest.RequireAdministrator: manifestFile = Properties.Resources.FileManifestRequireAdministrator; isManifestResource = false; break; default: throw new InvalidOperationException(); } File.WriteAllBytes(manifestPath, manifestFile); using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } })) { string platformName; switch (project.Platform) { case BuildPlatform.Win32: platformName = "x86"; break; case BuildPlatform.Win64: platformName = "x64"; break; case BuildPlatform.AnyCPU: platformName = "anycpu"; break; default: throw new InvalidOperationException(); } CompilerParameters parameters = new CompilerParameters { GenerateExecutable = true, GenerateInMemory = true, OutputAssembly = path, CompilerOptions = "/nostdlib /target:winexe /platform:" + platformName + (isManifestResource ? null : " /win32manifest:" + manifestPath), Win32Resource = isManifestResource ? manifestPath : null }; parameters.ReferencedAssemblies.AddRange(new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Windows.Forms.dll" }); CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count == 0 && project.IconPath != null) { WindowMain.Singleton.OverlayTitle = "Applying icon '" + Path.GetFileName(project.IconPath) + "'"; ResourceFile.ChangeIcon(path, project.IconPath); } return(results); } } finally { if (manifestPath != null) { File.Delete(manifestPath); } } }
public static void CompileAndExecuteFile(string file, string[] args, bool createexe) { //Currently only csharp scripting is supported AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateInMemory = true; compilerparams.GenerateExecutable = true; compilerparams.CompilerOptions = "/unsafe"; if (createexe) { compilerparams.OutputAssembly = file.Substring(0, file.LastIndexOf('.')) + ".exe"; } //Add assembly references from nscript.nrf or <file>.nrf string nrfFile = Path.ChangeExtension(file, "nrf"); Regex regex = new Regex( @"\/\/\s*ref\s*\:\s*(?<refs>.*)", RegexOptions.IgnoreCase); compilerparams.ReferencedAssemblies.Add(typeof(ScriptManager).Assembly.Location); foreach (Match m in regex.Matches(File.ReadAllText(file))) { string str = m.Groups["refs"].Value.Trim(); if (str == "" || str.StartsWith("//")) { continue; } _refs.Add(str); Assembly a = Assembly.LoadFrom(str); if (a != null) { compilerparams.ReferencedAssemblies.Add(a.Location); } } //else { // load SCRIPT refs if (File.Exists(nrfFile)) { AddReferencesFromFile(compilerparams, nrfFile); } // load default nscript.nrf nrfFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "nscript.nrf"); if (File.Exists(nrfFile)) { AddReferencesFromFile(compilerparams, nrfFile); } else { // use embedded file here AddReferencesFromFile(compilerparams, Assembly.GetExecutingAssembly().GetManifestResourceStream("nscript.NScript.nrf")); } } CompilerResults results = compiler.CompileAssemblyFromFile(compilerparams, file); if (results.Errors.HasErrors == true) { StringBuilder sb = new StringBuilder(); foreach (var e in results.Errors) { sb.AppendLine(e.ToString()); } throw new Exception(sb.ToString()); } else if (createexe == false) { results.CompiledAssembly.EntryPoint.Invoke(null, BindingFlags.Static, null, new object[] { args }, null); } }
protected override CompilerResults FromFile(CompilerParameters options, string fileName) { return(FromFileWorker(options, fileName)); }
private static int GenCsMeta(NameValueCollection parameters) { var connectionString = parameters["connection-string"]; var resultAssemblyFullPath = parameters["result-assembly-full-path"]; var namespaceRoot = parameters["namespace-root"]; var scanItems = (parameters["scan-items"] ?? "").Split(','); var sourcePath = parameters["source-path"]; var csprojFilePath = parameters["csproj-file-path"]; var parametersAreValid = !string.IsNullOrEmpty(connectionString) && (!string.IsNullOrEmpty(resultAssemblyFullPath) || !string.IsNullOrEmpty(sourcePath)) && !string.IsNullOrEmpty(namespaceRoot) && scanItems.Length > 0; if (!parametersAreValid) { Console.Out.WriteLine("Invalid arguments"); Console.Out.WriteLine( "Usage: Generator.exe -cmd gen-cs-meta -connection-string <string> [-result-assembly-full-path <path>] -namespace-root <namespace> -scanItems Справочник.Банки,Документ.СписаниеСРасчетногоСчета [-source-path <sourcePath>] [-csproj-file-path]"); return(-1); } object globalContext = null; LogHelpers.LogWithTiming(string.Format("connecting to [{0}]", connectionString), () => globalContext = new GlobalContextFactory().Create(connectionString)); sourcePath = sourcePath ?? GetTemporaryDirectoryFullPath(); if (Directory.Exists(sourcePath)) { Directory.Delete(sourcePath, true); } string[] fileNames = null; LogHelpers.LogWithTiming(string.Format("generating code into [{0}]", sourcePath), () => { var generator = new ObjectModelGenerator(globalContext, scanItems, namespaceRoot, sourcePath); fileNames = generator.Generate().ToArray(); }); if (!string.IsNullOrEmpty(csprojFilePath)) { csprojFilePath = Path.GetFullPath(csprojFilePath); if (!File.Exists(csprojFilePath)) { Console.Out.WriteLine("proj file [{0}] does not exist, create it manually for the first time", csprojFilePath); return(-1); } LogHelpers.LogWithTiming(string.Format("patching proj file [{0}]", csprojFilePath), () => { var updater = new CsProjectFileUpdater(csprojFilePath, sourcePath); updater.Update(); }); } if (!string.IsNullOrEmpty(resultAssemblyFullPath)) { LogHelpers.LogWithTiming(string.Format("compiling [{0}] to assembly [{1}]", sourcePath, resultAssemblyFullPath), () => { var cSharpCodeProvider = new CSharpCodeProvider(); var compilerParameters = new CompilerParameters { OutputAssembly = resultAssemblyFullPath, GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = false }; var linqTo1CFilePath = PathHelpers.AppendBasePath("Simple1C.dll"); compilerParameters.ReferencedAssemblies.Add(linqTo1CFilePath); var compilerResult = cSharpCodeProvider.CompileAssemblyFromFile(compilerParameters, fileNames); if (compilerResult.Errors.Count > 0) { Console.Out.WriteLine("compile errors"); foreach (CompilerError error in compilerResult.Errors) { Console.Out.WriteLine(error); Console.Out.WriteLine("==================="); } } }); } return(0); }
protected override string CmdArgsFromParameters(CompilerParameters options) { // gets called from base classes FromFileBatch - which is never invoked because we override it throw new Exception("The method or operation is not implemented."); }
public Dictionary <MapKey, IMap> Compile(List <IMappingConfiguration> configurationList) { List <string> referenceList = new List <string>(); Dictionary <MapKey, string> classMap = new Dictionary <MapKey, string>(); string code = @" using System; using System.Linq; using NextMap; "; foreach (IMappingConfiguration configuration in configurationList) { List <string> outputReferenceList; string className; code += GenerateMapClassCode(configuration, out outputReferenceList, out className) + "\r\n\r\n"; classMap[new MapKey(configuration.SourceType, configuration.DestinationType)] = className; //merge the assemblies in the general list foreach (string assemblyFile in outputReferenceList) { if (!referenceList.Contains(assemblyFile)) { referenceList.Add(assemblyFile); } } } CodeDomProvider loCompiler = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters loParameters = new CompilerParameters(); loParameters.ReferencedAssemblies.Add("System.dll"); loParameters.ReferencedAssemblies.Add("System.Core.dll"); loParameters.ReferencedAssemblies.Add(typeof(Mapper).Assembly.Location); //"NextMap.dll"); //add the rest of the referenced assemblies referenceList.ForEach(x => loParameters.ReferencedAssemblies.Add(x)); loParameters.GenerateInMemory = true; // *** Now compile the whole thing CompilerResults loCompiled = loCompiler.CompileAssemblyFromSource(loParameters, code); foreach (CompilerError compilerError in loCompiled.Errors) { string a = compilerError.ErrorText; } Assembly loAssembly = loCompiled.CompiledAssembly; Dictionary <MapKey, IMap> resultDict = new Dictionary <MapKey, IMap>(); foreach (KeyValuePair <MapKey, string> pair in classMap) { IMap loObject = (IMap)loAssembly.CreateInstance(pair.Value); resultDict.Add(pair.Key, loObject); } return(resultDict); }