protected bool Supports (CodeDomProvider provider, GeneratorSupport support) { #if WHIDBEY return provider.Supports (support); #else return (provider.CreateGenerator ()).Supports (support); #endif }
internal string GetTypeName(CodeDomProvider codeProvider) { if (base.IsNeedNullable && codeProvider.Supports(GeneratorSupport.GenericTypeReference)) { return this.GetNullableType(base.TypeDesc); } return base.TypeDesc.FullName; }
/// <summary> /// Compile a set of source files with a specific provider /// </summary> /// <param name="files">Array of source files</param> /// <param name="referencedAssemblies">Array of referenced assemblies</param> /// <param name="outputFilePath">Output assembly file path</param> /// <param name="provider">Code dom provider</param> /// <returns>Compiler results</returns> public static CompilerResults Compile(List<string> files, List<string> referencedAssemblies, List<string> embeddedResourcesFiles, string outputFilePath, CodeDomProvider provider) { // Configure parameters CompilerParameters parms = new CompilerParameters(); parms.GenerateExecutable = false; parms.GenerateInMemory = false; parms.OutputAssembly = outputFilePath; parms.IncludeDebugInformation = false; if (provider.Supports(GeneratorSupport.Resources)) parms.EmbeddedResources.AddRange(embeddedResourcesFiles.ToArray()); parms.ReferencedAssemblies.AddRange(referencedAssemblies.ToArray()); // Compile return provider.CompileAssemblyFromFile(parms, files.ToArray()); }
private static CodeCompileUnit InternalCreate(Dictionary<string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable) { Hashtable hashtable; if (baseName == null) { throw new ArgumentNullException("baseName"); } if (codeProvider == null) { throw new ArgumentNullException("codeProvider"); } ArrayList errors = new ArrayList(0); SortedList list2 = VerifyResourceNames(resourceList, codeProvider, errors, out hashtable); string str = baseName; if (!codeProvider.IsValidIdentifier(str)) { string str2 = VerifyResourceName(str, codeProvider); if (str2 != null) { str = str2; } } if (!codeProvider.IsValidIdentifier(str)) { throw new ArgumentException(Microsoft.Build.Tasks.SR.GetString("InvalidIdentifier", new object[] { str })); } if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace)) { string str3 = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (str3 != null) { generatedCodeNamespace = str3; } } CodeCompileUnit e = new CodeCompileUnit(); e.ReferencedAssemblies.Add("System.dll"); e.UserData.Add("AllowLateBound", false); e.UserData.Add("RequireVariableDeclaration", true); CodeNamespace namespace2 = new CodeNamespace(generatedCodeNamespace); namespace2.Imports.Add(new CodeNamespaceImport("System")); e.Namespaces.Add(namespace2); CodeTypeDeclaration declaration = new CodeTypeDeclaration(str); namespace2.Types.Add(declaration); AddGeneratedCodeAttributeforMember(declaration); TypeAttributes attributes = internalClass ? TypeAttributes.AnsiClass : TypeAttributes.Public; declaration.TypeAttributes = attributes; declaration.Comments.Add(new CodeCommentStatement("<summary>", true)); declaration.Comments.Add(new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassDocComment"), true)); CodeCommentStatement statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments1"), true); declaration.Comments.Add(statement); statement = new CodeCommentStatement(Microsoft.Build.Tasks.SR.GetString("ClassComments3"), true); declaration.Comments.Add(statement); declaration.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeTypeReference attributeType = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType)); CodeTypeReference reference2 = new CodeTypeReference(typeof(CompilerGeneratedAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(reference2)); bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(declaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch); foreach (DictionaryEntry entry in list2) { string key = (string) entry.Key; string resourceName = (string) hashtable[key]; if (resourceName == null) { resourceName = key; } if (!DefineResourceFetchingProperty(key, resourceName, (ResourceData) entry.Value, declaration, internalClass, useStatic)) { errors.Add(entry.Key); } } unmatchable = (string[]) errors.ToArray(typeof(string)); CodeGenerator.ValidateIdentifiers(e); return e; }
public static bool CompileCode(CodeDomProvider provider, String[] sourceFile, String exeFile) { CompilerParameters cp = new CompilerParameters(); // Generate an executable instead of // a class library. cp.GenerateExecutable = true; // Set the assembly file name to generate. cp.OutputAssembly = exeFile; // Generate debug information. cp.IncludeDebugInformation = true; // Add an assembly reference. cp.ReferencedAssemblies.Add("Onyx.JS.api.dll"); // Save the assembly as a physical file. cp.GenerateInMemory = false; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 3; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. //cp.CompilerOptions = "/optimize"; // Set a temporary files collection. // The TempFileCollection stores the temporary files // generated during a build in the current directory, // and does not delete them after compilation. cp.TempFiles = new TempFileCollection(".", true); //if (provider.Supports(GeneratorSupport.EntryPointMethod)) //{ // // Specify the class that contains // // the main method of the executable. // cp.MainClass = "Samples.Class1"; //} if (Directory.Exists("Resources")) { if (provider.Supports(GeneratorSupport.Resources)) { // Set the embedded resource file of the assembly. // This is useful for culture-neutral resources, // or default (fallback) resources. cp.EmbeddedResources.Add("Resources\\Default.resources"); // Set the linked resource reference files of the assembly. // These resources are included in separate assembly files, // typically localized for a specific language and culture. cp.LinkedResources.Add("Resources\\nb-no.resources"); } } // Invoke compilation. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); if (cr.Errors.Count > 0) { // Display compilation errors. Console.WriteLine("Errors building {0} into {1}", sourceFile, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } } else { Console.WriteLine("Source {0} built into {1} successfully.", sourceFile, cr.PathToAssembly); Console.WriteLine("{0} temporary files created during the compilation.", cp.TempFiles.Count.ToString()); } // Return the results of compilation. if (cr.Errors.Count > 0) { return false; } else { return true; } }
public static bool CompileCode(CodeDomProvider provider, String sourceFile,List<string> filesToEmbed, String exeFile) { CompilerParameters cp = new CompilerParameters(); // Generate an executable instead of // a class library. cp.GenerateExecutable = true; // Set the assembly file name to generate. cp.OutputAssembly = exeFile; // Generate debug information. cp.IncludeDebugInformation = true; // Add an assembly reference. cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Core.dll"); cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Save the assembly as a physical file. cp.GenerateInMemory = false; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 3; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. cp.CompilerOptions = "/debug- /optimize+ /target:winexe";// "/optimize"; // Set a temporary files collection. // The TempFileCollection stores the temporary files // generated during a build in the current directory, // and does not delete them after compilation. cp.TempFiles = new TempFileCollection(".", true); if (provider.Supports(GeneratorSupport.EntryPointMethod)) { // Specify the class that contains // the main method of the executable. cp.MainClass = "skeleton.Program"; } //if (Directory.Exists("Resources")) //{ if (provider.Supports(GeneratorSupport.Resources)) { // Set the embedded resource file of the assembly. // This is useful for culture-neutral resources, // or default (fallback) resources. // cp.EmbeddedResources.Add(@"D:\PROJECTS\Tests\R_N_D\CompileCode\CompileCode\Extractor\CCD.resource"); cp.EmbeddedResources.AddRange(filesToEmbed.ToArray()); // cp.EmbeddedResources.Add("enc_1097421_JOHN_30-01-12_05-50-13.xml"); // Set the linked resource reference files of the assembly. // These resources are included in separate assembly files, // typically localized for a specific language and culture. // cp.LinkedResources.Add("Resources\\nb-no.resources"); } // } // Invoke compilation. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); if (cr.Errors.Count > 0) { // Display compilation errors. //Console.WriteLine("Errors building {0} into {1}", // sourceFile, cr.PathToAssembly); //foreach (CompilerError ce in cr.Errors) //{ // Console.WriteLine(" {0}", ce.ToString()); // Console.WriteLine(); //} } else { //Console.WriteLine("Source {0} built into {1} successfully.", // sourceFile, cr.PathToAssembly); //Console.WriteLine("{0} temporary files created during the compilation.", // cp.TempFiles.Count.ToString()); } // Return the results of compilation. if (cr.Errors.Count > 0) { return false; } else { return true; } }
private static CodeCompileUnit InternalCreate(Type callerType, Dictionary<string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, List<ResourceErrorData> unmatchable, string logicalName) { //logicalName added by Ðonny if (null == baseName) throw new ArgumentNullException("baseName"); if (null == codeProvider) throw new ArgumentNullException("codeProvider"); Dictionary<string, string> reverseFixupTable; SortedList<string, ResourceData> validResources = VerifyResourceNames(resourceList, codeProvider, unmatchable, out reverseFixupTable); string verifiedBaseName = baseName; if (!codeProvider.IsValidIdentifier(verifiedBaseName)) { string adjustedBaseName = VerifyResourceName(verifiedBaseName, codeProvider); if (adjustedBaseName != null) verifiedBaseName = adjustedBaseName; } if (!codeProvider.IsValidIdentifier(verifiedBaseName)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, InvalidIdentifier, verifiedBaseName)); if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace)) { string adjustedCodeNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (adjustedCodeNamespace != null) generatedCodeNamespace = adjustedCodeNamespace; } CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.ReferencedAssemblies.Add("System.dll"); codeCompileUnit.UserData.Add("AllowLateBound", false); codeCompileUnit.UserData.Add("RequireVariableDeclaration", true); CodeNamespace codeNamespace = new CodeNamespace(generatedCodeNamespace); codeNamespace.Imports.Add(new CodeNamespaceImport("System")); codeCompileUnit.Namespaces.Add(codeNamespace); CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(verifiedBaseName); codeNamespace.Types.Add(codeTypeDeclaration); AddGeneratedCodeAttributeforMember(codeTypeDeclaration); TypeAttributes typeAttributes = TypeAttributes.AutoLayout; if (!internalClass) typeAttributes |= TypeAttributes.Public; codeTypeDeclaration.TypeAttributes = typeAttributes; AddComments(codeTypeDeclaration, ClassDocComment); if (codeProvider.FileExtension.ToLowerInvariant() == "vb")//Visual Basic - generate module codeTypeDeclaration.UserData.Add("Module", true); CodeTypeReference debuggerNonUserCodeTypeReference = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute), CodeTypeReferenceOptions.GlobalReference); codeTypeDeclaration.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerNonUserCodeTypeReference)); CodeAttributeDeclaration suppressAttributeTypeDeclaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute))); suppressAttributeTypeDeclaration.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference; suppressAttributeTypeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Naming"))); suppressAttributeTypeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1724:TypeNamesShouldNotMatchNamespaces"))); codeTypeDeclaration.CustomAttributes.Add(suppressAttributeTypeDeclaration); bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(callerType, codeTypeDeclaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch, logicalName, codeProvider.FileExtension.ToLowerInvariant() != "vb"); //logicalName added by Ðonny SortedList<string, ResourceData> formatMethods = new SortedList<string, ResourceData>(validResources.Count, StringComparer.InvariantCultureIgnoreCase); // Generate resource fetching properties foreach (KeyValuePair<string, ResourceData> validResourceEntry in validResources) { string initialResourceKey; if (!reverseFixupTable.TryGetValue(validResourceEntry.Key, out initialResourceKey)) initialResourceKey = validResourceEntry.Key; if (!DefineResourceFetchingProperty(validResourceEntry.Key, initialResourceKey, validResourceEntry.Value, codeTypeDeclaration, internalClass, useStatic)) { unmatchable.Add(new ResourceErrorData(validResourceEntry.Key.ToString(), string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, validResourceEntry.Key.ToString()))); } else if (typeof(string) == validResourceEntry.Value.Type) formatMethods.Add(validResourceEntry.Key, validResourceEntry.Value); } // Generate resource fetching format methods foreach (KeyValuePair<string, ResourceData> formatMethodEntry in formatMethods) { try { string methodName = formatMethodEntry.Key + FormatSuffix; // Check for duplicate method names bool uniqueMethodName = true; foreach (CodeTypeMember codeTypeMember in codeTypeDeclaration.Members) { if (null == codeTypeMember) continue; if (codeTypeMember.Name == methodName) { uniqueMethodName = false; break; } } if (!uniqueMethodName) continue; int numberOfArguments = FormatValidator.Parse(formatMethodEntry.Value.ValueIfString); if (codeProvider.IsValidIdentifier(methodName)) { string initialResourceKey; if (!reverseFixupTable.TryGetValue(formatMethodEntry.Key, out initialResourceKey)) initialResourceKey = formatMethodEntry.Key; DefineFormattedResourceFetchingMethod(methodName, formatMethodEntry.Key, initialResourceKey, formatMethodEntry.Value, codeTypeDeclaration, internalClass, useStatic, numberOfArguments); } else { unmatchable.Add(new ResourceErrorData(methodName, string.Format(CultureInfo.CurrentCulture, CannotCreateFormatMethod, methodName, formatMethodEntry.Key))); } } catch (FormatException ex) { unmatchable.Add(new ResourceErrorData(formatMethodEntry.Key.ToString(), string.Format(CultureInfo.CurrentCulture, ErrorInFormatPropertyForResource, ex.Message, formatMethodEntry.Key.ToString()))); } } CodeGenerator.ValidateIdentifiers(codeCompileUnit); return codeCompileUnit; }
private static CodeCompileUnit InternalCreate(Dictionary<String, ResourceData> resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable) { if (baseName == null) throw new ArgumentNullException("baseName"); if (codeProvider == null) throw new ArgumentNullException("codeProvider"); // Keep a list of errors describing known strings that couldn't be // fixed up (like "4"), as well as listing all duplicate resources that // were fixed up to the same name (like "A B" and "A-B" both going to // "A_B"). ArrayList errors = new ArrayList(0); // Verify the resource names are valid property names, and they don't // conflict. This includes checking for language-specific keywords, // translating spaces to underscores, etc. SortedList cleanedResourceList; Hashtable reverseFixupTable; cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out reverseFixupTable); // Verify the class name is legal. String className = baseName; // Attempt to fix up class name, and throw an exception if it fails. if (!codeProvider.IsValidIdentifier(className)) { String fixedClassName = VerifyResourceName(className, codeProvider); if (fixedClassName != null) className = fixedClassName; } if (!codeProvider.IsValidIdentifier(className)) throw new ArgumentException(SR.GetString(SR.InvalidIdentifier, className)); // If we have a namespace, verify the namespace is legal, // attempting to fix it up if needed. if (!String.IsNullOrEmpty(generatedCodeNamespace)) { if (!codeProvider.IsValidIdentifier(generatedCodeNamespace)) { String fixedNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (fixedNamespace != null) generatedCodeNamespace = fixedNamespace; } // Note we cannot really ensure that the generated code namespace // is a valid identifier, as namespaces can have '.' and '::', but // identifiers cannot. } CodeCompileUnit ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.Add("System.dll"); ccu.UserData.Add("AllowLateBound", false); ccu.UserData.Add("RequireVariableDeclaration", true); CodeNamespace ns = new CodeNamespace(generatedCodeNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ccu.Namespaces.Add(ns); // Generate class CodeTypeDeclaration srClass = new CodeTypeDeclaration(className); ns.Types.Add(srClass); AddGeneratedCodeAttributeforMember(srClass); TypeAttributes ta = internalClass ? TypeAttributes.NotPublic : TypeAttributes.Public; //ta |= TypeAttributes.Sealed; srClass.TypeAttributes = ta; srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); srClass.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ClassDocComment), true)); CodeCommentStatement comment = new CodeCommentStatement(SR.GetString(SR.ClassComments1), true); srClass.Comments.Add(comment); comment = new CodeCommentStatement(SR.GetString(SR.ClassComments3), true); srClass.Comments.Add(comment); srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); CodeTypeReference debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)); debuggerAttrib.Options = CodeTypeReferenceOptions.GlobalReference; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib)); CodeTypeReference compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)); compilerGenedAttrib.Options = CodeTypeReferenceOptions.GlobalReference; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(compilerGenedAttrib)); // Figure out some basic restrictions to the code generation bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch); // Now for each resource, add a property foreach(DictionaryEntry entry in cleanedResourceList) { String propertyName = (String) entry.Key; // The resourceName will be the original value, before fixups, // if any. String resourceName = (String) reverseFixupTable[propertyName]; if (resourceName == null) resourceName = propertyName; bool r = DefineResourceFetchingProperty(propertyName, resourceName, (ResourceData) entry.Value, srClass, internalClass, useStatic); if (!r) { errors.Add(entry.Key); } } unmatchable = (String[]) errors.ToArray(typeof(String)); // Validate the generated class now CodeGenerator.ValidateIdentifiers(ccu); return ccu; }
bool Compile( CodeDomProvider provider, string dataContextCode, PadConfig config, String dllFile ) { if (!dllFile.EndsWith(".dll")) dllFile += ".dll"; dcAutoGenFile = dllFile; CompilerParameters cp = new CompilerParameters(); // Generate a class library. cp.GenerateExecutable = false; // Generate debug information. cp.IncludeDebugInformation = false; // Add assembly references. cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("Iesi.Collections.dll"); // Save the assembly as a physical file. cp.GenerateInMemory = false; cp.OutputAssembly = dcAutoGenFile; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 3; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. cp.CompilerOptions = "/optimize"; string workDir = Path.Combine(Path.GetTempPath(), "SpoolPad$temp$" + config.Name); if (!Directory.Exists(workDir)) Directory.CreateDirectory(workDir); foreach (MapConfig map in config.Mappings) { if (map.IsValid) { if (provider.Supports(GeneratorSupport.Resources)) { if (!config.DataContext.AutoGen) { if (map.IsFile) cp.EmbeddedResources.Add(map.Map); else if (map.IsAssembly) { string tempFile = Path.Combine(workDir, Path.GetFileName(map.ResourceName)); TextReader tr = new StreamReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName)); File.WriteAllText(tempFile, tr.ReadToEnd()); cp.EmbeddedResources.Add(tempFile); } else continue; } else { XDocument doc = null; if (map.IsAssembly) { doc = XDocument.Load(new XmlTextReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName))); } else if (map.IsFile) { doc = XDocument.Load(map.Map); } else continue; var hibmap = doc.Root; if (hibmap != null) { hibmap.SetAttributeValue("assembly", config.Name); hibmap.SetAttributeValue("namespace", config.DataContextAutoGenNamespace); string tempFile = Path.Combine(workDir, Path.GetFileName(map.Map)); doc.Save(tempFile); cp.EmbeddedResources.Add(tempFile); } } } } } CompilerResults cr = provider.CompileAssemblyFromSource(cp, dataContextCode); Directory.Delete(workDir, true); if (cr.Errors.Count > 0) { // Display compilation errors. _log.ErrorFormat("Errors building {0}", cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { _log.DebugFormat(" {0}", ce.ToString()); } } else { _log.DebugFormat("Source built into {0} successfully.", cr.PathToAssembly); } // Return the results of compilation. if (cr.Errors.Count > 0) { return false; } else { return true; } }