private void CheckExample_Click(object sender, RoutedEventArgs e) { Analizor_LL_1_.CodeGenerator codeGenerator = new Analizor_LL_1_.CodeGenerator(); codeGenerator.AddEntryPoint(_gramatica); codeGenerator.AddFields(); codeGenerator.AddMethods(_gramatica); codeGenerator.GenerateCSharpCode("output.cs"); CompilerParameters cp = new CompilerParameters { GenerateExecutable = true, IncludeDebugInformation = true, GenerateInMemory = false, WarningLevel = 4, TreatWarningsAsErrors = false, CompilerOptions = "/optimize", OutputAssembly = "output.exe", }; cp.ReferencedAssemblies.Add("System.dll"); CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerResults cr = provider.CompileAssemblyFromFile(cp, "output.cs"); Process.Start("output.exe"); }
public static CompilerResults Compile(Dictionary <string, CodeFile> codeFiles, bool inMemory) { using (HeavyProfiler.Log("COMPILE")) { CodeDomProvider supplier = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); foreach (var ass in DynamicCode.Assemblies) { parameters.ReferencedAssemblies.Add(Path.Combine(DynamicCode.AssemblyDirectory, ass)); } if (inMemory) { parameters.GenerateInMemory = true; } else { parameters.OutputAssembly = Path.Combine(DynamicCode.CodeGenDirectory, DynamicCode.CodeGenAssembly); } Directory.CreateDirectory(DynamicCode.CodeGenDirectory); Directory.EnumerateFiles(DynamicCode.CodeGenDirectory).Where(a => !inMemory || a != DynamicCode.CodeGenAssemblyPath).ToList().ForEach(a => File.Delete(a)); codeFiles.Values.ToList().ForEach(a => File.WriteAllText(Path.Combine(DynamicCode.CodeGenDirectory, a.FileName), a.FileContent)); CompilerResults compiled = supplier.CompileAssemblyFromFile(parameters, codeFiles.Values.Select(a => Path.Combine(DynamicCode.CodeGenDirectory, a.FileName)).ToArray()); return(compiled); } }
private static void LoadSingleMod(string ModFolderPath) { string path1 = Path.Combine(ModFolderPath, "Modinfo.dat"); string str = ""; if (File.Exists(path1)) { str = File.ReadAllText(path1); } else { //Debug.Log(@"(DataLoader.LoadSingleMod)오류/" + path1 + " 모드인포 파일을 찾을수 없습니다."); return; } object obj2 = ObjectSaver.ObjectSaver.Load(path1); ModInfo info = ObjectSaver.ObjectSaver.Load(path1) as ModInfo; string scriptpath = Path.Combine(ModFolderPath, info.ScriptPath); //CSharpCodeProvider provider = new CSharpCodeProvider(); CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.GenerateExecutable = false; //parameters.CoreAssemblyFileName = "CataclysmRemasterd"; parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); //parameters.ReferencedAssemblies.Add("System.dll"); CompilerResults results = provider.CompileAssemblyFromFile(parameters, scriptpath); if (results.Errors.HasErrors) { StringBuilder 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()); } Assembly assembly = results.CompiledAssembly; Type[] ts = assembly.GetTypes(); Type program = assembly.GetType(info.FullName); object obj = assembly.CreateInstance(info.FullName); program.GetField("data").SetValue(obj, StaticUse.mainstorage); program.GetMethod("Initialize").Invoke(obj, null); DataLoadScript loader = program.GetField("load").GetValue(obj) as DataLoadScript; StaticUse.mainstorage.LoadedModAssembly.Add(assembly); StaticUse.mainstorage.LoadedModObject.Add(obj); DataLoadScriptLoader.Load(loader, info); }
static void CompileCodeOnTheFly(string[] args) { // The built-in CSharpCodeProvider cannot resolve features from C# 6.0 onward // Therefore we use roslyn package instead. CodeDomProvider codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Linq.dll"); parameters.GenerateInMemory = true; parameters.GenerateExecutable = true; parameters.IncludeDebugInformation = true; CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, GetSourceFilePathToCompile()); if (results.Errors.HasErrors) { StringBuilder 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()); } Assembly assembly = results.CompiledAssembly; var type = assembly.GetTypes()[0]; MethodInfo mainMethod = null; foreach (var t in assembly.GetTypes()) { var method = t.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); if (method != null) { mainMethod = method; break; } } var methodParameters = mainMethod.GetParameters(); mainMethod.Invoke(null, methodParameters.Length > 0 ? new object[] { args } : null); }
/// <summary> /// Metoda folosita pentru a compila codul sursa dintr-un anumit fisier. /// </summary> /// <param name="sourceFile">Fisierul care contine codul sursa.</param> /// <returns>Erorile ce pot aparea pe parcursul procesului de compilare sau string.Empty daca totul functioneaza corect.</returns> public string CompileazaCodSursa(string sourceFile) { CompilerParameters cp = new CompilerParameters { // Generate an executable instead of // a class library. GenerateExecutable = true, // Generate debug information. IncludeDebugInformation = true, // Save the assembly as a physical file. GenerateInMemory = false, // Set the level at which the compiler // should start displaying warnings. WarningLevel = 4, // Set whether to treat all warnings as errors. TreatWarningsAsErrors = false, // Set compiler argument to optimize output. CompilerOptions = "/optimize", // Specify the assembly file name to generate. OutputAssembly = Path.GetFileNameWithoutExtension(sourceFile) + ".exe" }; // Add an assembly reference. cp.ReferencedAssemblies.Add("System.dll"); // Invoke compilation. CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); if (cr.Errors.Count > 0) { string errors = string.Format("Errors building {0} into {1}: \n", sourceFile, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { errors += string.Format(" {0}\n", ce.ToString()); } return(errors); } return(string.Empty); }
internal static CompilerResults Compile() { bool optimize = false; // there are builtin CodeDomProvider.CreateProvider("CSharp") or the Nuget one // we use the latter since it suppports newer C# features (but it is way slower) // you may encounter IO path issues like: Could not find a part of the path … bin\roslyn\csc.exe // solution is to run Nuget console: // Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r // string source = "gen.cs"; FromatFile(source); // use a provider recognize newer C# features var provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); // compile it string[] references = { "qpmodel.exe", "System.dll", "Microsoft.CSharp.dll", "System.Core.dll" }; CompilerParameters cp = new CompilerParameters(references); cp.GenerateInMemory = true; cp.GenerateExecutable = false; cp.IncludeDebugInformation = !optimize; if (optimize) { cp.CompilerOptions = "/optimize"; } CompilerResults cr = provider.CompileAssemblyFromFile(cp, source); // detect any errors if (cr.Errors.Count > 0) { Console.WriteLine("Errors building {0} into {1}", source, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}: {1}", ce.ErrorNumber, ce.ErrorText); } throw new SemanticExecutionException("codegen failed"); } // now we can execute it Console.WriteLine("compiled OK"); return(cr); }
public CompilerResults Compile() { AddCS(); ParseFilesForCompilerOptions(); if (SourceFilePaths.Count == 0) { return(null); } using (Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider()) { provider.Supports(GeneratorSupport.Resources); CompilerResults results = provider.CompileAssemblyFromFile(Options, SourceFilePaths.ToArray()); if (!results.Errors.HasErrors) { CompiledAssembly = results.CompiledAssembly; } results.TempFiles.Delete(); return(results); } }
private List <Assembly> CompilePluginsFromSource(DirectoryInfo[] sourcePlugins) { using (CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider()) using (new PerformanceTimer("Compile and load source plugins")) { var _compilerSettings = provider.GetType().GetField("_compilerSettings", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(provider); var _compilerFullPath = _compilerSettings .GetType().GetField("_compilerFullPath", BindingFlags.Instance | BindingFlags.NonPublic); _compilerFullPath.SetValue(_compilerSettings, ((string)_compilerFullPath.GetValue(_compilerSettings)).Replace(@"bin\roslyn\", @"roslyn\")); var rootDirInfo = new DirectoryInfo(RootDirectory); var dllFiles = rootDirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly).WhereF(x => !x.Name.Equals("cimgui.dll")) .SelectF(x => x.FullName).ToArray(); var results = new List <Assembly>(sourcePlugins.Length); foreach (var info in sourcePlugins) { using (new PerformanceTimer($"Compile and load source plugin: {info.Name}")) { var csFiles = info.GetFiles("*.cs", SearchOption.AllDirectories).Select(x => x.FullName).ToArray(); var parameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true, CompilerOptions = "/optimize /unsafe" }; parameters.ReferencedAssemblies.AddRange(dllFiles); var csprojPath = Path.Combine(info.FullName, $"{info.Name}.csproj"); if (File.Exists(csprojPath)) { var refer = File.ReadAllLines(csprojPath) .WhereF(x => x.TrimStart().StartsWith("<Reference Include=") && x.TrimEnd().EndsWith("/>")); foreach (var r in refer) { var arr = new int[2] { 0, 0 }; var j = 0; for (var i = 0; i < r.Length; i++) { if (r[i] == '"') { arr[j] = i; j++; } } if (arr[1] != 0) { var dll = $"{r.Substring(arr[0] + 1, arr[1] - arr[0] - 1)}.dll"; parameters.ReferencedAssemblies.Add(dll); } } } var libsFolder = Path.Combine(info.FullName, "libs"); if (Directory.Exists(libsFolder)) { var libsDll = Directory.GetFiles(libsFolder, "*.dll"); parameters.ReferencedAssemblies.AddRange(libsDll); } // parameters.TempFiles = new TempFileCollection($"{MainDir}\\{PluginsDirectory}\\Temp"); // parameters.CoreAssemblyFileName = info.Name; var result = provider.CompileAssemblyFromFile(parameters, csFiles); if (result.Errors.HasErrors) { var AllErrors = ""; foreach (CompilerError compilerError in result.Errors) { AllErrors += compilerError + Environment.NewLine; Logger.Log.Error($"{info.Name} -> {compilerError.ToString()}"); } File.WriteAllText(Path.Combine(info.FullName, "Errors.txt"), AllErrors); // throw new Exception("Offsets file corrupted"); } else { results.Add(result.CompiledAssembly); } } } return(results); } }
/// <summary> /// 从 源代码 中获取表信息 /// </summary> /// <param name="sourceFilePaths">sourceCodeFiles</param> /// <returns></returns> public static List <TableEntity> GeTableEntityFromSourceCode(params string[] sourceFilePaths) { if (sourceFilePaths == null || sourceFilePaths.Length <= 0) { return(null); } // //Set hardcoded environment variable to set the path to the library Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", System.IO.Directory.GetCurrentDirectory() + "\\roslyn", EnvironmentVariableTarget.Process); var provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); //Clean up Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", null, EnvironmentVariableTarget.Process); var result = provider.CompileAssemblyFromFile(new CompilerParameters(new[] { "System.dll" }), sourceFilePaths); if (result.Errors.HasErrors) { var error = new StringBuilder(result.Errors.Count * 1024); for (var i = 0; i < result.Errors.Count; i++) { error.AppendLine($"{result.Errors[i].FileName}({result.Errors[i].Line},{result.Errors[i].Column}):{result.Errors[i].ErrorText}"); } throw new ArgumentException($"所选文件编译有错误{Environment.NewLine}{error}"); } var tables = new List <TableEntity>(2); foreach (var type in result.CompiledAssembly.GetTypes()) { if (type.IsClass && type.IsPublic && !type.IsAbstract) { var table = new TableEntity { TableName = type.Name.TrimModelName(), TableDescription = type.GetCustomAttribute <DescriptionAttribute>()?.Description }; var defaultVal = Activator.CreateInstance(type); foreach (var property in type.GetProperties(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance)) { var columnInfo = new ColumnEntity { ColumnName = property.Name, ColumnDescription = property.GetCustomAttribute <DescriptionAttribute>()?.Description, IsNullable = property.PropertyType.Unwrap() != property.PropertyType }; var val = property.GetValue(defaultVal); columnInfo.DefaultValue = null == val || property.PropertyType.GetDefaultValue().Equals(val) || columnInfo.IsNullable ? null : val; columnInfo.IsPrimaryKey = columnInfo.ColumnDescription?.Contains("主键") ?? false; columnInfo.DataType = FclType2DbType(property.PropertyType).ToString(); if (!ConfigurationHelper.AppSetting(ConfigurationConstants.DbType).EqualsIgnoreCase("SqlServer") && columnInfo.DataType.Equals("NVARCHAR")) { columnInfo.DataType = "VARCHAR"; } columnInfo.Size = GetDefaultSizeForDbType(columnInfo.DataType); table.Columns.Add(columnInfo); } tables.Add(table); } } return(tables); }
public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly) { Utility.PushColor(ConsoleColor.Green); Console.Write("Scripts: Compiling C# scripts..."); Utility.PopColor(); var files = GetScripts("*.cs"); if (files.Length == 0) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("no files found."); Utility.PopColor(); assembly = null; return(true); } if (File.Exists("Scripts/Output/Scripts.CS.dll")) { if (cache && File.Exists("Scripts/Output/Scripts.CS.hash")) { try { var hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug); using ( FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BinaryReader bin = new BinaryReader(fs)) { var 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.CS.dll"); if (!m_AdditionalReferences.Contains(assembly.Location)) { m_AdditionalReferences.Add(assembly.Location); } Utility.PushColor(ConsoleColor.Green); Console.WriteLine("done (cached)"); Utility.PopColor(); return(true); } } } } } catch { } } } DeleteFiles("Scripts.CS*.dll"); using (CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider()) { string path = GetUnusedPath("Scripts.CS"); CompilerParameters parms = new CompilerParameters(GetReferenceAssemblies(), path, debug); string options = GetCompilerOptions(debug); if (options != null) { parms.CompilerOptions = options; } if (Core.HaltOnWarning) { parms.WarningLevel = 4; } #if !MONO CompilerResults results = provider.CompileAssemblyFromFile(parms, files); #else parms.CompilerOptions = String.Format("{0} /nowarn:169,219,414 /recurse:Scripts/*.cs", parms.CompilerOptions); CompilerResults results = provider.CompileAssemblyFromFile(parms, ""); #endif m_AdditionalReferences.Add(path); Display(results); #if !MONO if (results.Errors.Count > 0) { assembly = null; return(false); } #else if (results.Errors.Count > 0) { foreach (CompilerError err in results.Errors) { if (!err.IsWarning) { assembly = null; return(false); } } } #endif if (cache && Path.GetFileName(path) == "Scripts.CS.dll") { try { var hashCode = GetHashCode(path, files, debug); using ( FileStream fs = new FileStream( "Scripts/Output/Scripts.CS.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 bool CompilerProject(string srcPath, string projectFilePath, string targetPath, TextWriter wStream, out string dllFileNameWithFullPath) { dllFileNameWithFullPath = string.Empty; bool hasError = false; try { if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } //src : http://ww0ww.blogspot.in/2014/07/automated-build-csharp-code-using.html //https://stackoverflow.com/questions/42260915/codedomprovider-compileassemblyfromsource-cant-find-roslyn-csc-exe System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters(); string _projectName = Path.GetFileNameWithoutExtension(projectFilePath); XmlDocument _project = new XmlDocument(); _project.Load(projectFilePath); XmlNamespaceManager ns = new XmlNamespaceManager(_project.NameTable); ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode _settings = _project.SelectSingleNode("//msbld:Project/msbld:PropertyGroup/msbld:AssemblyName", ns); string _asmName = _settings.InnerText; XmlNodeList _files = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Compile", ns); ArrayList _sourceNames = new ArrayList(); // Add compilable files foreach (XmlNode _file in _files) { string _codeFilename = _file.Attributes["Include"].Value.ToLower(); if (_codeFilename != "assemblyinfo.cs" && !_codeFilename.EndsWith("vsa.cs")) { // Read the source code int _idx = _sourceNames.Add(_file.Attributes["Include"].Value); } } XmlNodeList _reference = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Reference", ns); foreach (XmlNode _asmRef in _reference) { // Try to use the AssemblyName attribute if it exists string _refAsmName; if (_asmRef.Attributes["AssemblyName"] != null) { _refAsmName = _asmRef.Attributes["AssemblyName"].Value + ".dll"; } else if (_asmRef.Attributes["Name"] != null) { _refAsmName = _asmRef.Attributes["Name"].Value + ".dll"; } else { if (_asmRef.HasChildNodes && _asmRef["HintPath"] != null) { _refAsmName = Path.Combine(srcPath, _asmRef["HintPath"].InnerText); } else { _refAsmName = _asmRef.Attributes["Include"].Value + ".dll"; if (_refAsmName.IndexOf(",") > 0) { _refAsmName = _refAsmName.Substring(0, _refAsmName.IndexOf(",")) + ".dll"; } } } cp.ReferencedAssemblies.Add(_refAsmName); } cp.GenerateExecutable = false; // result is a .DLL cp.IncludeDebugInformation = true; String[] _sourcefiles = (String[])_sourceNames.ToArray(typeof(string)); string[] fullPath_sourcefiles = _sourcefiles.Select(t => Path.Combine(srcPath, t)).ToArray(); //------------------------------------------------------------- CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); //CodeDomProvider.CreateProvider("CSharp", options); dllFileNameWithFullPath = Path.Combine(targetPath, _asmName + ".dll"); cp.CompilerOptions = " /out:" + dllFileNameWithFullPath; CompilerResults cr = provider.CompileAssemblyFromFile(cp, fullPath_sourcefiles); if (cr.Errors.Count > 0) //if (_compErrs.Length > 0) { hasError = true; bool _error = false; foreach (CompilerError _err in cr.Errors) { // Error or warning? if (!_err.IsWarning)//( _err.ErrorLevel != Microsoft.CSharp.ErrorLevel.Warning ) { _error = true; } if (_error) { string errorMsg = "CompileAndDeploy:CompileComponentAssemblies: Error compiling " + _projectName + ".\nPlease rectify then redeloy."; wStream.WriteLine(errorMsg); Console.WriteLine(errorMsg); } else { string errorMsg = "CompileAndDeploy:CompileComponentAssemblies: Warning compiling " + _projectName + ".\nPlease rectify then redeloy."; wStream.WriteLine(errorMsg); Console.WriteLine(errorMsg); } wStream.WriteLine(_err.ErrorText); Console.WriteLine(_err.ErrorText); } if (_error) { wStream.WriteLine("Compile errors occurred. Rectify first."); Console.WriteLine("Compile errors occurred. Rectify first."); //throw new Exception("Compile errors occurred. Rectify first."); } } var v = cr.Output; foreach (var line in cr.Output) { wStream.WriteLine(line); } } catch (Exception e) { hasError = true; wStream.WriteLine(e.Message); Console.WriteLine(e.Message); } wStream.Flush(); return(hasError); }