public void GenerateCode(string szFileName, string szLanguage) { CodeDomProvider oCodeDomProvider = CodeDomProvider.CreateProvider(szLanguage); CodeGeneratorOptions oCodeGeneratorOptions = new CodeGeneratorOptions(); oCodeGeneratorOptions.BracingStyle = "C"; if (oCodeDomProvider.Supports(GeneratorSupport.DeclareEnums)) { //output enums } else { //output constants } using (StreamWriter oStreamWriter = new StreamWriter(szFileName)) { oCodeDomProvider.GenerateCodeFromCompileUnit(oCodeCompileUnit, oStreamWriter, oCodeGeneratorOptions); } if (oCodeDomProvider.Supports(GeneratorSupport.DeclareEnums)) { } }
static void addMain(CodeDomProvider cdp, CodeTypeDeclaration ret, CodeMemberMethod m, CodeNamespace ns) { CodeEntryPointMethod cepm; CodeObjectCreateExpression ce; CodeVariableReferenceExpression vr; string aType; if (cdp.Supports(GeneratorSupport.EntryPointMethod)) { aType = ret.Name; if (string.Compare(cdp.FileExtension, "h", true) == 0) { if (!string.IsNullOrEmpty(ns.Name)) { aType = ns.Name + "::" + ret.Name; } } ce = new CodeObjectCreateExpression(aType); ret.Members.Add(cepm = new CodeEntryPointMethod()); vr = new CodeVariableReferenceExpression("anObj"); cepm.Statements.Add(new CodeVariableDeclarationStatement(ce.CreateType, vr.VariableName, ce)); cepm.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(vr, m.Name))); } }
protected virtual CodeTypeDeclaration GenerateClass(CodeNamespace @namespace) { var generator = typeof(ResourceTypeBuilder); var version = generator.Assembly.GetName( ).Version; var type = Declare.Class(settings.ClassName) .Modifiers(settings.AccessModifiers) .IsPartial(CodeDomProvider.Supports(GeneratorSupport.PartialTypes)) .AddSummary(ClassSummary) .AddTo(@namespace); if (settings.CustomToolType != null) { type.AddRemarks(ClassRemarksFormat, generator.FullName, settings.CustomToolType.Name); } else { type.AddRemarks(ClassRemarksToollessFormat, generator.FullName); } if (string.Equals(@namespace.Name.Split('.').Last( ), settings.ClassName, StringComparison.OrdinalIgnoreCase)) { type.Attributed(Declare.Attribute <SuppressMessageAttribute> ("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")); } return(type.Attributed(Declare.Attribute <GeneratedCodeAttribute> (generator.FullName, version.ToString( )), Declare.Attribute <DebuggerNonUserCodeAttribute> ( ), Declare.Attribute <ObfuscationAttribute> ( ) .WithArgument(nameof(ObfuscationAttribute.Exclude), true) .WithArgument(nameof(ObfuscationAttribute.ApplyToMembers), true))); }
protected CodeExpression GenerateSingleton(CodeTypeDeclaration @class, CodeTypeReference type, string fieldName, CodeExpression initializer) { var cctor = Declare.Constructor( ).Static( ) .AddComment(SingletonBeforeFieldInitComment); if (CodeDomProvider.Supports(GeneratorSupport.NestedTypes)) { var lazyType = Declare.NestedClass(fieldName).Private( ).Static( ) .AddTo(@class); cctor.AddTo(lazyType); Declare.Field(type, SingletonFieldName).Internal( ).Static( ) .Initialize(initializer) .AddTo(lazyType); return(Code.Type(fieldName).Local( ) .Static( ) .Field(SingletonFieldName)); } else { Declare.Field(type, fieldName).Private( ).Static( ) .Initialize(initializer) .AddTo(@class); if ([email protected] <CodeTypeConstructor> ( ).Any( )) { @class.Members.Add(cctor); } return(Code.Static( ).Field(fieldName)); } }
static void Main() { foreach (CompilerInfo ci in CodeDomProvider.GetAllCompilerInfo()) { StringBuilder output = new StringBuilder(); string language = ci.GetLanguages()[0]; output.AppendFormat("{0} features:\r\n", language); try { CodeDomProvider provider = CodeDomProvider .CreateProvider(language); output.AppendFormat("CaseInsensitive = {0}\r\n", provider.LanguageOptions.HasFlag( LanguageOptions.CaseInsensitive)); foreach (GeneratorSupport supportableFeature in Enum.GetValues(typeof(GeneratorSupport))) { output.AppendFormat("{0} = {1}\r\n", supportableFeature, provider.Supports(supportableFeature)); } } catch (Exception ex) { output.AppendFormat("{0} occurred while getting " + "features for language {1} with the following " + "message:\r\n\r\n'{2}'.\r\n", ex.GetType().Name, language, ex.Message); } Console.WriteLine(output.ToString()); } Console.ReadLine(); }
public static String GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit) { // Build the source file name with the language // extension (vb, cs, js). String sourceFile = ""; // Write the source out in the selected language if // the code generator supports partial type declarations. if (provider.Supports(GeneratorSupport.PartialTypes)) { if (provider.FileExtension[0] == '.') { sourceFile = "DocProp" + provider.FileExtension; } else { sourceFile = "DocProp." + provider.FileExtension; } // Create a TextWriter to a StreamWriter to an output file. IndentedTextWriter outWriter = new IndentedTextWriter(new StreamWriter(sourceFile, false), " "); // Generate source code using the code generator. provider.GenerateCodeFromCompileUnit(compileUnit, outWriter, null); // Close the output file. outWriter.Close(); } return(sourceFile); }
static void generateGotoStuff(CodeDomProvider cdp, CodeMemberMethod m) { if (cdp.Supports(GeneratorSupport.GotoStatements)) { const string LABEL_1 = "here"; const string LABEL_2 = "there"; m.Statements.Add(new CodeLabeledStatement(LABEL_1)); m.Statements.Add(new CodeGotoStatement(LABEL_2)); m.Statements.Add(new CodeGotoStatement(LABEL_1)); m.Statements.Add(new CodeLabeledStatement(LABEL_2)); } else { if (string.Compare(cdp.FileExtension, "js", true) == 0) { m.Statements.Add( new CodeThrowExceptionStatement( new CodeObjectCreateExpression("Error", new CodePrimitiveExpression("here")))); } else { m.Statements.Add(new CodeSnippetStatement("#warning GOTO not allowed!")); } } }
private CompilerParameters BuildParameters(CodeDomProvider provider) { var parameters = new CompilerParameters { OutputAssembly = _outputFileName, GenerateExecutable = _target != Target.Library, CompilerOptions = $"/target:{_target.ToString().ToLowerInvariant()}", }; if (_symbols.Any()) { parameters.CompilerOptions += $" /define:{string.Join(";", _symbols)}"; } if (!string.IsNullOrEmpty(_iconFilename)) { parameters.CompilerOptions += $" /win32icon:\"{_iconFilename}\""; } var references = _references .Select(r => r.EndsWith(LibraryExtension) ? r : $"{r}.{LibraryExtension}") .ToArray(); parameters.ReferencedAssemblies.AddRange(references); if (provider.Supports(GeneratorSupport.Resources)) { parameters.EmbeddedResources.AddRange(_embeddedResources.ToArray()); } return(parameters); }
internal string GetTypeName(CodeDomProvider codeProvider) { if (base.IsNeedNullable && codeProvider.Supports(GeneratorSupport.GenericTypeReference)) { return(this.GetNullableType(base.TypeDesc)); } return(base.TypeDesc.FullName); }
protected bool Supports(CodeDomProvider provider, GeneratorSupport support) { #if WHIDBEY return(provider.Supports(support)); #else return((provider.CreateGenerator()).Supports(support)); #endif }
public static MemberAttributes ValidateAccessModifiers(this CodeDomProvider codeDomProvider, MemberAttributes accessModifiers) { if (accessModifiers.HasBitMask(MemberAttributes.Public | MemberAttributes.Static)) { if (!codeDomProvider.Supports(GeneratorSupport.PublicStaticMembers)) { accessModifiers &= ~MemberAttributes.Static; } } return(accessModifiers); }
/// <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())); }
/// <summary> /// Checks if a script has a error in it's code. /// </summary> /// <param name="script">The script file.</param> public static int Debug(string script) { int i = 0; File.Delete(@"compile_errors.txt"); CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameters = new CompilerParameters(); if (codeDomProvider.Supports(GeneratorSupport.EntryPointMethod)) { parameters.MainClass = "Script"; } parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.ReferencedAssemblies.Add("3DRadSpaceDll.dll"); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.ReferencedAssemblies.Add("System.Console.dll"); parameters.ReferencedAssemblies.Add("mscorlib.dll"); parameters.ReferencedAssemblies.Add("netstandard.dll"); CompilerResults results = codeDomProvider.CompileAssemblyFromFile(parameters, script); CompilerErrorCollection errors = results.Errors; for (int j = 0; j < errors.Count; j++) { File.AppendAllText(@"compile_errors.txt", errors[i].ErrorText + " Line:" + errors[i].Line + " Is warning:" + errors[i].IsWarning + " \r\n"); } if (errors.HasErrors == false) { Assembly compiledcode = results.CompiledAssembly; for (i = 0; i < _3DRadSpaceGame.MAX_SCRIPTS; i++) { if (scripts[i] == null) { scripts[i] = compiledcode; break; } } } else { Process.Start(@"compile_errors.txt"); throw new ScriptError(File.ReadAllText(@"compile_errors.txt")); } return(i); }
static void generateEventCalls(CodeDomProvider cdp, CodeMemberEvent cme, CodeMemberMethod m, CodeTypeDeclaration ctd, CodeMemberMethod m2, CodeTypeDelegate ctdDel) { CodeEventReferenceExpression cere; if (cdp.Supports(GeneratorSupport.DeclareEvents)) { cere = new CodeEventReferenceExpression(null, cme.Name); CodeDelegateCreateExpression cdce = new CodeDelegateCreateExpression( cme.Type, ceThis0, m2.Name); CodeParameterDeclarationExpressionCollection parms = new CodeParameterDeclarationExpressionCollection(); populateParmList(parms, ctdDel); m.Statements.Add(new CodeAttachEventStatement(cere, cdce)); m.Statements.Add(new CodeDelegateInvokeExpression(cere, makeArgList(parms))); m.Statements.Add(new CodeRemoveEventStatement(cere, cdce)); } }
public override void VerifyAssembly(CodeDomProvider provider, Assembly asm) { #if WHIDBEY if (provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { object genObject; Type genType; AddScenario("InstantiateTest"); if (!FindAndInstantiate("TestNamespace.Test", asm, out genObject, out genType)) { return; } VerifyScenario("InstantiateTest"); // verify scenario with 'new' attribute if (VerifyMethod(genType, genObject, "MyMethod", null, 275)) { VerifyScenario("CheckMyMethod"); } } #endif }
static CodeTypeDeclaration createType(string className, CodeDomProvider cdp, CodeNamespace ns) { CodeTypeDeclaration ret = new CodeTypeDeclaration(className); CodeMemberMethod m2 = null, m; CodeMemberField f; CodeFieldReferenceExpression fr; CodeMemberProperty p; CodeMemberEvent cme = null; CodeTypeDelegate ctd2 = null; if (cdp.Supports(GeneratorSupport.DeclareEvents)) { const string HANLDER_NAME = "BlahEventHandler"; ctd2 = createDelegateType(ret, HANLDER_NAME); cme = createEvent(ret, ctd2, "myEvent"); ret.Members.Add(m2 = createSimpleMethod()); } ret.Members.Add(f = createField(out fr)); ret.Members.Add(p = createProperty(fr, f.Type)); ret.Members.Add(m = createStatementMethod1(m2, cdp, cme, ctd2, ret)); addMain(cdp, ret, m, ns); return(ret); }
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) { #if WHIDBEY if (provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { object genObject; Type genType; AddScenario ("InstantiateTest"); if (!FindAndInstantiate ("TestNamespace.Test", asm, out genObject, out genType)) return; VerifyScenario ("InstantiateTest"); // verify scenario with 'new' attribute if (VerifyMethod(genType, genObject, "MyMethod", null, 275)) { VerifyScenario ("CheckMyMethod"); } } #endif }
//<Snippet2> 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("System.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 sourceCode, String exeFile ) { CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = true; cp.OutputAssembly = exeFile; cp.IncludeDebugInformation = true; cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add(@"D:\projects\X3D\x3d-finely-sharpened\OpenTK\OpenTK.dll"); cp.ReferencedAssemblies.Add(@"D:\projects\X3D\x3d-finely-sharpened\X3DRuntime\bin\Debug\X3DRuntime.exe"); cp.ReferencedAssemblies.Add(@"D:\projects\X3D\x3d-finely-sharpened\X3DRuntime\bin\Debug\X3D.dll"); cp.GenerateInMemory = false; // Save the assembly as a physical file. // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 3; cp.TreatWarningsAsErrors = false; cp.CompilerOptions = "/optimize"; cp.TempFiles = new TempFileCollection(".", true); if (provider.Supports(GeneratorSupport.EntryPointMethod)) { // Specify the class that contains // the main method of the executable. cp.MainClass = "X3D.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("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.CompileAssemblyFromSource(cp, sourceCode.Split('\n')); //CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); if (cr.Errors.Count > 0) { // Display compilation errors. Console.WriteLine("Errors building source code into {0}", cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } } else { Console.WriteLine("Source code built into {0} successfully.", 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 override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY // GENERATES (C#): // namespace TestNamespace { // using System; // using System.Collections.Generic; // // // public class MyDictionary<K, V> : Dictionary<K, V> // where K : System.IComparable, IComparable<K>, new () // where V : IList<string> { // // public virtual int Calculate<S, T>(int value1, int value2) // where S : new() // { // return (value1 * value2); // } // } // // public class Test { // // public virtual int MyMethod() { // int dReturn; // MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>(); // dReturn = dict.Calculate<int, int>(2.5, 11); // return dReturn; // } // } // } if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { return; } CodeNamespace ns = new CodeNamespace("TestNamespace"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); cu.Namespaces.Add (ns); // Declare a generic class CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add( new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("K"), new CodeTypeReference("V"),})); CodeTypeParameter kType = new CodeTypeParameter("K"); kType.HasConstructorConstraint= true; kType.Constraints.Add( new CodeTypeReference(typeof(IComparable))); kType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType")))); CodeTypeReference iComparableT = new CodeTypeReference("IComparable"); iComparableT.TypeArguments.Add(new CodeTypeReference(kType)); kType.Constraints.Add(iComparableT); CodeTypeParameter vType = new CodeTypeParameter("V"); vType.Constraints.Add(new CodeTypeReference("IList[System.String]")); class1.TypeParameters.Add(kType); class1.TypeParameters.Add(vType); ns.Types.Add(class1); // declare a generic method CodeMemberMethod method = new CodeMemberMethod(); CodeTypeParameter sType = new CodeTypeParameter("S"); sType.HasConstructorConstraint = true; CodeTypeParameter tType = new CodeTypeParameter("T"); sType.HasConstructorConstraint = true; method.Name = "Calculate"; method.TypeParameters.Add(sType); method.TypeParameters.Add(tType); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value1")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value2")); method.ReturnType = new CodeTypeReference(typeof(int)); method.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("value1"), CodeBinaryOperatorType.Multiply, new CodeVariableReferenceExpression("value2")))); method.Attributes = MemberAttributes.Public; class1.Members.Add(method); CodeTypeDeclaration class2 = new CodeTypeDeclaration(); class2.Name = "Test"; AddScenario ("CheckMyMethod"); CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "MyMethod"; method2.Attributes = MemberAttributes.Public; method2.ReturnType = new CodeTypeReference(typeof(int)); method2.Statements.Add( new CodeVariableDeclarationStatement(typeof(int), "dReturn")); CodeTypeReference myClass = new CodeTypeReference( "MyDictionary", new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List", new CodeTypeReference[] {new CodeTypeReference("System.String") })} ); method2.Statements.Add( new CodeVariableDeclarationStatement( myClass, "dict", new CodeObjectCreateExpression(myClass) )); method2.Statements.Add(new CodeAssignStatement( new CodeVariableReferenceExpression("dReturn"), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("dict"), "Calculate", new CodeTypeReference[] { new CodeTypeReference("System.Int32"), new CodeTypeReference("System.Int32"),}), new CodeExpression[]{new CodePrimitiveExpression(25), new CodePrimitiveExpression(11)}))); method2.Statements.Add (new CodeMethodReturnStatement(new CodeVariableReferenceExpression("dReturn"))); class2.Members.Add(method2); ns.Types.Add(class2); #endif }
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(System.Design.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(System.Design.SR.GetString("ClassDocComment"), true)); 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 void CompileExecutable(string csPath, string dllPath, string outFileName, string outFilePath) { //var uid = csPath.GetHashCode() ^ dllPath.GetHashCode(); List <string> csFiles = new FileHelper(csPath, "*.cs").GetAllFiles(); List <string> csFileNames = new FileHelper(csPath, "*.cs").GetAllFileNames(); List <string> dllFiles = new FileHelper(dllPath, "*.dll").GetAllFiles(); provider = CodeDomProvider.CreateProvider("CSharp"); if (provider != null) { CompilerParameters cp = new CompilerParameters() { CompilerOptions = "/optimize", GenerateExecutable = false, GenerateInMemory = true, IncludeDebugInformation = false, TreatWarningsAsErrors = false, OutputAssembly = Path.Combine(outFilePath, outFileName), WarningLevel = 4 }; var prefix = outFileName.Remove(outFileName.IndexOf('.'), 1); var resName = "CSNames"; string xmlResource = Path.Combine(Logger.ServiceLogPath, prefix + resName); SerializeHelper.SerializeToXML ( Logger.ServiceLogPath, new CSFiles() { CSFileNames = csFileNames }, prefix + resName, false ); if (File.Exists(xmlResource + ".xml")) { if (provider.Supports(GeneratorSupport.Resources)) { cp.EmbeddedResources.Add(xmlResource + ".xml"); } } cp.ReferencedAssemblies.AddRange(Libraries.CommonFrameworkLibraries); dllFiles.ForEach( a => { var name = new FileInfo(a).Name; if (!Libraries.CommonFrameworkLibraries.Contains(name, new CustomStrComparer())) { cp.ReferencedAssemblies.Add(a); } //The follow can do the same thing as above... //if (!Array.Exists(Libraries.CommonFrameworkLibraries,s=>string.Equals(s.ToUpper(),name.ToUpper()))) // cp.ReferencedAssemblies.Add(a); }); CompilerResults cr = provider.CompileAssemblyFromFile(cp, csFiles.ToArray()); CompileResult results; LogModel model; if (cr.Errors.Count > 0) { var errorArray = new CompilerError[cr.Errors.Count]; cr.Errors.CopyTo(errorArray, 0); var warnings = errorArray.Where(e => e.IsWarning).ToList(); var errors = errorArray.Where(e => !e.IsWarning).ToList(); results = new CompileResult() { IsBuildSuccess = errors.Count > 0 ? false : true, Warnings = warnings, Errors = errors }; } else { results = new CompileResult() { IsBuildSuccess = true, Warnings = null, Errors = null }; } model = new LogModel() { CurrentFolder = csPath, DllPath = dllPath, CompileTime = DateTime.Now, CSFileNames = csFileNames, Results = results }; SerializeHelper.SerializeToXML(outputFolder, model, prefix, true); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // #region Compile Unit Region // // namespace Namespace1 { // // // #region Outer Type Region // // Outer Type Comment // public class Class1 { // // // Field 1 Comment // private string field1; // // public void Method1() { // this.Event1(this, System.EventArgs.Empty); // } // // #region Constructor Region // public Class1() { // #region Statements Region // this.field1 = "value1"; // this.field2 = "value2"; // #endregion // } // #endregion // // public string Property1 { // get { // return this.field1; // } // } // // public static void Main() { // } // // public event System.EventHandler Event1; // // public class NestedClass1 { // } // // public delegate void nestedDelegate1(object sender, System.EventArgs e); // // // // #region Field Region // private string field2; // #endregion // // #region Method Region // // Method 2 Comment // // #line 500 "MethodLinePragma.txt" // public void Method2() { // this.Event2(this, System.EventArgs.Empty); // } // // #line default // #line hidden // #endregion // // public Class1(string value1, string value2) { // } // // #region Property Region // public string Property2 { // get { // return this.field2; // } // } // #endregion // // #region Type Constructor Region // static Class1() { // } // #endregion // // #region Event Region // public event System.EventHandler Event2; // #endregion // // #region Nested Type Region // // Nested Type Comment // // #line 400 "NestedTypeLinePragma.txt" // public class NestedClass2 { // } // // #line default // #line hidden // #endregion // // #region Delegate Region // public delegate void nestedDelegate2(object sender, System.EventArgs e); // #endregion // // #region Snippet Region // // #endregion // } // #endregion // } // #endregion CodeNamespace ns = new CodeNamespace ("Namespace1"); cu.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Compile Unit Region")); cu.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1"); ns.Types.Add (cd); cd.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Outer Type Region")); cd.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cd.Comments.Add (new CodeCommentStatement ("Outer Type Comment")); CodeMemberField field1 = new CodeMemberField (typeof (String), "field1"); CodeMemberField field2 = new CodeMemberField (typeof (String), "field2"); field1.Comments.Add (new CodeCommentStatement ("Field 1 Comment")); field2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Field Region")); field2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberEvent evt1 = new CodeMemberEvent (); evt1.Name = "Event1"; evt1.Type = new CodeTypeReference (typeof (System.EventHandler)); evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeMemberEvent evt2 = new CodeMemberEvent (); evt2.Name = "Event2"; evt2.Type = new CodeTypeReference (typeof (System.EventHandler)); evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; evt2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Event Region")); evt2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports (GeneratorSupport.DeclareEvents)) { method1.Statements.Add ( new CodeDelegateInvokeExpression ( new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event1"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } CodeMemberMethod method2 = new CodeMemberMethod (); method2.Name = "Method2"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports (GeneratorSupport.DeclareEvents)) { method2.Statements.Add ( new CodeDelegateInvokeExpression ( new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event2"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } method2.LinePragma = new CodeLinePragma ("MethodLinePragma.txt", 500); method2.Comments.Add (new CodeCommentStatement ("Method 2 Comment")); method2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Method Region")); method2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeMemberProperty property1 = new CodeMemberProperty (); property1.Name = "Property1"; property1.Type = new CodeTypeReference (typeof (string)); property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property1.GetStatements.Add ( new CodeMethodReturnStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field1"))); CodeMemberProperty property2 = new CodeMemberProperty (); property2.Name = "Property2"; property2.Type = new CodeTypeReference (typeof (string)); property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property2.GetStatements.Add ( new CodeMethodReturnStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field2"))); property2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Property Region")); property2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeConstructor constructor1 = new CodeConstructor (); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeStatement conState1 = new CodeAssignStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field1"), new CodePrimitiveExpression ("value1")); conState1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Statements Region")); constructor1.Statements.Add (conState1); CodeStatement conState2 = new CodeAssignStatement ( new CodeFieldReferenceExpression ( new CodeThisReferenceExpression (), "field2"), new CodePrimitiveExpression ("value2")); conState2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); constructor1.Statements.Add (conState2); constructor1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Constructor Region")); constructor1.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeConstructor constructor2 = new CodeConstructor (); constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value1")); constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value2")); CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor (); typeConstructor2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Type Constructor Region")); typeConstructor2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeEntryPointMethod methodMain = new CodeEntryPointMethod (); CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration ("NestedClass1"); CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration ("NestedClass2"); nestedClass2.LinePragma = new CodeLinePragma ("NestedTypeLinePragma.txt", 400); nestedClass2.Comments.Add (new CodeCommentStatement ("Nested Type Comment")); nestedClass2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Nested Type Region")); nestedClass2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeTypeDelegate delegate1 = new CodeTypeDelegate (); delegate1.Name = "nestedDelegate1"; delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender")); delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e")); CodeTypeDelegate delegate2 = new CodeTypeDelegate (); delegate2.Name = "nestedDelegate2"; delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender")); delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e")); delegate2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Delegate Region")); delegate2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); CodeSnippetTypeMember snippet1 = new CodeSnippetTypeMember (); CodeSnippetTypeMember snippet2 = new CodeSnippetTypeMember (); CodeRegionDirective regionStart = new CodeRegionDirective (CodeRegionMode.End, ""); regionStart.RegionText = "Snippet Region"; regionStart.RegionMode = CodeRegionMode.Start; snippet2.StartDirectives.Add (regionStart); snippet2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty)); cd.Members.Add (field1); cd.Members.Add (method1); cd.Members.Add (constructor1); cd.Members.Add (property1); cd.Members.Add (methodMain); if (Supports (provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add (evt1); } if (Supports (provider, GeneratorSupport.NestedTypes)) { cd.Members.Add (nestedClass1); if (Supports (provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add (delegate1); } } cd.Members.Add (snippet1); cd.Members.Add (field2); cd.Members.Add (method2); cd.Members.Add (constructor2); cd.Members.Add (property2); if (Supports (provider, GeneratorSupport.StaticConstructors)) { cd.Members.Add (typeConstructor2); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add (evt2); } if (Supports (provider, GeneratorSupport.NestedTypes)) { cd.Members.Add (nestedClass2); if (Supports (provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add (delegate2); } } cd.Members.Add (snippet2); } #endif }
public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY // GENERATES (C#): // namespace TestNamespace { // using System; // using System.Collections.Generic; // // // public class MyDictionary<K, V> : Dictionary<K, V> // where K : System.IComparable, IComparable<K>, new () // where V : IList<string> { // // public virtual int Calculate<S, T>(int value1, int value2) // where S : new() // { // return (value1 * value2); // } // } // // public class Test { // // public virtual int MyMethod() { // int dReturn; // MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>(); // dReturn = dict.Calculate<int, int>(2.5, 11); // return dReturn; // } // } // } if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { return; } CodeNamespace ns = new CodeNamespace("TestNamespace"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); cu.Namespaces.Add(ns); // Declare a generic class CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("K"), new CodeTypeReference("V"), })); CodeTypeParameter kType = new CodeTypeParameter("K"); kType.HasConstructorConstraint = true; kType.Constraints.Add(new CodeTypeReference(typeof(IComparable))); kType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType")))); CodeTypeReference iComparableT = new CodeTypeReference("IComparable"); iComparableT.TypeArguments.Add(new CodeTypeReference(kType)); kType.Constraints.Add(iComparableT); CodeTypeParameter vType = new CodeTypeParameter("V"); vType.Constraints.Add(new CodeTypeReference("IList[System.String]")); class1.TypeParameters.Add(kType); class1.TypeParameters.Add(vType); ns.Types.Add(class1); // declare a generic method CodeMemberMethod method = new CodeMemberMethod(); CodeTypeParameter sType = new CodeTypeParameter("S"); sType.HasConstructorConstraint = true; CodeTypeParameter tType = new CodeTypeParameter("T"); sType.HasConstructorConstraint = true; method.Name = "Calculate"; method.TypeParameters.Add(sType); method.TypeParameters.Add(tType); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value1")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value2")); method.ReturnType = new CodeTypeReference(typeof(int)); method.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("value1"), CodeBinaryOperatorType.Multiply, new CodeVariableReferenceExpression("value2")))); method.Attributes = MemberAttributes.Public; class1.Members.Add(method); CodeTypeDeclaration class2 = new CodeTypeDeclaration(); class2.Name = "Test"; AddScenario("CheckMyMethod"); CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "MyMethod"; method2.Attributes = MemberAttributes.Public; method2.ReturnType = new CodeTypeReference(typeof(int)); method2.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "dReturn")); CodeTypeReference myClass = new CodeTypeReference("MyDictionary", new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List", new CodeTypeReference[] { new CodeTypeReference("System.String") }) }); method2.Statements.Add(new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass))); method2.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("dReturn"), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("dict"), "Calculate", new CodeTypeReference[] { new CodeTypeReference("System.Int32"), new CodeTypeReference("System.Int32"), }), new CodeExpression[] { new CodePrimitiveExpression(25), new CodePrimitiveExpression(11) }))); method2.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("dReturn"))); class2.Members.Add(method2); ns.Types.Add(class2); #endif }
//<Snippet1> 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; // Save the assembly as a physical file. cp.GenerateInMemory = false; // Generate debug information. cp.IncludeDebugInformation = true; // Add an assembly reference. cp.ReferencedAssemblies.Add("System.dll"); // Set the warning level at which // the compiler should abort compilation // if a warning of this level occurs. cp.WarningLevel = 3; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; if (provider.Supports(GeneratorSupport.EntryPointMethod)) { // Specify the class that contains // the main method of the executable. cp.MainClass = "DocumentSamples.DocumentProperties"; } // 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); } // Return the results of compilation. if (cr.Errors.Count > 0) { return(false); } else { return(true); } }
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(nameof(baseName)); } if (codeProvider == null) { throw new ArgumentNullException(nameof(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"). var errors = new List <string>(); // 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 <string, ResourceData> cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out Dictionary <string, string> 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. } var ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.Add("System.dll"); ccu.UserData.Add("AllowLateBound", false); ccu.UserData.Add("RequireVariableDeclaration", true); var ns = new CodeNamespace(generatedCodeNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ccu.Namespaces.Add(ns); // Generate class var 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)); var 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)); var debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib)); var compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)) { 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); EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic); // Now for each resource, add a property foreach (KeyValuePair <string, ResourceData> entry in cleanedResourceList) { String propertyName = entry.Key; // The resourceName will be the original value, before fixups, if any. if (reverseFixupTable.TryGetValue(propertyName, out string resourceName)) { resourceName = propertyName; } bool r = DefineResourceFetchingProperty(propertyName, resourceName, entry.Value, srClass, internalClass, useStatic); if (!r) { errors.Add(propertyName); } } unmatchable = errors.ToArray(); // Validate the generated class now CodeGenerator.ValidateIdentifiers(ccu); return(ccu); }
public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // #region Compile Unit Region // // namespace Namespace1 { // // // #region Outer Type Region // // Outer Type Comment // public class Class1 { // // // Field 1 Comment // private string field1; // // public void Method1() { // this.Event1(this, System.EventArgs.Empty); // } // // #region Constructor Region // public Class1() { // #region Statements Region // this.field1 = "value1"; // this.field2 = "value2"; // #endregion // } // #endregion // // public string Property1 { // get { // return this.field1; // } // } // // public static void Main() { // } // // public event System.EventHandler Event1; // // public class NestedClass1 { // } // // public delegate void nestedDelegate1(object sender, System.EventArgs e); // // // // #region Field Region // private string field2; // #endregion // // #region Method Region // // Method 2 Comment // // #line 500 "MethodLinePragma.txt" // public void Method2() { // this.Event2(this, System.EventArgs.Empty); // } // // #line default // #line hidden // #endregion // // public Class1(string value1, string value2) { // } // // #region Property Region // public string Property2 { // get { // return this.field2; // } // } // #endregion // // #region Type Constructor Region // static Class1() { // } // #endregion // // #region Event Region // public event System.EventHandler Event2; // #endregion // // #region Nested Type Region // // Nested Type Comment // // #line 400 "NestedTypeLinePragma.txt" // public class NestedClass2 { // } // // #line default // #line hidden // #endregion // // #region Delegate Region // public delegate void nestedDelegate2(object sender, System.EventArgs e); // #endregion // // #region Snippet Region // // #endregion // } // #endregion // } // #endregion CodeNamespace ns = new CodeNamespace("Namespace1"); cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region")); cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); cu.Namespaces.Add(ns); CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1"); ns.Types.Add(cd); cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region")); cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); cd.Comments.Add(new CodeCommentStatement("Outer Type Comment")); CodeMemberField field1 = new CodeMemberField(typeof(String), "field1"); CodeMemberField field2 = new CodeMemberField(typeof(String), "field2"); field1.Comments.Add(new CodeCommentStatement("Field 1 Comment")); field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region")); field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeMemberEvent evt1 = new CodeMemberEvent(); evt1.Name = "Event1"; evt1.Type = new CodeTypeReference(typeof(System.EventHandler)); evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeMemberEvent evt2 = new CodeMemberEvent(); evt2.Name = "Event2"; evt2.Type = new CodeTypeReference(typeof(System.EventHandler)); evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region")); evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.DeclareEvents)) { method1.Statements.Add( new CodeDelegateInvokeExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } CodeMemberMethod method2 = new CodeMemberMethod(); method2.Name = "Method2"; method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.DeclareEvents)) { method2.Statements.Add( new CodeDelegateInvokeExpression( new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"), new CodeExpression[] { new CodeThisReferenceExpression(), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty") })); } method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500); method2.Comments.Add(new CodeCommentStatement("Method 2 Comment")); method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region")); method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeMemberProperty property1 = new CodeMemberProperty(); property1.Name = "Property1"; property1.Type = new CodeTypeReference(typeof(string)); property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property1.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field1"))); CodeMemberProperty property2 = new CodeMemberProperty(); property2.Name = "Property2"; property2.Type = new CodeTypeReference(typeof(string)); property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; property2.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field2"))); property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region")); property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; CodeStatement conState1 = new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field1"), new CodePrimitiveExpression("value1")); conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region")); constructor1.Statements.Add(conState1); CodeStatement conState2 = new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field2"), new CodePrimitiveExpression("value2")); conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); constructor1.Statements.Add(conState2); constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region")); constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeConstructor constructor2 = new CodeConstructor(); constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1")); constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2")); CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor(); typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region")); typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1"); CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2"); nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400); nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment")); nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region")); nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeTypeDelegate delegate1 = new CodeTypeDelegate(); delegate1.Name = "nestedDelegate1"; delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender")); delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e")); CodeTypeDelegate delegate2 = new CodeTypeDelegate(); delegate2.Name = "nestedDelegate2"; delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender")); delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e")); delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region")); delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); CodeSnippetTypeMember snippet1 = new CodeSnippetTypeMember(); CodeSnippetTypeMember snippet2 = new CodeSnippetTypeMember(); CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, ""); regionStart.RegionText = "Snippet Region"; regionStart.RegionMode = CodeRegionMode.Start; snippet2.StartDirectives.Add(regionStart); snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty)); cd.Members.Add(field1); cd.Members.Add(method1); cd.Members.Add(constructor1); cd.Members.Add(property1); cd.Members.Add(methodMain); if (Supports(provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add(evt1); } if (Supports(provider, GeneratorSupport.NestedTypes)) { cd.Members.Add(nestedClass1); if (Supports(provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add(delegate1); } } cd.Members.Add(snippet1); cd.Members.Add(field2); cd.Members.Add(method2); cd.Members.Add(constructor2); cd.Members.Add(property2); if (Supports(provider, GeneratorSupport.StaticConstructors)) { cd.Members.Add(typeConstructor2); } if (Supports(provider, GeneratorSupport.DeclareEvents)) { cd.Members.Add(evt2); } if (Supports(provider, GeneratorSupport.NestedTypes)) { cd.Members.Add(nestedClass2); if (Supports(provider, GeneratorSupport.DeclareDelegates)) { cd.Members.Add(delegate2); } } cd.Members.Add(snippet2); } #endif }
// Create a CodeDOM graph. static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu) { //<Snippet8> if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) { // Return if the generator does not support generics. return; } //</Snippet8> CodeNamespace ns = new CodeNamespace("DemoNamespace"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); cu.Namespaces.Add(ns); // Declare a generic class. CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), })); //<Snippet2> //<Snippet10> CodeTypeParameter kType = new CodeTypeParameter("TKey"); //</Snippet2> //<Snippet3> kType.HasConstructorConstraint = true; //</Snippet3> //<Snippet4> kType.Constraints.Add(new CodeTypeReference(typeof(IComparable))); //</Snippet4> //<Snippet5> kType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType")))); //</Snippet5> CodeTypeReference iComparableT = new CodeTypeReference("IComparable"); iComparableT.TypeArguments.Add(new CodeTypeReference(kType)); kType.Constraints.Add(iComparableT); CodeTypeParameter vType = new CodeTypeParameter("TValue"); vType.Constraints.Add(new CodeTypeReference(typeof(IList <System.String>))); vType.CustomAttributes.Add(new CodeAttributeDeclaration( "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("ValueType")))); class1.TypeParameters.Add(kType); class1.TypeParameters.Add(vType); //</Snippet10> ns.Types.Add(class1); //<Snippet6> // Declare a generic method. CodeMemberMethod printMethod = new CodeMemberMethod(); CodeTypeParameter sType = new CodeTypeParameter("S"); sType.HasConstructorConstraint = true; CodeTypeParameter tType = new CodeTypeParameter("T"); sType.HasConstructorConstraint = true; printMethod.Name = "Print"; printMethod.TypeParameters.Add(sType); printMethod.TypeParameters.Add(tType); //</Snippet6> //<Snippet7> printMethod.Statements.Add(ConsoleWriteLineStatement( new CodeDefaultValueExpression(new CodeTypeReference("T")))); printMethod.Statements.Add(ConsoleWriteLineStatement( new CodeDefaultValueExpression(new CodeTypeReference("S")))); //</Snippet7> printMethod.Attributes = MemberAttributes.Public; class1.Members.Add(printMethod); CodeTypeDeclaration class2 = new CodeTypeDeclaration(); class2.Name = "Demo"; CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); CodeTypeReference myClass = new CodeTypeReference( "MyDictionary", new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List", new CodeTypeReference[] { new CodeTypeReference("System.String") }) }); methodMain.Statements.Add( new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass))); methodMain.Statements.Add(ConsoleWriteLineStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("dict"), "Count"))); //<Snippet9> methodMain.Statements.Add(new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("dict"), "Print", new CodeTypeReference[] { new CodeTypeReference("System.Decimal"), new CodeTypeReference("System.Int32"), }), new CodeExpression[0]))); //</Snippet9> string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary <int, System.Collections.Generic.List <string> >[]).FullName; CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName); methodMain.Statements.Add( new CodeVariableDeclarationStatement(dictionaryType, "dict2", new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) }))); methodMain.Statements.Add(ConsoleWriteLineStatement( new CodePropertyReferenceExpression( new CodeVariableReferenceExpression("dict2"), "Length"))); class2.Members.Add(methodMain); ns.Types.Add(class2); }
public bool Supports(GeneratorSupport supports) { return(provider.Supports(supports)); }