internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail) { CompilerType compilerTypeInternal; this.EnsureCompilerCacheInit(); object obj2 = this._compilerExtensions[extension]; Compiler compiler = obj2 as Compiler; if (compiler != null) { compilerTypeInternal = compiler.CompilerTypeInternal; this._compilerExtensions[extension] = compilerTypeInternal; } else { compilerTypeInternal = obj2 as CompilerType; } if ((compilerTypeInternal == null) && CodeDomProvider.IsDefinedExtension(extension)) { CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension)); compilerTypeInternal = new CompilerType(compilerInfo.CodeDomProviderType, compilerInfo.CreateDefaultCompilerParameters()); this._compilerExtensions[extension] = compilerTypeInternal; } if (compilerTypeInternal == null) { if (throwOnFail) { throw new HttpException(System.Web.SR.GetString("Invalid_lang_extension", new object[] { extension })); } return(null); } compilerTypeInternal = compilerTypeInternal.Clone(); compilerTypeInternal.CompilerParameters.IncludeDebugInformation = this.Debug; return(compilerTypeInternal); }
internal static IDictionary <string, string> GetProviderOptionsCollection(string fileExt) { Dictionary <string, string> opts = new Dictionary <string, string>(); if (!CodeDomProvider.IsDefinedExtension(fileExt)) { return(new ReadOnlyDictionary <string, string>(opts)); } CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExt)); if (ci == null) { return(new ReadOnlyDictionary <string, string>(opts)); } // There is a fun little comment about this property in the framework code about making it // public after 3.5. Guess that didn't happen. Oh well. :) PropertyInfo pi = ci.GetType().GetProperty("ProviderOptions", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); if (pi == null) { return(new ReadOnlyDictionary <string, string>(opts)); } return(new ReadOnlyDictionary <string, string>((IDictionary <string, string>)pi.GetValue(ci, null))); }
private void SupportedLanguages() { CompilerInfo[] aCompilerInfo = CodeDomProvider.GetAllCompilerInfo(); foreach (CompilerInfo oCompilerInfo in aCompilerInfo) { foreach (string szLanguage in oCompilerInfo.GetLanguages()) { MessageBox.Show(szLanguage); } } if (!CodeDomProvider.IsDefinedLanguage("GW-BASIC")) { MessageBox.Show("GW-BASIC Not supported"); } if (!CodeDomProvider.IsDefinedLanguage("CSharp")) { MessageBox.Show("CSharp Not supported"); } if (!CodeDomProvider.IsDefinedExtension(".BAS")) { MessageBox.Show(".BAS Not supported"); } if (!CodeDomProvider.IsDefinedExtension(".cs")) { MessageBox.Show(".cs Not supported"); } }
/* * Return a CompilerType that a extension maps to. */ internal CompilerType GetCompilerInfoFromExtension(string extension, bool throwOnFail) { EnsureCompilerCacheInit(); // First, try the cache (i.e. old <compilers> section) CompilerType compilerType; object obj = _compilerExtensions[extension]; Compiler compiler = obj as Compiler; if (compiler != null) { compilerType = compiler.CompilerTypeInternal; _compilerExtensions[extension] = compilerType; } else { compilerType = obj as CompilerType; } if (compilerType == null) { // If not, try the <codedom> section if (CodeDomProvider.IsDefinedExtension(extension)) { string language = CodeDomProvider.GetLanguageFromExtension(extension); CompilerInfo ci = CodeDomProvider.GetCompilerInfo(language); compilerType = new CompilerType( ci.CodeDomProviderType, ci.CreateDefaultCompilerParameters()); // Cache it _compilerExtensions[extension] = compilerType; } } if (compilerType == null) { if (!throwOnFail) { return(null); } // Unsupported extension: throw an exception throw new HttpException(SR.GetString(SR.Invalid_lang_extension, extension)); } // Clone it so the original is not modified compilerType = compilerType.Clone(); // Set the value of the debug flag in the copy compilerType.CompilerParameters.IncludeDebugInformation = Debug; return(compilerType); }
internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType) { CodeDomProvider provider = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType); string fileExtension = provider.FileExtension; if (CodeDomProvider.IsDefinedExtension(fileExtension)) { return(GetProviderOptions(CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(fileExtension)))); } return(null); }
internal static IDictionary <string, string> GetProviderOptions(Type codeDomProviderType) { // Using reflection to get the property for the time being. // This could simply return CompilerInfo.PropertyOptions if it goes public in future. CodeDomProvider provider = (CodeDomProvider)Activator.CreateInstance(codeDomProviderType); string extension = provider.FileExtension; if (CodeDomProvider.IsDefinedExtension(extension)) { CompilerInfo ci = CodeDomProvider.GetCompilerInfo(CodeDomProvider.GetLanguageFromExtension(extension)); return(GetProviderOptions(ci)); } return(null); }
static void DisplayCompilerInfoUsingExtension(string fileExtension) { // <Snippet5> if (fileExtension[0] != '.') { fileExtension = "." + fileExtension; } // Get the language associated with the file extension. if (CodeDomProvider.IsDefinedExtension(fileExtension)) { CodeDomProvider provider; String language = CodeDomProvider.GetLanguageFromExtension(fileExtension); Console.WriteLine("The language \"{0}\" is associated with file extension \"{1}\"", language, fileExtension); Console.WriteLine(); // Next, check for a corresponding language provider. if (CodeDomProvider.IsDefinedLanguage(language)) { provider = CodeDomProvider.CreateProvider(language); // Display information about this language provider. Console.WriteLine("Language provider: {0}", provider.ToString()); Console.WriteLine(); // Get the compiler settings for this language. CompilerInfo langCompilerInfo = CodeDomProvider.GetCompilerInfo(language); CompilerParameters langCompilerConfig = langCompilerInfo.CreateDefaultCompilerParameters(); Console.WriteLine(" Compiler options: {0}", langCompilerConfig.CompilerOptions); Console.WriteLine(" Compiler warning level: {0}", langCompilerConfig.WarningLevel); } } else { // Tell the user that the language provider was not found. Console.WriteLine("There is no language provider associated with input file extension \"{0}\".", fileExtension); } // </Snippet5> }
public void Defaults() { cdp = new CodeDomProviderTest(); // execute ctor not a full trust Assert.AreEqual(String.Empty, cdp.FileExtension, "FileExtension"); Assert.AreEqual(LanguageOptions.None, cdp.LanguageOptions, "LanguageOptions"); Assert.IsNull(cdp.CreateCompiler(), "CreateCompiler"); Assert.IsNull(cdp.CreateGenerator(), "CreateGenerator"); Assert.IsNull(cdp.CreateGenerator(String.Empty), "CreateGenerator(string)"); Assert.IsNull(cdp.CreateGenerator(writer), "CreateGenerator(TextWriter)"); Assert.IsNull(cdp.CreateParser(), "CreateParser()"); Assert.IsNotNull(cdp.GetConverter(typeof(string)), "GetConverter"); Assert.IsNotNull(CodeDomProvider.GetAllCompilerInfo(), "GetAllCompilerInfo"); // mono returns null (missing config?) CodeDomProvider.GetCompilerInfo("cs"); CodeDomProvider.GetLanguageFromExtension("cs"); Assert.IsFalse(CodeDomProvider.IsDefinedExtension(String.Empty), "String.Empty"); Assert.IsFalse(CodeDomProvider.IsDefinedLanguage(String.Empty), "String.Empty"); }
public Assembly Compile(bool debug, string languageOrExtension, params string[] sourceCode) { CodeDomProvider provider; CompilerParameters parameters; CompilerResults results; string language = languageOrExtension; if (!CodeDomProvider.IsDefinedLanguage(languageOrExtension) && CodeDomProvider.IsDefinedExtension(languageOrExtension)) { language = CodeDomProvider.GetLanguageFromExtension(languageOrExtension); } if (ConfigurationManager.GetSection("system.codedom") != null) { CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo(language); provider = compilerInfo.CreateProvider(); parameters = compilerInfo.CreateDefaultCompilerParameters(); } else { if ((!language.Equals("c#", StringComparison.OrdinalIgnoreCase) && !language.Equals("cs", StringComparison.OrdinalIgnoreCase)) && !language.Equals("csharp", StringComparison.OrdinalIgnoreCase)) { throw new CompilerException(string.Format("When running the {0} in an AppDomain without a system.codedom config section only the csharp language is supported. This happens if you are precompiling your views.", typeof(BatchCompiler).FullName)); } string compilerVersion = GetCompilerVersion(); Dictionary <string, string> dictionary2 = new Dictionary <string, string>(); dictionary2.Add("CompilerVersion", compilerVersion); Dictionary <string, string> providerOptions = dictionary2; provider = new CSharpCodeProvider(providerOptions); parameters = new CompilerParameters(); } parameters.TreatWarningsAsErrors = false; string fileExtension = provider.FileExtension; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (!assembly.IsDynamic()) { parameters.ReferencedAssemblies.Add(assembly.Location); } } string tempDir = AppDomain.CurrentDomain.SetupInformation.DynamicBase ?? Path.GetTempPath(); parameters.TempFiles = new TempFileCollection(tempDir); if (debug) { parameters.IncludeDebugInformation = true; string str5 = Path.Combine(tempDir, Guid.NewGuid().ToString("n")); List <string> list = new List <string>(); int num = 0; foreach (string str6 in sourceCode) { num++; string path = string.Concat(new object[] { str5, "-", num, ".", fileExtension }); using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(str6); } } list.Add(path); } if (!string.IsNullOrEmpty(this.OutputAssembly)) { parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly); } else { parameters.OutputAssembly = str5 + ".dll"; } results = provider.CompileAssemblyFromFile(parameters, list.ToArray()); } else { if (!string.IsNullOrEmpty(this.OutputAssembly)) { parameters.OutputAssembly = Path.Combine(tempDir, this.OutputAssembly); } else { parameters.GenerateInMemory = true; } results = provider.CompileAssemblyFromSource(parameters, sourceCode); } if (!results.Errors.HasErrors) { return(results.CompiledAssembly); } StringBuilder builder = new StringBuilder(); builder.AppendLine("Dynamic view compilation failed."); foreach (CompilerError error in results.Errors) { builder.AppendFormat("{4}({0},{1}): {2} {3}: ", new object[] { error.Line, error.Column, error.IsWarning ? "warning" : "error", error.ErrorNumber, error.FileName }); builder.AppendLine(error.ErrorText); } builder.AppendLine(); foreach (string str8 in sourceCode) { using (StringReader reader = new StringReader(str8)) { int num2 = 1; while (true) { string str9 = reader.ReadLine(); if (str9 != null) { builder.Append(num2).Append(' ').AppendLine(str9); num2++; } } } } throw new BatchCompilerException(builder.ToString(), results); }
// Build and add the assembly to the BuildManager's // CodeAssemblies collection public void Build(string[] binAssemblies) { Type compilerProvider = null; CompilerInfo compilerInfo = null, cit; string extension, language, cpfile = null; List <string> knownfiles = new List <string>(); List <string> unknownfiles = new List <string>(); // First make sure all the files are in the same // language bool known = false; foreach (string f in files) { known = true; language = null; extension = Path.GetExtension(f); if (String.IsNullOrEmpty(extension) || !CodeDomProvider.IsDefinedExtension(extension)) { known = false; } if (known) { language = CodeDomProvider.GetLanguageFromExtension(extension); if (!CodeDomProvider.IsDefinedLanguage(language)) { known = false; } } if (!known || language == null) { unknownfiles.Add(f); continue; } cit = CodeDomProvider.GetCompilerInfo(language); if (cit == null || !cit.IsCodeDomProviderTypeValid) { continue; } if (compilerProvider == null) { cpfile = f; compilerProvider = cit.CodeDomProviderType; compilerInfo = cit; } else if (compilerProvider != cit.CodeDomProviderType) { throw new HttpException( String.Format( "Files {0} and {1} are in different languages - they cannot be compiled into the same assembly", Path.GetFileName(cpfile), Path.GetFileName(f))); } knownfiles.Add(f); } CodeDomProvider provider = null; CompilationSection compilationSection = WebConfigurationManager.GetWebApplicationSection("system.web/compilation") as CompilationSection; if (compilerInfo == null) { if (!CodeDomProvider.IsDefinedLanguage(compilationSection.DefaultLanguage)) { throw new HttpException("Failed to retrieve default source language"); } compilerInfo = CodeDomProvider.GetCompilerInfo(compilationSection.DefaultLanguage); if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid) { throw new HttpException("Internal error while initializing application"); } } provider = compilerInfo.CreateProvider(); if (provider == null) { throw new HttpException("A code provider error occurred while initializing application."); } AssemblyBuilder abuilder = new AssemblyBuilder(provider); foreach (string file in knownfiles) { abuilder.AddCodeFile(file); } foreach (CodeCompileUnit unit in units) { abuilder.AddCodeCompileUnit(unit); } BuildProvider bprovider; CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters(); parameters.IncludeDebugInformation = compilationSection.Debug; if (binAssemblies != null && binAssemblies.Length > 0) { StringCollection parmRefAsm = parameters.ReferencedAssemblies; foreach (string binAsm in binAssemblies) { if (parmRefAsm.Contains(binAsm)) { continue; } parmRefAsm.Add(binAsm); } } if (compilationSection != null) { foreach (AssemblyInfo ai in compilationSection.Assemblies) { if (ai.Assembly != "*") { try { parameters.ReferencedAssemblies.Add( AssemblyPathResolver.GetAssemblyPath(ai.Assembly)); } catch (Exception ex) { throw new HttpException( String.Format("Could not find assembly {0}.", ai.Assembly), ex); } } } BuildProviderCollection buildProviders = compilationSection.BuildProviders; foreach (string file in unknownfiles) { bprovider = GetBuildProviderFor(file, buildProviders); if (bprovider == null) { continue; } bprovider.GenerateCode(abuilder); } } if (knownfiles.Count == 0 && unknownfiles.Count == 0 && units.Count == 0) { return; } outputAssemblyName = (string)FileUtils.CreateTemporaryFile( AppDomain.CurrentDomain.SetupInformation.DynamicBase, name, "dll", OnCreateTemporaryAssemblyFile); parameters.OutputAssembly = outputAssemblyName; foreach (Assembly a in BuildManager.TopLevelAssemblies) { parameters.ReferencedAssemblies.Add(a.Location); } CompilerResults results = abuilder.BuildAssembly(parameters); if (results == null) { return; } if (results.NativeCompilerReturnValue == 0) { BuildManager.CodeAssemblies.Add(results.CompiledAssembly); BuildManager.TopLevelAssemblies.Add(results.CompiledAssembly); HttpRuntime.WritePreservationFile(results.CompiledAssembly, name); } else { if (HttpContext.Current.IsCustomErrorEnabled) { throw new HttpException("An error occurred while initializing application."); } throw new CompilationException(null, results.Errors, null); } }
public void IsDefinedExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws <ArgumentNullException>("extension", () => CodeDomProvider.IsDefinedExtension(null)); }
public void IsDefinedExtension_ReturnsExpected(string extension, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedExtension(extension)); }
public Assembly Compile(bool debug, string languageOrExtension, params string[] sourceCode) { var language = languageOrExtension; if (CodeDomProvider.IsDefinedLanguage(languageOrExtension) == false && CodeDomProvider.IsDefinedExtension(languageOrExtension)) { language = CodeDomProvider.GetLanguageFromExtension(languageOrExtension); } CodeDomProvider codeProvider; CompilerParameters compilerParameters; if (ConfigurationManager.GetSection("system.codedom") != null) { var compilerInfo = CodeDomProvider.GetCompilerInfo(language); codeProvider = compilerInfo.CreateProvider(); compilerParameters = compilerInfo.CreateDefaultCompilerParameters(); } else { if (!language.Equals("c#", StringComparison.OrdinalIgnoreCase) && !language.Equals("cs", StringComparison.OrdinalIgnoreCase) && !language.Equals("csharp", StringComparison.OrdinalIgnoreCase)) { throw new CompilerException( string.Format("When running the {0} in an AppDomain without a system.codedom config section only the csharp language is supported. This happens if you are precompiling your views.", typeof(BatchCompiler).FullName)); } var compilerVersion = GetCompilerVersion(); var providerOptions = new Dictionary <string, string> { { "CompilerVersion", compilerVersion } }; codeProvider = new CSharpCodeProvider(providerOptions); compilerParameters = new CompilerParameters(); } compilerParameters.TreatWarningsAsErrors = false; var extension = codeProvider.FileExtension; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.IsDynamic()) { continue; } compilerParameters.ReferencedAssemblies.Add(assembly.Location); } CompilerResults compilerResults; var basePath = AppDomain.CurrentDomain.SetupInformation.DynamicBase ?? Path.GetTempPath(); if (debug) { compilerParameters.IncludeDebugInformation = true; var baseFile = Path.Combine(basePath, Guid.NewGuid().ToString("n")); var codeFiles = new List <string>(); int fileCount = 0; foreach (string sourceCodeItem in sourceCode) { ++fileCount; var codeFile = baseFile + "-" + fileCount + "." + extension; using (var stream = new FileStream(codeFile, FileMode.Create, FileAccess.Write)) { using (var writer = new StreamWriter(stream)) { writer.Write(sourceCodeItem); } } codeFiles.Add(codeFile); } if (!string.IsNullOrEmpty(OutputAssembly)) { compilerParameters.OutputAssembly = Path.Combine(basePath, OutputAssembly); } else { compilerParameters.OutputAssembly = baseFile + ".dll"; } compilerResults = codeProvider.CompileAssemblyFromFile(compilerParameters, codeFiles.ToArray()); } else { if (!string.IsNullOrEmpty(OutputAssembly)) { compilerParameters.OutputAssembly = Path.Combine(basePath, OutputAssembly); } else { // This should result in the assembly being loaded without keeping the file on disk compilerParameters.GenerateInMemory = true; } compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode); } if (compilerResults.Errors.HasErrors) { var sb = new StringBuilder(); sb.AppendLine("Dynamic view compilation failed."); foreach (CompilerError err in compilerResults.Errors) { sb.AppendFormat("{4}({0},{1}): {2} {3}: ", err.Line, err.Column, err.IsWarning ? "warning" : "error", err.ErrorNumber, err.FileName); sb.AppendLine(err.ErrorText); } sb.AppendLine(); foreach (var sourceCodeItem in sourceCode) { using (var reader = new StringReader(sourceCodeItem)) { for (int lineNumber = 1; ; ++lineNumber) { var line = reader.ReadLine(); if (line == null) { break; } sb.Append(lineNumber).Append(' ').AppendLine(line); } } } throw new BatchCompilerException(sb.ToString(), compilerResults); } return(compilerResults.CompiledAssembly); }
Assembly compileAssembly(string fileName) { var comp = new CompilerParameters(); var mainRefs = new List <string> { Path.Combine(Native.freeswitch.SWITCH_GLOBAL_dirs.mod_dir, "FreeSWITCH.Managed.dll"), "System.dll", "System.Xml.dll", "System.Data.dll" }; var extraRefs = new List <string> { "System.Core.dll", "System.Xml.Linq.dll", }; comp.ReferencedAssemblies.AddRange(mainRefs.ToArray()); comp.ReferencedAssemblies.AddRange(extraRefs.ToArray()); CodeDomProvider cdp; var ext = Path.GetExtension(fileName).ToLowerInvariant(); switch (ext) { case ".fsx": cdp = CodeDomProvider.CreateProvider("f#"); break; case ".csx": cdp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v3.5" } }); break; case ".vbx": cdp = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v3.5" } }); break; case ".jsx": // Have to figure out better JS support cdp = CodeDomProvider.CreateProvider("js"); extraRefs.ForEach(comp.ReferencedAssemblies.Remove); break; default: if (CodeDomProvider.IsDefinedExtension(ext)) { cdp = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(ext)); } else { return(null); } break; } comp.GenerateInMemory = true; comp.GenerateExecutable = true; Log.WriteLine(LogLevel.Info, "Compiling {0}", fileName); var res = cdp.CompileAssemblyFromFile(comp, fileName); var errors = res.Errors.Cast <CompilerError>().Where(x => !x.IsWarning).ToList(); if (errors.Count > 0) { Log.WriteLine(LogLevel.Error, "There were {0} errors compiling {1}.", errors.Count, fileName); foreach (var err in errors) { if (string.IsNullOrEmpty(err.FileName)) { Log.WriteLine(LogLevel.Error, "{0}: {1}", err.ErrorNumber, err.ErrorText); } else { Log.WriteLine(LogLevel.Error, "{0}: {1}:{2}:{3} {4}", err.ErrorNumber, err.FileName, err.Line, err.Column, err.ErrorText); } } return(null); } Log.WriteLine(LogLevel.Info, "File {0} compiled successfully.", fileName); return(res.CompiledAssembly); }