public void AddEntryPoint() { CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeObjectCreateExpression objectCreate = new CodeObjectCreateExpression( new CodeTypeReference("CodeDOMCreatedClass"), new CodePrimitiveExpression(5.3), new CodePrimitiveExpression(6.9)); // Add the statement: // "CodeDOMCreatedClass testClass = // new CodeDOMCreatedClass(5.3, 6.9);" start.Statements.Add(new CodeVariableDeclarationStatement( new CodeTypeReference("CodeDOMCreatedClass"), "testClass", objectCreate)); // Creat the expression: // "testClass.ToString()" CodeMethodInvokeExpression toStringInvoke = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("testClass"), "ToString"); // Add a System.Console.WriteLine statement with the previous // expression as a parameter. start.Statements.Add(new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", toStringInvoke)); targetClass.Members.Add(start); }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression csl = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WritLine", new CodePrimitiveExpression("Hello World")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(csl); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("HellowWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); tw.Close(); } }
public void ReadAndGenerateCodeForMobs() { var unit = new CodeCompileUnit(); var ns = new CodeNamespace("MiNET.Generated"); unit.Namespaces.Add(ns); ns.Comments.Add(new CodeCommentStatement("Test")); var aClass = new CodeTypeDeclaration("MyClass"); aClass.Members.Add(new CodeConstructor()); var method = new CodeMemberMethod() { Name = "Test" }; aClass.Members.Add(method); var start = new CodeEntryPointMethod(); var cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); start.Statements.Add(cs1); aClass.Members.Add(start); ns.Types.Add(aClass); GenerateCSharpCode(unit); }
private bool HandleDynamic(CodeEntryPointMethod obj, Context ctx) { return(HandleIfTrue(() => { HandleMain(obj, ctx); }, obj, ctx, CanHandleEntryPoint, MemberTypes.Method)); }
// Build a Hello World program graph using System.CodeDom types. public static CodeCompileUnit BuildHelloWorldGraph(string message) { CodeCompileUnit compileUnit = new CodeCompileUnit(); // Create a new CodeCompileUnit to contain the program graph. CodeNamespace samples = new CodeNamespace("Samples"); // Declare a new namespace called Samples. compileUnit.Namespaces.Add(samples); // Add the new namespace to the compile unit. samples.Imports.Add(new CodeNamespaceImport("System")); // Add the new namespace import for the System namespace. CodeTypeDeclaration class1 = new CodeTypeDeclaration("Program"); // Declare a new type called Class1. samples.Types.Add(class1); // Add the new type to the namespace type collection. CodeEntryPointMethod start = new CodeEntryPointMethod(); // Declare a new code entry point method. CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console"); // Create a type reference for the System.Console class. CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( // Build a Console.WriteLine statement. csSystemConsoleType, "WriteLine", new CodePrimitiveExpression(message)); start.Statements.Add(cs1); // Add the WriteLine call to the statement collection. CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression( // Build another Console.WriteLine statement. csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Press the Enter key to continue.")); start.Statements.Add(cs2); // Add the WriteLine call to the statement collection. CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression( // Build a call to System.Console.ReadLine. csSystemConsoleType, "ReadLine"); start.Statements.Add(csReadLine); // Add the ReadLine statement. class1.Members.Add(start); // Add the code entry point method to the Members collection of the type. return(compileUnit); }
public static void ExampleHelloWorld() { /* * NOT COMPATIBE WITH .NET CORE AT THE MOMENT */ CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); //Write to source CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } }
private static CodeEntryPointMethod BuildMainMethod() { var method = new CodeEntryPointMethod(); // Create a type reference for the System.Console class. var csSystemConsoleType = new CodeTypeReferenceExpression("System.Console"); // Add Console.WriteLine statement method.Statements.Add( new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Hello World!"))); // Add another Console.WriteLine statement method.Statements.Add( new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Press the Enter key to exit."))); // Add the ReadLine statement. method.Statements.Add( new CodeMethodInvokeExpression( csSystemConsoleType, "ReadLine")); return(method); }
protected string GenerateEntryPointMethod(CodeGeneratorOptions options) { TypeDeclaration.Name = "Test1"; CodeEntryPointMethod method = new CodeEntryPointMethod(); method.Name = "Something"; // should be ignored in C# and VB method.Attributes = MemberAttributes.Private; // should be ignored in C# and VB method.ReturnType = new CodeTypeReference(typeof(int)); // should be ignored in C# 1.x and VB 1.x and 2.x // parameters on entry point are ignored in C# and VB CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression( typeof(object), "value1"); method.Parameters.Add(param); // custom attributes on entry point are ignored in C# 1.x and VB 1.x CodeAttributeDeclaration attrDec = new CodeAttributeDeclaration(); attrDec.Name = "A"; method.CustomAttributes.Add(attrDec); CodeVariableDeclarationStatement v = new CodeVariableDeclarationStatement("Test+InnerType", "x"); method.Statements.Add(v); TypeDeclaration.Members.Add(method); /* * CodeTypeDeclaration nestedType = new CodeTypeDeclaration ("InnerType"); * TypeDeclaration.Members.Add (nestedType); */ return(GenerateCodeFromType(TypeDeclaration, options)); }
/// <summary> /// 创建Main方法 /// </summary> public void CreateEntryPoint() { // 创建一个对象并将其命名为Main (Entry Point, 入口点) var main = new CodeEntryPointMethod { Name = "Main", Attributes = MemberAttributes.Public | MemberAttributes.Static, }; // 定义Main方法 // 创建我们声明的类的一个对象, 并调用其方法 var exp1 = new CodeSnippetExpression("MyClass cls = new MyClass()"); var exp2 = new CodeSnippetExpression("cls.Message = \"Hello World\""); var exp3 = new CodeSnippetExpression("Console.WriteLine(cls.Message)"); var exp4 = new CodeSnippetExpression("Console.WriteLine(\"Answer: {0}\", cls.AddNumbers(10, 20))"); var exp5 = new CodeSnippetExpression("Console.ReadLine()"); //Create expression statements for the snippets var ces1 = new CodeExpressionStatement(exp1); var ces2 = new CodeExpressionStatement(exp2); var ces3 = new CodeExpressionStatement(exp3); var ces4 = new CodeExpressionStatement(exp4); var ces5 = new CodeExpressionStatement(exp5); //Add the expression statements to the main method. main.Statements.Add(ces1); main.Statements.Add(ces2); main.Statements.Add(ces3); main.Statements.Add(ces4); main.Statements.Add(ces5); //Add the main method to the class _myClass.Members.Add(main); }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders."); Console.Write("Press a key to exit"); Console.ReadKey(); }
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))); } }
private void button1_Click(object sender, EventArgs e) { var unit = new CodeCompileUnit(); var dynamucNamespace = new CodeNamespace("FourthCoffee.Dynamic"); unit.Namespaces.Add(dynamucNamespace); dynamucNamespace.Imports.Add(new CodeNamespaceImport("System")); var programType = new CodeTypeDeclaration("Program"); dynamucNamespace.Types.Add(programType); var mainMethod = new CodeEntryPointMethod(); programType.Members.Add(mainMethod); var expression = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello Development Team!!!")); mainMethod.Statements.Add(expression); var provider = new CSharpCodeProvider(); var filename = "program.cs"; var stream = new StreamWriter(filename); var textWriter = new IndentedTextWriter(stream); var options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; // var compileUnit = FourthCoffee.GetModel(); provider.GenerateCodeFromCompileUnit(unit, textWriter, options); textWriter.Close(); stream.Close(); }
static void _Patch(CodeMemberMethod meth, CodeDomVisitContext ctx, CodeDomResolver resolver) { if (null != meth) { // TODO: Populate public implementation types meth.UserData.Remove("slang:unresolved"); if ("Main" == meth.Name && (meth.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Static) { if (0 == meth.Parameters.Count && null == meth.ReturnType || "System.Void" == meth.ReturnType.BaseType) { var epm = new CodeEntryPointMethod(); epm.Attributes = meth.Attributes; epm.LinePragma = meth.LinePragma; epm.StartDirectives.AddRange(meth.StartDirectives); epm.EndDirectives.AddRange(meth.EndDirectives); epm.Comments.AddRange(meth.Comments); epm.CustomAttributes.AddRange(meth.CustomAttributes); epm.ReturnTypeCustomAttributes.AddRange(meth.ReturnTypeCustomAttributes); epm.TypeParameters.AddRange(meth.TypeParameters); epm.PrivateImplementationType = meth.PrivateImplementationType; epm.ImplementationTypes.AddRange(meth.ImplementationTypes); epm.Name = meth.Name; epm.Statements.AddRange(meth.Statements); CodeDomVisitor.ReplaceTarget(ctx, epm); } } //return; } }
public static CodeEntryPointMethod EntryPointMethod( CodeTypeReference returnType, string name, MemberAttributes attributes, CodeParameterDeclarationExpression[] parameters, CodeStatement[] statements, CodeTypeReference[] implementationTypes, CodeTypeReference privateImplementationType, CodeCommentStatement[] comments, CodeAttributeDeclaration[] customAttributes, CodeAttributeDeclaration[] returnTypeCustomAttributes, CodeDirective[] startDirectives, CodeDirective[] endDirectives, CodeLinePragma linePragma) { var result = new CodeEntryPointMethod(); result.ReturnType = returnType; result.Name = name; result.Attributes = attributes; result.Parameters.AddRange(parameters); result.Statements.AddRange(statements); result.ImplementationTypes.AddRange(implementationTypes); result.PrivateImplementationType = privateImplementationType; result.Comments.AddRange(comments); result.CustomAttributes.AddRange(customAttributes); result.ReturnTypeCustomAttributes.AddRange(returnTypeCustomAttributes); result.StartDirectives.AddRange(startDirectives); result.EndDirectives.AddRange(endDirectives); result.LinePragma = linePragma; return(result); }
public void CreateAHelloWorld() { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace("XNamespace"); codeNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myclass = new CodeTypeDeclaration("myClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); compileUnit.Namespaces.Add(codeNamespace); codeNamespace.Types.Add(myclass); myclass.Members.Add(start); start.Statements.Add(cs1); //create a source file CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("helloworld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // namespace Namespace1 { // // public class TEST { // // public static void Main() { // // the following is repeated Char.MaxValue times // System.Console.WriteLine(/* character value goes here */); // } // } // } CodeNamespace ns = new CodeNamespace ("Namespace1"); ns.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; ns.Types.Add (cd); CodeEntryPointMethod methodMain = new CodeEntryPointMethod (); for (int i = 0; i < Char.MaxValue; i+=50) methodMain.Statements.Add (CDHelper.ConsoleWriteLineStatement (new CodePrimitiveExpression (System.Convert.ToChar (i)))); cd.Members.Add (methodMain); } }
/// <summary> /// 描述所生成源代码的结构信息,例如函数定义 /// </summary> /// <returns></returns> public CodeNamespace CreateCodeDomHelloDemo() { CodeMemberMethod method = new CodeMemberMethod(); //方法声明; method.Name = "SayHello"; // 方法名 method.Attributes = MemberAttributes.Public | MemberAttributes.Final; //属性 method.ReturnType = new CodeTypeReference(typeof(string)); //返回类型 method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello from code!"))); //方法体,只有一句返回语句return "Hello from code!"; CodeEntryPointMethod main = new CodeEntryPointMethod(); //主方法Main main.Statements.Add(new CodeVariableDeclarationStatement("HelloWord", "hw", new CodeObjectCreateExpression("HelloWord", new CodeExpression[] { })));//变量声明:HelloWord hw = new HelloWord(); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("hw"), "SayHello", new CodeExpression[] {}); main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", methodinvoke)); main.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "Read")); //两个方法调用:System.Console.WriteLine(hw.SayHello()); CodeTypeDeclaration helloword = new CodeTypeDeclaration("HelloWord"); //类型Class声明 helloword.Attributes = MemberAttributes.Public; helloword.Members.AddRange(new CodeTypeMember[] { method, main }); //添加方法到clss CodeNamespace nspace = new CodeNamespace("HelloDemo1"); //命名空间声明 nspace.Imports.Add(new CodeNamespaceImport("System")); //引入程序命名空间:using System; nspace.Types.Add(helloword); // return(nspace); }
public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) { if (!(provider is JScriptCodeProvider)) { // GENERATES (C#): // // namespace Namespace1 { // // public class TEST { // // public static void Main() { // // the following is repeated Char.MaxValue times // System.Console.WriteLine(/* character value goes here */); // } // } // } CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); cu.Namespaces.Add(ns); CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; ns.Types.Add(cd); CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); for (int i = 0; i < Char.MaxValue; i += 50) { methodMain.Statements.Add(CDHelper.ConsoleWriteLineStatement(new CodePrimitiveExpression(System.Convert.ToChar(i)))); } cd.Members.Add(methodMain); } }
public CodeCompileUnit CodeDomHelloDemo() { //Mehtod CodeEntryPointMethod method = new CodeEntryPointMethod(); //Console.WriteLine("Hello Word!"); CodeMethodInvokeExpression methodWrite = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Console)), "WriteLine", new CodePrimitiveExpression("Hello Word!")); //Console.Read(); CodeMethodInvokeExpression methodread = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression(typeof(Console)), "Read"); method.Statements.Add(methodWrite); method.Statements.Add(methodread); //class Hello CodeTypeDeclaration hello = new CodeTypeDeclaration("Hello"); hello.Attributes = MemberAttributes.Public; hello.Members.Add(method); //namespace Demo5 CodeNamespace nspace = new CodeNamespace("Demo5"); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Types.Add(hello); //CodeCompileUnit CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nspace); return(unit); }
public static void Test_Using_CodeDOM() { CodeCompileUnit compileUnit = new CodeCompileUnit(); // file CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); // namespace myNamespace.Imports.Add(new CodeNamespaceImport("System")); // using System; CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); // class CodeEntryPointMethod start = new CodeEntryPointMethod(); // main method CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( // method new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression( // method new CodeTypeReferenceExpression("Console"), "ReadLine"); compileUnit.Namespaces.Add(myNamespace); // add namespace to file myNamespace.Types.Add(myClass); // add class to namespace myClass.Members.Add(start); // add main function to myClass start.Statements.Add(cs1); // add cs1 and cs2 to main method start.Statements.Add(cs2); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) // the output file path is: C:\Visual_Studio_Project\DotNet_Projects\ExamRef_70_483_Chapter1\ExamRef_70_483_Chapter2\bin\Debug { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); tw.Close(); } }
public void AddEntryPoint(Gramatica gramatica) { CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeSnippetExpression methodValue = new CodeSnippetExpression(); methodValue.Value += "stringIndex = 0;\n" + $" inputArrayString = Console.ReadLine().Split(\' \'); \n" + "try \n" + "{\n" + $"\t { gramatica.Start } (); \n" + "if( inputArrayString[stringIndex] == \"$\" ) \n" + "\tConsole.WriteLine(\"Propozitie corecta\");\n" + "else\n" + "Console.WriteLine(\"Propozitie Incorecta\");\n" + "}\n" + "catch(Exception e)\n" + "{\n" + "Console.WriteLine(e.Message);\n" + "Console.WriteLine(\"Propozitie Incorecta\");\n" + "}\n" + "Console.ReadKey();\n" ; start.Statements.Add(new CodeSnippetStatement(methodValue.Value)); targetClass.Members.Add(start); }
protected override void GenerateEntryPointMethod( CodeEntryPointMethod method, CodeTypeDeclaration declaration) { method.Name = "__Main__"; GenerateMethod(method, declaration); }
private static CodeCompileUnit createCompileUnit(string className, string message) { //Create a namespace for our code to live in CodeNamespace demoNamespace = new CodeNamespace("Demos.CodeDOM"); //Add a class to our namespace CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(className); demoNamespace.Types.Add(classDeclaration); //Declare a main method CodeEntryPointMethod mainMethod = new CodeEntryPointMethod(); CodeTypeReferenceExpression codeRef = new CodeTypeReferenceExpression("System.Console"); CodeMethodInvokeExpression line1 = new CodeMethodInvokeExpression(codeRef, "WriteLine", new CodePrimitiveExpression(message)); mainMethod.Statements.Add(new CodeExpressionStatement(line1)); //Add the main method to the class classDeclaration.Members.Add(mainMethod); //Create the object graph CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(demoNamespace); return(compileUnit); }
static void Main(string[] args) { var unit = new CodeCompileUnit(); var dynamicNamespace = new CodeNamespace("PhilsAutogeneratedCode"); unit.Namespaces.Add(dynamicNamespace); dynamicNamespace.Imports.Add(new CodeNamespaceImport("System")); var programType = new CodeTypeDeclaration("Program"); dynamicNamespace.Types.Add(programType); var mainMethod = new CodeEntryPointMethod(); programType.Members.Add(mainMethod); var prop = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"), "Now"); var expression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("The time is {0}"), prop); mainMethod.Statements.Add(expression); expression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "ReadLine"); mainMethod.Statements.Add(expression); var csProvider = new CSharpCodeProvider(); var csFileName = "program.cs"; var options = new CodeGeneratorOptions(); // options.BlankLinesBetweenMembers = true; using (var stream = new StreamWriter(csFileName)) { using (var textWriter = new IndentedTextWriter(stream)) { csProvider.GenerateCodeFromCompileUnit(unit, textWriter, options); } } var compilerSettings = new CompilerParameters(); compilerSettings.ReferencedAssemblies.Add("System.dll"); compilerSettings.GenerateExecutable = true; compilerSettings.OutputAssembly = "CodeDOM_02_output.exe"; var compilationResults = csProvider.CompileAssemblyFromFile(compilerSettings, csFileName); foreach (var error in compilationResults.Errors) { var errorMessage = error.ToString(); } Console.WriteLine("The system has generated an exe file."); Console.WriteLine("After 3 seconds it is going to execute"); System.Threading.Thread.Sleep(3000); System.Diagnostics.Process.Start(@"CodeDOM_02_output.exe"); }
protected override void GenerateEntryPointMethod (CodeEntryPointMethod e, CodeTypeDeclaration c) { Output.Write("public static void Main()"); StartBlock(); GenerateStatements(e.Statements); EndBlock(); }
public CodeEntryPointMethod declEntry() { statStack.Clear(); CodeEntryPointMethod method = new CodeEntryPointMethod(); statPush(method.Statements); AddMember(method); return(method); }
static void Main(string[] args) { CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); start.Statements.Add(cs1); }
protected override void GenerateEntryPointMethod (CodeEntryPointMethod e, CodeTypeDeclaration c) { Output.WriteLine("Public Shared Sub Main()"); ++Indent; GenerateStatements(e.Statements); --Indent; Output.WriteLine("End Sub"); }
//生产代码一种方式 public static CodeCompileUnit BuildHelloWorldGraph() { // 新建一个 CodeCompileUnit 来包含程序图纸 CodeCompileUnit compileUnit = new CodeCompileUnit(); // 声明一个名称为 Samples 的新命名空间 CodeNamespace samples = new CodeNamespace("Samples"); // 把新命名空间添加到程序编译单元中 compileUnit.Namespaces.Add(samples); // 添加新的命名空间(System 命名空间)的引用 samples.Imports.Add(new CodeNamespaceImport("System")); // 定义一个新类,取名为 Class1 CodeTypeDeclaration TestComipleUnit = new CodeTypeDeclaration(dllorexeName); // 把 Class1 添加到 Samples 命名空间中 samples.Types.Add(TestComipleUnit); // 定义新的代码入口点(Main 方法) CodeEntryPointMethod start = new CodeEntryPointMethod(); // 为 System.Console 类创建一个类型引用 CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console"); // 构建一个 Console.WriteLine 方法的声明 CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("hello world") ); //将 system.console.writeline("hello world")添加到Main方法中 start.Statements.Add(cs1); CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Press the Enter key to continue") ); start.Statements.Add(cs2); // 构建 Console.ReadLine 方法的声明 CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression( csSystemConsoleType, "ReadLine"); // 把 ReadLine 方法添加到 Main 方法中 start.Statements.Add(csReadLine); // 把 Main 方法添加 Class1 类中 TestComipleUnit.Members.Add(start); return(compileUnit); }
/// <inheritdoc/> protected override void HandleMain(CodeEntryPointMethod obj, Context ctx) { ctx.HandlerProvider.MemberAttributesHandler.Handle( GeneralUtils.GetMaskedMemberAttributes(obj.Attributes, true, false, false, true), ctx); ctx.Writer.Write("static "); //TODO async main ctx.HandlerProvider.TypeReferenceHandler.Handle(obj.ReturnType, ctx); ctx.Writer.Write(" Main(string[] args)"); HandleMethodStatements(obj, ctx); }
// Build a Hello World program graph using System.CodeDom types. // For simplicity, this method builds a fixed code compile unit. // In most scenarios, this method would use the virtual path, // and build a code compile unit from the parsed file. public static CodeCompileUnit BuildCompileUnitFromPath(string virtualPath) { // Create a new CodeCompileUnit to contain the program graph CodeCompileUnit compileUnit = new CodeCompileUnit(); // Declare the HelloWorldSample namespace. CodeNamespace helloNamespace = new CodeNamespace(genNamespace); // Add the new namespace to the compile unit. compileUnit.Namespaces.Add(helloNamespace); // Add the new namespace import for the System namespace. helloNamespace.Imports.Add(new CodeNamespaceImport("System")); // Declare a class named HelloWorldClass. CodeTypeDeclaration helloClass = new CodeTypeDeclaration(genClassName); // Add the HelloWorldClass to the namespace. helloNamespace.Types.Add(helloClass); // Declare the Main method of the class. CodeEntryPointMethod helloMain = new CodeEntryPointMethod(); // Add the code entry point method to the Members // collection of the type. helloClass.Members.Add(helloMain); // Create a type reference for the System.Console class. CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console"); // Build Console.WriteLine("Hello World!"). CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Hello World!")); // Add the WriteLine call to the statement collection. helloMain.Statements.Add(cs1); // Build another Console.WriteLine statement. CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression( csSystemConsoleType, "WriteLine", new CodePrimitiveExpression("Press the Enter key to continue.")); // Add the new code statement. helloMain.Statements.Add(cs2); // Build a call to Console.ReadLine. CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression( csSystemConsoleType, "ReadLine"); // Add the new code statement. helloMain.Statements.Add(csReadLine); return(compileUnit); }
public void Compilation_NotSupported() { CodeDomProvider provider = GetProvider(); var options = new CompilerParameters(new string[] { }, "test.exe"); var cu = new CodeCompileUnit(); var ns = new CodeNamespace("ns"); var cd = new CodeTypeDeclaration("Program"); var mm = new CodeEntryPointMethod(); cd.Members.Add(mm); ns.Types.Add(cd); cu.Namespaces.Add(ns); string tempPath = Path.GetTempFileName(); try { File.WriteAllText(tempPath, GetEmptyProgramSource()); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromFile(options, tempPath)); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromDom(options, cu)); Assert.Throws<PlatformNotSupportedException>(() => provider.CompileAssemblyFromSource(options, GetEmptyProgramSource())); #pragma warning disable 0618 // obsolete ICodeCompiler cc = provider.CreateCompiler(); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDom(options, cu)); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromDomBatch(options, new[] { cu })); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFile(options, tempPath)); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromFileBatch(options, new[] { tempPath })); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSource(options, GetEmptyProgramSource())); Assert.Throws<PlatformNotSupportedException>(() => cc.CompileAssemblyFromSourceBatch(options, new[] { GetEmptyProgramSource() })); #pragma warning restore 0618 } finally { File.Delete(tempPath); } }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // GENERATES (C#): // [assembly: System.Reflection.AssemblyTitle("MyAssembly")] // [assembly: System.Reflection.AssemblyVersion("1.0.6.2")] // [assembly: System.CLSCompliantAttribute(false)] // // namespace MyNamespace { // using System; // using System.Drawing; // using System.Windows.Forms; // using System.ComponentModel; // CodeNamespace ns = new CodeNamespace (); ns.Name = "MyNamespace"; ns.Imports.Add (new CodeNamespaceImport ("System")); ns.Imports.Add (new CodeNamespaceImport ("System.Drawing")); ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms")); ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cu.Namespaces.Add (ns); cu.ReferencedAssemblies.Add ("System.Xml.dll"); cu.ReferencedAssemblies.Add ("System.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); // Assembly Attributes if (Supports (provider, GeneratorSupport.AssemblyAttributes)) { AddScenario ("CheckAssemblyAttributes", "Check that assembly attributes get generated properly."); CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes; attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly")))); attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2")))); attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false)))); } // GENERATES (C#): // [System.Serializable()] // [System.Obsolete("Don\'t use this Class")] // [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")] // public class MyClass { // #if !WHIDBEY // Everett versions of C# and VB code providers will never have these generated properly if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly."); #else AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly."); #endif CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "MyClass"; class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable")); class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Class")))); class1.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName, new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID")))); ns.Types.Add (class1); // GENERATES (C#): // [System.Serializable()] // public class NestedClass { // } if (Supports (provider, GeneratorSupport.NestedTypes)) { #if !WHIDBEY // Everett versions of C# and VB code providers will never have these generated properly if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly."); #else AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly."); #endif CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("NestedClass"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; nestedClass.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable")); class1.Members.Add (nestedClass); } // GENERATES (C#): // [System.Obsolete("Don\'t use this Method")] // [System.ComponentModel.Editor("This", "That")] // public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] int[] arrayit) { // } AddScenario ("CheckMyMethodAttributes", "Check that attributes are generated properly on MyMethod()."); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; method1.Name = "MyMethod"; method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Method")))); method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.ComponentModel.Editor", new CodeAttributeArgument (new CodePrimitiveExpression ("This")), new CodeAttributeArgument (new CodePrimitiveExpression ("That")))); CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah"); if (Supports (provider, GeneratorSupport.ParameterAttributes)) { AddScenario ("CheckParameterAttributes", "Check that parameter attributes are generated properly."); param1.CustomAttributes.Add ( new CodeAttributeDeclaration ( "System.Xml.Serialization.XmlElement", new CodeAttributeArgument ( "Form", new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument ( "IsNullable", new CodePrimitiveExpression (false)))); } method1.Parameters.Add (param1); CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit"); if (Supports (provider, GeneratorSupport.ParameterAttributes)) { param2.CustomAttributes.Add ( new CodeAttributeDeclaration ( "System.Xml.Serialization.XmlElement", new CodeAttributeArgument ( "Form", new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument ( "IsNullable", new CodePrimitiveExpression (false)))); } //param2.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArray")); method1.Parameters.Add (param2); class1.Members.Add (method1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Function")] // [return: System.Xml.Serialization.XmlIgnoreAttribute()] // [return: System.Xml.Serialization.XmlRootAttribute(Namespace="Namespace Value", ElementName="Root, hehehe")] // public string MyFunction() { // return "Return"; // } // if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) { AddScenario ("CheckMyFunctionAttributes", "Check return type attributes."); CodeMemberMethod function1 = new CodeMemberMethod (); function1.Attributes = MemberAttributes.Public; function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference (typeof (string)); function1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Function")))); function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument ("Namespace", new CodePrimitiveExpression ("Namespace Value")), new CodeAttributeArgument ("ElementName", new CodePrimitiveExpression ("Root, hehehe")))); function1.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("Return"))); class1.Members.Add (function1); } // GENERATES (C#): // [System.Xml.Serialization.XmlElementAttribute()] // private string myField = "hi!"; // AddScenario ("CheckMyFieldAttributes", "Check that attributes are generated properly on MyField."); CodeMemberField field1 = new CodeMemberField (); field1.Name = "myField"; field1.Attributes = MemberAttributes.Public; field1.Type = new CodeTypeReference (typeof (string)); field1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlElementAttribute")); field1.InitExpression = new CodePrimitiveExpression ("hi!"); class1.Members.Add (field1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Property")] // public string MyProperty { // get { // return this.myField; // } // } AddScenario ("CheckMyPropertyAttributes", "Check that attributes are generated properly on MyProperty."); CodeMemberProperty prop1 = new CodeMemberProperty (); prop1.Attributes = MemberAttributes.Public; prop1.Name = "MyProperty"; prop1.Type = new CodeTypeReference (typeof (string)); prop1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Property")))); prop1.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "myField"))); class1.Members.Add (prop1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Constructor")] // public MyClass() { // } if (!(provider is JScriptCodeProvider)) AddScenario ("CheckConstructorAttributes", "Check that attributes are generated properly on the constructor."); CodeConstructor const1 = new CodeConstructor (); const1.Attributes = MemberAttributes.Public; const1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor")))); class1.Members.Add (const1); // GENERATES (C#): // [System.Obsolete("Don\'t use this Constructor")] // static MyClass() { // } if (Supports (provider, GeneratorSupport.StaticConstructors)) { // C#, VB and JScript code providers don't generate this properly. This will // be fixed in Beta2 (with the exception of JScript code provider. JScript doesn't // support static constructor custom attributes) //if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) { AddScenario ("CheckStaticConstructorAttributes", "Check that attributes are generated properly on type constructors."); //} CodeTypeConstructor typecons = new CodeTypeConstructor (); typecons.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor")))); class1.Members.Add (typecons); } // GENERATES (C#): // [System.Obsolete ("Don\'t use this entry point")] // public static void Main () { // } if (Supports (provider, GeneratorSupport.EntryPointMethod)) { // C#, VB and JScript code providers don't generate this properly. This will // be fixed in Beta2 (with the exception of JScript code provider. JScript doesn't // support static constructor custom attributes) ///if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) { AddScenario ("CheckEntryPointMethodAttributes", "Check that attributes are generated properly on entry point methods."); //} CodeEntryPointMethod entpoint = new CodeEntryPointMethod (); entpoint.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this entry point")))); class1.Members.Add (entpoint); } if (Supports (provider, GeneratorSupport.DeclareDelegates)) { AddScenario ("CheckDelegateAttributes"); CodeTypeDelegate del = new CodeTypeDelegate ("MyDelegate"); del.TypeAttributes = TypeAttributes.Public; del.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this delegate")))); ns.Types.Add (del); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { // GENERATES (C#): // public class Test : Form { // // private Button b = new Button(); // // AddScenario ("CheckEventAttributes", "test attributes on an event"); class1 = new CodeTypeDeclaration ("Test"); class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("Form")); ns.Types.Add (class1); CodeMemberField mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button")); class1.Members.Add (mfield); // GENERATES (C#): // public Test() { // this.Size = new Size(600, 600); // b.Text = "Test"; // b.TabIndex = 0; // b.Location = new Point(400, 525); // this.MyEvent += new EventHandler(this.b_Click); // } // CodeConstructor ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "Size"), new CodeObjectCreateExpression (new CodeTypeReference ("Size"), new CodePrimitiveExpression (600), new CodePrimitiveExpression (600)))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Text"), new CodePrimitiveExpression ("Test"))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "TabIndex"), new CodePrimitiveExpression (0))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Location"), new CodeObjectCreateExpression (new CodeTypeReference ("Point"), new CodePrimitiveExpression (400), new CodePrimitiveExpression (525)))); ctor.Statements.Add (new CodeAttachEventStatement (new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler") , new CodeThisReferenceExpression (), "b_Click"))); class1.Members.Add (ctor); // GENERATES (C#): // [System.CLSCompliantAttribute(false)] // public event System.EventHandler MyEvent; CodeMemberEvent evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Public; evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false)))); class1.Members.Add (evt); // GENERATES (C#): // private void b_Click(object sender, System.EventArgs e) { // } // } // } // CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "b_Click"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e")); class1.Members.Add (cmm); } }
public void Visit(CodeEntryPointMethod o) { g.GenerateEntryPointMethod(o, g.CurrentClass); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { #if WHIDBEY CodeNamespace ns = new CodeNamespace("Namespace1"); cu.Namespaces.Add(ns); CodeTypeDeclaration cd = new CodeTypeDeclaration ("Class1"); ns.Types.Add(cd); cd.Comments.Add(new CodeCommentStatement("Outer Type Comment")); CodeMemberField field1 = new CodeMemberField(typeof(String), "field1"); CodeMemberField field2 = new CodeMemberField(typeof(String), "field2"); field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Foo")); field2.EndDirectives.Add(new CodeRegionDirective (CodeRegionMode.End, String.Empty)); field1.Comments.Add(new CodeCommentStatement("Field 1 Comment")); 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; CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "Method1"; method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; if (Supports(provider, 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 (Supports(provider, 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")); 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"))); CodeConstructor constructor1 = new CodeConstructor(); constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; constructor1.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field1"), new CodePrimitiveExpression("value1"))); constructor1.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), "field2"), new CodePrimitiveExpression("value2"))); 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(); 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")); 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")); cd.Members.Add(field1); cd.Members.Add(method1); cd.Members.Add(constructor1); cd.Members.Add(property1); if (Supports (provider, GeneratorSupport.EntryPointMethod)) 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(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); } } #endif }
protected abstract void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c);
public void ProviderSupports() { CodeDomProvider provider = GetProvider(); CodeCompileUnit cu = new CodeCompileUnit(); CodeNamespace nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("System.Drawing")); nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; nspace.Types.Add(cd); // Arrays of Arrays CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.ArraysOfArrays)) { cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])), "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]), new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)), new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) })))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0)) , new CodePrimitiveExpression(1)))); } else { throw new Exception("not supported"); } cd.Members.Add(cmm); // assembly attributes if (provider.Supports(GeneratorSupport.AssemblyAttributes)) { CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes; attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly")))); attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration(); if (provider.Supports(GeneratorSupport.ChainedConstructorArguments)) { class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(String)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeConstructor cctor = new CodeConstructor(); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString")); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); class1.Members.Add(cctor); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3")); cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression() , "stringField"), new CodeVariableReferenceExpression("p1"))); class1.Members.Add(cc); // verify chained constructors work cmm = new CodeMemberMethod(); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(String)); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "accessStringField"))); cd.Members.Add(cmm); } // complex expressions if (provider.Supports(GeneratorSupport.ComplexExpressions)) { cmm = new CodeMemberMethod(); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(3))))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEnums)) { CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add(ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString()); Field.InitExpression = new CodePrimitiveExpression(k); ce.Members.Add(Field); } cmm = new CodeMemberMethod(); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement( new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareInterfaces)) { cmm = new CodeMemberMethod(); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke)); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("InterfaceA"); class1.IsInterface = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); class1.Members.Add(cmm); if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers)) { CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add(classDecl); cmm = new CodeMemberMethod(); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); classDecl.Members.Add(cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp"); class2.BaseTypes.Add(new CodeTypeReference("System.Object")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceB")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class2.IsClass = true; nspace.Types.Add(class2); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class2.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp"))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA", new CodeVariableReferenceExpression("t")))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB", new CodeVariableReferenceExpression("t")))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add(cmm); } class1 = new CodeTypeDeclaration("TestSingleInterfaceImp"); class1.BaseTypes.Add(new CodeTypeReference("System.Object")); class1.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class1.IsClass = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class1.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareValueTypes)) { CodeTypeDeclaration structA = new CodeTypeDeclaration("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration("structB"); structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add(firstInt); CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add(structB); structA.Members.Add(innerStruct); nspace.Types.Add(structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod(); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA"); nestedStructMethod.Statements.Add(varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"), /* Expression1 */ new CodePrimitiveExpression(3) ) ); nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"))); cd.Members.Add(nestedStructMethod); } if (provider.Supports(GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod(); cd.Members.Add(cep); } // goto statements if (provider.Supports(GeneratorSupport.GotoStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)), new CodeGotoStatement("comehere")); cmm.Statements.Add(condstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6))); cmm.Statements.Add(new CodeLabeledStatement("comehere", new CodeMethodReturnStatement(new CodePrimitiveExpression(7)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.NestedTypes)) { cmm = new CodeMemberMethod(); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "publicNestedClassesMethod", new CodeVariableReferenceExpression("i")))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add(class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add(nestedClass); nestedClass = new CodeTypeDeclaration("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add(nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add(innerNestedClass); cmm = new CodeMemberMethod(); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); innerNestedClass.Members.Add(cmm); } // Parameter Attributes if (provider.Supports(GeneratorSupport.ParameterAttributes)) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah"); param1.CustomAttributes.Add( new CodeAttributeDeclaration( "System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument( "Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument( "IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param1); cd.Members.Add(method1); } // public static members if (provider.Supports(GeneratorSupport.PublicStaticMembers)) { cmm = new CodeMemberMethod(); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16))); cd.Members.Add(cmm); } // reference parameters if (provider.Supports(GeneratorSupport.ReferenceParameters)) { cmm = new CodeMemberMethod(); cmm.Name = "Work"; cmm.ReturnType = new CodeTypeReference("System.void"); cmm.Attributes = MemberAttributes.Static; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); param.Direction = FieldDirection.Ref; cmm.Parameters.Add(param); // add parameter with out direction param = new CodeParameterDeclarationExpression(typeof(int), "j"); param.Direction = FieldDirection.Out; cmm.Parameters.Add(param); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4)))); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"), new CodePrimitiveExpression(5))); cd.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(parames); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodePrimitiveExpression(10))); cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b")); // invoke the method called "work" CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression (new CodeTypeReferenceExpression("TEST"), "Work")); // add parameter with ref direction CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression("a")); methodinvoked.Parameters.Add(parameter); // add parameter with out direction parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b")); methodinvoked.Parameters.Add(parameter); cmm.Statements.Add(methodinvoked); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.ReturnTypeAttributes)) { CodeMemberMethod function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe")))); function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return"))); cd.Members.Add(function1); } if (provider.Supports(GeneratorSupport.StaticConstructors)) { cmm = new CodeMemberMethod(); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4"))); // set then get number cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i") , new CodeVariableReferenceExpression("a"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "i"))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration(); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(int)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeTypeConstructor ctc = new CodeTypeConstructor(); class1.Members.Add(ctc); } if (provider.Supports(GeneratorSupport.TryCatchStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement(); tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(5)))); cmm.Statements.Add(tcfstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEvents)) { CodeNamespace ns = new CodeNamespace(); ns.Name = "MyNamespace"; ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(ns); class1 = new CodeTypeDeclaration("Test"); class1.IsClass = true; class1.BaseTypes.Add(new CodeTypeReference("Form")); ns.Types.Add(class1); CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button")); class1.Members.Add(mfield); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"), new CodePrimitiveExpression(600), new CodePrimitiveExpression(600)))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Text"), new CodePrimitiveExpression("Test"))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "TabIndex"), new CodePrimitiveExpression(0))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"), new CodePrimitiveExpression(400), new CodePrimitiveExpression(525)))); ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler") , new CodeThisReferenceExpression(), "b_Click"))); class1.Members.Add(ctor); CodeMemberEvent evt = new CodeMemberEvent(); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference("System.EventHandler"); evt.Attributes = MemberAttributes.Public; class1.Members.Add(evt); cmm = new CodeMemberMethod(); cmm.Name = "b_Click"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e")); class1.Members.Add(cmm); } AssertEqual(cu, @"'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Imports System Imports System.ComponentModel Imports System.Drawing Imports System.Windows.Forms <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""), _ Assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")> Namespace NSPC Public Class TEST Public Function ArraysOfArrays() As Integer Dim arrayOfArrays()() As Integer = New Integer()() {New Integer() {3, 4}, New Integer() {1}} Return arrayOfArrays(0)(1) End Function Public Shared Function ChainedConstructorUse() As String Dim t As Test2 = New Test2() Return t.accessStringField End Function Public Function ComplexExpressions(ByVal i As Integer) As Integer i = (i _ * (i + 3)) Return i End Function Public Shared Function OutputDecimalEnumVal(ByVal i As Integer) As Integer If (i = 3) Then Return CType(DecimalEnum.Num3,Integer) End If If (i = 4) Then Return CType(DecimalEnum.Num4,Integer) End If If (i = 2) Then Return CType(DecimalEnum.Num2,Integer) End If If (i = 1) Then Return CType(DecimalEnum.Num1,Integer) End If If (i = 0) Then Return CType(DecimalEnum.Num0,Integer) End If Return (i + 10) End Function Public Shared Function TestSingleInterface(ByVal i As Integer) As Integer Dim t As TestSingleInterfaceImp = New TestSingleInterfaceImp() Return t.InterfaceMethod(i) End Function Public Shared Function TestMultipleInterfaces(ByVal i As Integer) As Integer Dim t As TestMultipleInterfaceImp = New TestMultipleInterfaceImp() Dim interfaceAobject As InterfaceA = CType(t,InterfaceA) Dim interfaceBobject As InterfaceB = CType(t,InterfaceB) Return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i)) End Function Public Shared Function NestedStructMethod() As Integer Dim varStructA As structA varStructA.innerStruct.int1 = 3 Return varStructA.innerStruct.int1 End Function Public Shared Sub Main() End Sub Public Function GoToMethod(ByVal i As Integer) As Integer If (i < 1) Then goto comehere End If Return 6 comehere: Return 7 End Function Public Shared Function CallingPublicNestedScenario(ByVal i As Integer) As Integer Dim t As PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC = New PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC() Return t.publicNestedClassesMethod(i) End Function Public Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String) End Sub Public Shared Function PublicStaticMethod() As Integer Return 16 End Function Shared Sub Work(ByRef i As Integer, ByRef j As Integer) i = (i + 4) j = 5 End Sub Public Shared Function CallingWork(ByVal a As Integer) As Integer a = 10 Dim b As Integer TEST.Work(a, b) Return (a + b) End Function Public Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String Return ""Return"" End Function Public Shared Function TestStaticConstructor(ByVal a As Integer) As Integer Dim t As Test4 = New Test4() t.i = a Return t.i End Function Public Shared Function TryCatchMethod(ByVal a As Integer) As Integer Try Finally a = (a + 5) End Try Return a End Function End Class Public Class Test2 Private stringField As String Public Sub New() Me.New(""testingString"", Nothing, Nothing) End Sub Public Sub New(ByVal p1 As String, ByVal p2 As String, ByVal p3 As String) MyBase.New Me.stringField = p1 End Sub Public Property accessStringField() As String Get Return Me.stringField End Get Set Me.stringField = value End Set End Property End Class Public Enum DecimalEnum Num0 = 0 Num1 = 1 Num2 = 2 Num3 = 3 Num4 = 4 End Enum Public Interface InterfaceA Function InterfaceMethod(ByVal a As Integer) As Integer End Interface Public Interface InterfaceB Function InterfaceMethod(ByVal a As Integer) As Integer End Interface Public Class TestMultipleInterfaceImp Inherits Object Implements InterfaceB, InterfaceA Public Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod , InterfaceB.InterfaceMethod Return a End Function End Class Public Class TestSingleInterfaceImp Inherits Object Implements InterfaceA Public Overridable Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod Return a End Function End Class Public Structure structA Public innerStruct As structB Public Structure structB Public int1 As Integer End Structure End Structure Public Class PublicNestedClassA Public Class PublicNestedClassB1 End Class Public Class PublicNestedClassB2 Public Class PublicNestedClassC Public Function publicNestedClassesMethod(ByVal a As Integer) As Integer Return a End Function End Class End Class End Class Public Class Test4 Private number As Integer Shared Sub New() End Sub Public Property i() As Integer Get Return number End Get Set number = value End Set End Property End Class End Namespace Namespace MyNamespace Public Class Test Inherits Form Private b As Button = New Button() Public Sub New() MyBase.New Me.Size = New Size(600, 600) b.Text = ""Test"" b.TabIndex = 0 b.Location = New Point(400, 525) AddHandler MyEvent, AddressOf Me.b_Click End Sub Public Event MyEvent As System.EventHandler Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs) End Sub End Class End Namespace"); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.ReferenceParameters)) { //************** static internal method with parameters with out and ref directions, ************** //************** and void return type ************** // GENERATES (C#): // /*FamANDAssem*/ internal static void Work(ref int i, out int j) { // i = (i + 4); // j = 5; // } CodeMemberMethod cmm1 = new CodeMemberMethod (); cmm1.Name = "Work"; cmm1.ReturnType = new CodeTypeReference ("System.void"); cmm1.Attributes = MemberAttributes.Static | MemberAttributes.FamilyAndAssembly; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); param.Direction = FieldDirection.Ref; cmm1.Parameters.Add (param); // add parameter with out direction param = new CodeParameterDeclarationExpression (typeof (int), "j"); param.Direction = FieldDirection.Out; cmm1.Parameters.Add (param); cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (4)))); cmm1.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("j"), new CodePrimitiveExpression (5))); cd.Members.Add (cmm1); } // ********* pass by value using a protected method ****** // GENERATES (C#): // protected static int ProtectedMethod(int a) { // return a; // } CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "ProtectedMethod"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Family | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cmm.ReturnType = new CodeTypeReference (typeof (int)); cd.Members.Add (cmm); // declare a method to test the protected method with new attribute // GENERATES (C#): // public static int CallProtected(int a) { // return (a + ProtectedMethod(a)); // } AddScenario ("CheckCallProtected"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallProtected"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; CodeMethodReferenceExpression meth = new CodeMethodReferenceExpression (); meth.MethodName = "ProtectedMethod"; meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth, new CodeArgumentReferenceExpression ("a"))))); cd.Members.Add (cmm); // GENERATES (C#): // public static void Main() { // } if (Supports (provider, GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod (); cd.Members.Add (cep); } // add a second class cd = new CodeTypeDeclaration ("TEST2"); cd.BaseTypes.Add (new CodeTypeReference ("TEST")); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.ReferenceParameters)) { // GENERATES (C#): // public static int CallingWork(int a) { // a = 10; // int b; // TEST.Work(ref a, out b); // return (a + b); // } AddScenario ("CheckCallingWork"); cmm = new CodeMemberMethod (); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public; CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (parames); cmm.ReturnType = new CodeTypeReference ("System.Int32"); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodePrimitiveExpression (10))); cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "b")); // invoke the method called "work" CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression ("TEST"), "Work"); // add parameter with ref direction CodeDirectionExpression parameter = new CodeDirectionExpression (FieldDirection.Ref, new CodeArgumentReferenceExpression ("a")); methodinvoked.Parameters.Add (parameter); // add parameter with out direction parameter = new CodeDirectionExpression (FieldDirection.Out, new CodeVariableReferenceExpression ("b")); methodinvoked.Parameters.Add (parameter); cmm.Statements.Add (methodinvoked); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression ("b")))); cd.Members.Add (cmm); } // ***** declare a private method with value return type ****** // GENERATES (C#): // private static int PrivateMethod() { // return 5; // } cmm = new CodeMemberMethod (); cmm.Name = "PrivateMethod"; cmm.Attributes = MemberAttributes.Private | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (5))); cmm.ReturnType = new CodeTypeReference (typeof (int)); cd.Members.Add (cmm); // declare a method to test the private method // GENERATES (C#): // public static int CallPrivateMethod(int a) { // return (a + PrivateMethod()); // } AddScenario ("CheckCallPrivateMethod"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallPrivateMethod"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; meth = new CodeMethodReferenceExpression (); meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); meth.MethodName = "PrivateMethod"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth)))); cd.Members.Add (cmm); // ********* pass by value using a protected static method ****** // this class needs to inherit from the first class so that we can call the protected method from here and call the // public method that calls the protected method from that class // declare a method to test the protected method // GENERATES (C#): // public static int CallProtectedAndPublic(int a) { // return (CallProtected(a) + ProtectedMethod(a)); // } AddScenario ("CheckCallProtectedAndPublic"); cmm = new CodeMemberMethod (); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Name = "CallProtectedAndPublic"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; meth = new CodeMethodReferenceExpression (); meth.MethodName = "ProtectedMethod"; meth.TargetObject = new CodeTypeReferenceExpression("TEST2"); CodeMethodReferenceExpression meth2 = new CodeMethodReferenceExpression (); meth2.MethodName = "CallProtected"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeMethodInvokeExpression (meth2, new CodeArgumentReferenceExpression ("a")), CodeBinaryOperatorType.Add, new CodeMethodInvokeExpression (meth, new CodeArgumentReferenceExpression ("a"))))); cd.Members.Add (cmm); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // ******** implement a single public interface *********** // declare an interface // GENERATES (C#): // public interface TEST3 { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("TEST3"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement the interface // GENERATES (C#): // public class TEST3b : object, TEST3 { // public virtual int InterfaceMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("TEST3b"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("TEST3")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); // ********implement two interfaces with overloading method name******* // declare the second interface // GENERATES (C#): // public interface TEST4 { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("TEST4"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement both of the interfaces // GENERATES (C#): // public class TEST4b : object, TEST3, TEST4 { // public int InterfaceMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("TEST4b"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("TEST3")); cd.BaseTypes.Add (new CodeTypeReference ("TEST4")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST3")); cmm.ImplementationTypes.Add (new CodeTypeReference ("TEST4")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); } // create a class which will have a method to call the method name that was overloaded // this class will also call a method in the class that implements the private implements testcase cd = new CodeTypeDeclaration ("TEST5"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // GENERATES (C#): // public static int TestMultipleInterfaces(int i) { // TEST4b t = new TEST4b(); // TEST3 TEST3 = ((TEST3)(t)); // TEST4 TEST4 = ((TEST4)(t)); // return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i)); // } AddScenario ("CheckTestMultipleInterfaces"); cmm = new CodeMemberMethod (); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4b", "t", new CodeObjectCreateExpression ("TEST4b"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4", new CodeVariableReferenceExpression ("t")))); CodeMethodInvokeExpression methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3") , "InterfaceMethod"); methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4") , "InterfaceMethod"); methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2))); cd.Members.Add (cmm); // GENERATES (C#): // public static int PrivateImplements(int i) { // TEST6 t = new TEST6(); // TEST3 TEST3 = ((TEST3)(t)); // TEST4 TEST4 = ((TEST4)(t)); // return (TEST3.InterfaceMethod(i) - TEST4.InterfaceMethod(i)); // } AddScenario ("CheckPrivateImplements"); cmm = new CodeMemberMethod (); cmm.Name = "PrivateImplements"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST6", "t", new CodeObjectCreateExpression ("TEST6"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST3", "TEST3", new CodeCastExpression ("TEST3", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("TEST4", "TEST4", new CodeCastExpression ("TEST4", new CodeVariableReferenceExpression ("t")))); methodinvoking = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST3") , "InterfaceMethod"); methodinvoking.Parameters.Add (new CodeArgumentReferenceExpression ("i")); methodinvoking2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("TEST4") , "InterfaceMethod"); methodinvoking2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoking, CodeBinaryOperatorType.Subtract, methodinvoking2))); cd.Members.Add (cmm); //******************* private implements *************************** // implement both of the interfaces // GENERATES (C#): // public class TEST6 : object, TEST3, TEST4 { // int TEST3.InterfaceMethod(int a) { // return a; // } // int TEST4.InterfaceMethod(int a) { // return (5 * a); // } // } CodeTypeDeclaration ctd = new CodeTypeDeclaration ("TEST6"); ctd.BaseTypes.Add (new CodeTypeReference ("System.Object")); ctd.BaseTypes.Add (new CodeTypeReference ("TEST3")); ctd.BaseTypes.Add (new CodeTypeReference ("TEST4")); ctd.IsClass = true; nspace.Types.Add (ctd); // make a seperate implementation for each base // first for TEST3 base cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cmm.PrivateImplementationType = new CodeTypeReference ("TEST3"); ctd.Members.Add (cmm); // now implement for TEST4 base cmm = new CodeMemberMethod (); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.PrivateImplementationType = new CodeTypeReference ("TEST4"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (5), CodeBinaryOperatorType.Multiply, new CodeArgumentReferenceExpression ("a")))); ctd.Members.Add (cmm); } // method to test the 'new' scenario by calling the 'new' method // GENERATES (C#): // public int CallingNewScenario(int i) { // ClassWVirtualMethod t = new ClassWNewMethod(); // return (((ClassWNewMethod)(t)).VirtualMethod(i) - t.VirtualMethod(i)); // } CodeMethodInvokeExpression methodinvoke; #if !FSHARP AddScenario ("CheckCallingNewScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingNewScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWNewMethod")))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeCastExpression ("ClassWNewMethod", new CodeVariableReferenceExpression ("t")), "VirtualMethod"); methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoke2, CodeBinaryOperatorType.Subtract, methodinvoke))); cd.Members.Add (cmm); #endif // similar to the 'new' test, write a method to complete testing of the 'override' scenario // GENERATES (C#): // public static int CallingOverrideScenario(int i) { // ClassWVirtualMethod t = new ClassWOverrideMethod(); // return t.VirtualMethod(i); // } AddScenario ("CheckCallingOverrideScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverrideScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression("ClassWOverrideMethod")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); //*************** overload member function **************** // new class which will include both functions // GENERATES (C#): // public class TEST7 { // public static int OverloadedMethod(int a) { // return a; // } // public static int OverloadedMethod(int a, int b) { // return (b + a); // } // public static int CallingOverloadedMethods(int i) { // return (OverloadedMethod(i, i) - OverloadedMethod(i)); // } // } cd = new CodeTypeDeclaration ("TEST7"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "OverloadedMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "b")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("b"), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); // declare a method that will call both OverloadedMethod functions AddScenario ("CheckCallingOverloadedMethods"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverloadedMethods"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public; CodeMethodReferenceExpression methodref = new CodeMethodReferenceExpression (); methodref.MethodName = "OverloadedMethod"; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i"), new CodeArgumentReferenceExpression ("i")) , CodeBinaryOperatorType.Subtract, new CodeMethodInvokeExpression (methodref, new CodeArgumentReferenceExpression ("i"))))); cd.Members.Add (cmm); // ***************** declare method using new ****************** // first declare a class with a virtual method in it // GENERATES (C#): // public class ClassWVirtualMethod { // public virtual int VirtualMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("ClassWVirtualMethod"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); #if !FSHARP // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWNewMethod : ClassWVirtualMethod { // public new virtual int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWNewMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.New; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); #endif // *************** declare a method using override ****************** // now declare a class that inherits from the previous class and has a 'new' method with the // name VirtualMethod // GENERATES (C#): // public class ClassWOverrideMethod : ClassWVirtualMethod { // public override int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWOverrideMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); }
public void CharEncoding() { string chars = "\u1234 \u4567 \uABCD \r \n \t \\ \" \' \0 \u2028 \u2029 \u0084 \u0085 \U00010F00"; var main = new CodeEntryPointMethod(); main.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Console)), "WriteLine"), new CodeExpression[] { new CodePrimitiveExpression(chars) })); AssertEqual(main, "public static void Main() { " + " System.Console.WriteLine(\"\u1234 \u4567 \uABCD \\r \\n \\t \\\\ \\\" \\' \\0 \\u2028 \\u2029 \u0084 \u0085 \U00010F00\"); " + "}"); }
public void GenericTypesAndConstraints() { CodeNamespace ns = new CodeNamespace("NS"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), })); CodeTypeParameter kType = new CodeTypeParameter("TKey"); 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("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); ns.Types.Add(class1); // 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 = "Nop"; printMethod.TypeParameters.Add(sType); printMethod.TypeParameters.Add(tType); printMethod.Attributes = MemberAttributes.Public; class1.Members.Add(printMethod); var class2 = new CodeTypeDeclaration(); class2.Name = "Demo"; var methodMain = new CodeEntryPointMethod(); var 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))); string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[]).FullName; var dictionaryType = new CodeTypeReference(dictionaryTypeName); methodMain.Statements.Add( new CodeVariableDeclarationStatement(dictionaryType, "dict2", new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) }))); class2.Members.Add(methodMain); ns.Types.Add(class2); AssertEqual(ns, @"namespace NS { using System; using System.Collections.Generic; public class MyDictionary<[System.ComponentModel.DescriptionAttribute(""KeyType"")] TKey, [System.ComponentModel.DescriptionAttribute(""ValueType"")] TValue> : Dictionary<TKey, TValue> where TKey : System.IComparable, IComparable<TKey>, new () where TValue : System.Collections.Generic.IList<string> { public virtual void Nop<S, T>() where S : new() { } } public class Demo { public static void Main() { MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>(); System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] dict2 = new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] { null}; } } }"); }
public void CharEncoding() { string chars = "\u1234 \u4567 \uABCD \r \n \t \\ \" \' \0 \u2028 \u2029 \u0084 \u0085 \U00010F00"; var main = new CodeEntryPointMethod(); main.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Console)), "WriteLine"), new CodeExpression[] { new CodePrimitiveExpression(chars) })); AssertEqual(main, "Public Shared Sub Main() " + " System.Console.WriteLine(\"\u1234 \u4567 \uABCD \"&Global.Microsoft.VisualBasic.ChrW(13)&\" \"&Global.Microsoft.VisualBasic.ChrW(10)&\" \"&Global.Microsoft.VisualBasic.ChrW(9)&\" \\ \"\" ' \"&Global.Microsoft.VisualBasic.ChrW(0)&\" \"&Global.Microsoft.VisualBasic.ChrW(8232)&\" \"&Global.Microsoft.VisualBasic.ChrW(8233)&\" \u0084 \u0085 \U00010F00\") " + "End Sub"); }
public void RegionsSnippetsAndLinePragmas() { CodeCompileUnit cu = new CodeCompileUnit(); 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; 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; 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)); var snippet1 = new CodeSnippetTypeMember(); var 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); cd.Members.Add(evt1); cd.Members.Add(nestedClass1); cd.Members.Add(delegate1); cd.Members.Add(snippet1); cd.Members.Add(field2); cd.Members.Add(method2); cd.Members.Add(constructor2); cd.Members.Add(property2); cd.Members.Add(typeConstructor2); cd.Members.Add(evt2); cd.Members.Add(nestedClass2); cd.Members.Add(delegate2); cd.Members.Add(snippet2); AssertEqual(cu, @"#Region ""Compile Unit Region"" '------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict Off Option Explicit On Namespace Namespace1 #Region ""Outer Type Region"" 'Outer Type Comment Public Class Class1 'Field 1 Comment Private field1 As String #Region ""Field Region"" Private field2 As String #End Region #Region ""Snippet Region"" #End Region #Region ""Type Constructor Region"" Shared Sub New() End Sub #End Region #Region ""Constructor Region"" Public Sub New() MyBase.New Me.field1 = ""value1"" Me.field2 = ""value2"" End Sub #End Region Public Sub New(ByVal value1 As String, ByVal value2 As String) MyBase.New End Sub Public ReadOnly Property Property1() As String Get Return Me.field1 End Get End Property #Region ""Property Region"" Public ReadOnly Property Property2() As String Get Return Me.field2 End Get End Property #End Region Public Event Event1 As System.EventHandler #Region ""Event Region"" Public Event Event2 As System.EventHandler #End Region Public Sub Method1() RaiseEvent Event1(Me, System.EventArgs.Empty) End Sub Public Shared Sub Main() End Sub #Region ""Method Region"" 'Method 2 Comment #ExternalSource(""MethodLinePragma.txt"",500) Public Sub Method2() RaiseEvent Event2(Me, System.EventArgs.Empty) End Sub #End ExternalSource #End Region Public Class NestedClass1 End Class Public Delegate Sub nestedDelegate1(ByVal sender As Object, ByVal e As System.EventArgs) #Region ""Nested Type Region"" 'Nested Type Comment #ExternalSource(""NestedTypeLinePragma.txt"",400) Public Class NestedClass2 End Class #End ExternalSource #End Region #Region ""Delegate Region"" Public Delegate Sub nestedDelegate2(ByVal sender As Object, ByVal e As System.EventArgs) #End Region End Class #End Region End Namespace #End Region"); }
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); nspace.Imports.Add (new CodeNamespaceImport ("System.Drawing")); nspace.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms")); nspace.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cu.Namespaces.Add (nspace); cu.ReferencedAssemblies.Add ("System.Drawing.dll"); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); cu.ReferencedAssemblies.Add ("System.Xml.dll"); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST"); cd.IsClass = true; nspace.Types.Add (cd); CodeMemberMethod cmm; // Arrays of Arrays #if !WHIDBEY // Everett VB code provider doesn't support array of array initialization if (!(provider is Microsoft.VisualBasic.VBCodeProvider)) { #endif if (Supports (provider, GeneratorSupport.ArraysOfArrays)) { AddScenario ("CheckArrayOfArrays"); cmm = new CodeMemberMethod (); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference (typeof (int[][])), "arrayOfArrays", new CodeArrayCreateExpression (typeof (int[][]), new CodeArrayCreateExpression (typeof (int[]), new CodePrimitiveExpression (3), new CodePrimitiveExpression (4)), new CodeArrayCreateExpression (typeof (int[]), new CodeExpression[] {new CodePrimitiveExpression (1)})))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArrayIndexerExpression ( new CodeArrayIndexerExpression (new CodeVariableReferenceExpression ("arrayOfArrays"), new CodePrimitiveExpression (0)), new CodePrimitiveExpression (1)))); cd.Members.Add (cmm); } #if !WHIDBEY } #endif // assembly attributes if (Supports (provider, GeneratorSupport.AssemblyAttributes)) { AddScenario ("CheckAssemblyAttributes"); CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes; attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly")))); attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration (); if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) { AddScenario ("CheckChainedConstructorArgs"); class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (String)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "stringField"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeConstructor cctor = new CodeConstructor (); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression ("testingString")); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null)); class1.Members.Add (cctor); CodeConstructor cc = new CodeConstructor (); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p1")); cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p2")); cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p3")); cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression () , "stringField"), new CodeArgumentReferenceExpression ("p1"))); class1.Members.Add (cc); // verify chained constructors work cmm = new CodeMemberMethod (); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (String)); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "accessStringField"))); cd.Members.Add (cmm); } // complex expressions if (Supports (provider, GeneratorSupport.ComplexExpressions)) { AddScenario ("CheckComplexExpressions"); cmm = new CodeMemberMethod (); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (3))))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("i"))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareEnums)) { AddScenario ("CheckDeclareEnums"); CodeTypeDeclaration ce = new CodeTypeDeclaration ("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add (ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField ("System.Int32", "Num" + (k).ToString ()); Field.InitExpression = new CodePrimitiveExpression (k); ce.Members.Add (Field); } cmm = new CodeMemberMethod (); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); cmm.Parameters.Add (param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement ( new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (4)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (2)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (1)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (0)); truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement (eq, truestmt); cmm.Statements.Add (condstmt); cmm.ReturnType = new CodeTypeReference ("System.Int32"); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (10)))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { AddScenario ("CheckDeclareInterfaces"); cmm = new CodeMemberMethod (); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression ("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t") , "InterfaceMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration ("InterfaceA"); class1.IsInterface = true; nspace.Types.Add (class1); cmm = new CodeMemberMethod (); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); class1.Members.Add (cmm); if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers)) { AddScenario ("CheckMultipleInterfaceMembers"); CodeTypeDeclaration classDecl = new CodeTypeDeclaration ("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add (classDecl); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); classDecl.Members.Add (cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration ("TestMultipleInterfaceImp"); class2.BaseTypes.Add (new CodeTypeReference ("System.Object")); class2.BaseTypes.Add (new CodeTypeReference ("InterfaceB")); class2.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); class2.IsClass = true; nspace.Types.Add (class2); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class2.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression ("TestMultipleInterfaceImp"))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceA", "interfaceAobject", new CodeCastExpression ("InterfaceA", new CodeVariableReferenceExpression ("t")))); cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceB", "interfaceBobject", new CodeCastExpression ("InterfaceB", new CodeVariableReferenceExpression ("t")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add (cmm); } class1 = new CodeTypeDeclaration ("TestSingleInterfaceImp"); class1.BaseTypes.Add (new CodeTypeReference ("System.Object")); class1.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); class1.IsClass = true; nspace.Types.Add (class1); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); } /*if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { AddScenario ("CheckDeclareValueTypes"); // create first struct to test nested structs // GENERATE (C#): // public struct structA { // public structB innerStruct; // public struct structB { // public int int1; // } // } CodeTypeDeclaration structA = new CodeTypeDeclaration ("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration ("structB"); structB.TypeAttributes = TypeAttributes.NestedPublic; structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField (typeof (int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add (firstInt); CodeMemberField innerStruct = new CodeMemberField ("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add (structB); structA.Members.Add (innerStruct); nspace.Types.Add (structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod (); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference (typeof (int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement ("structA", "varStructA"); nestedStructMethod.Statements.Add (varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1"), new CodePrimitiveExpression (3) ) ); nestedStructMethod.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1"))); cd.Members.Add (nestedStructMethod); }*/ if (Supports (provider, GeneratorSupport.EntryPointMethod)) { AddScenario ("CheckEntryPointMethod"); CodeEntryPointMethod cep = new CodeEntryPointMethod (); cd.Members.Add (cep); } // goto statements if (Supports (provider, GeneratorSupport.GotoStatements)) { AddScenario ("CheckGotoStatements"); cmm = new CodeMemberMethod (); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); cmm.Parameters.Add (param); CodeConditionStatement condstmt = new CodeConditionStatement (new CodeBinaryOperatorExpression ( new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression (1)), new CodeGotoStatement ("comehere")); cmm.Statements.Add (condstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (6))); cmm.Statements.Add (new CodeLabeledStatement ("comehere", new CodeMethodReturnStatement (new CodePrimitiveExpression (7)))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.NestedTypes)) { AddScenario ("CheckNestedTypes"); cmm = new CodeMemberMethod (); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "publicNestedClassesMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration ("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add (class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add (nestedClass); nestedClass = new CodeTypeDeclaration ("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add (nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration ("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add (innerNestedClass); cmm = new CodeMemberMethod (); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); innerNestedClass.Members.Add (cmm); } // Parameter Attributes if (Supports (provider, GeneratorSupport.ParameterAttributes)) { AddScenario ("CheckParameterAttributes"); CodeMemberMethod method1 = new CodeMemberMethod (); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah"); param1.CustomAttributes.Add ( new CodeAttributeDeclaration ( "System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument ( "Form", new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument ( "IsNullable", new CodePrimitiveExpression (false)))); method1.Parameters.Add (param1); cd.Members.Add (method1); } // public static members if (Supports (provider, GeneratorSupport.PublicStaticMembers)) { AddScenario ("CheckPublicStaticMembers"); cmm = new CodeMemberMethod (); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (16))); cd.Members.Add (cmm); } // reference parameters if (Supports (provider, GeneratorSupport.ReferenceParameters)) { AddScenario ("CheckReferenceParameters"); cmm = new CodeMemberMethod (); cmm.Name = "Work"; cmm.ReturnType = new CodeTypeReference ("System.void"); cmm.Attributes = MemberAttributes.Static; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i"); param.Direction = FieldDirection.Ref; cmm.Parameters.Add (param); // add parameter with out direction param = new CodeParameterDeclarationExpression (typeof (int), "j"); param.Direction = FieldDirection.Out; cmm.Parameters.Add (param); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (4)))); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("j"), new CodePrimitiveExpression (5))); cd.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (parames); cmm.ReturnType = new CodeTypeReference ("System.Int32"); cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodePrimitiveExpression (10))); cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "b")); // invoke the method called "work" CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeTypeReferenceExpression ("TEST"), "Work")); // add parameter with ref direction CodeDirectionExpression parameter = new CodeDirectionExpression (FieldDirection.Ref, new CodeArgumentReferenceExpression ("a")); methodinvoked.Parameters.Add (parameter); // add parameter with out direction parameter = new CodeDirectionExpression (FieldDirection.Out, new CodeVariableReferenceExpression ("b")); methodinvoked.Parameters.Add (parameter); cmm.Statements.Add (methodinvoked); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression ("b")))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) { AddScenario ("CheckReturnTypeAttributes"); CodeMemberMethod function1 = new CodeMemberMethod (); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference (typeof (string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument ("Namespace", new CodePrimitiveExpression ("Namespace Value")), new CodeAttributeArgument ("ElementName", new CodePrimitiveExpression ("Root, hehehe")))); function1.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("Return"))); cd.Members.Add (function1); } if (Supports (provider, GeneratorSupport.StaticConstructors)) { AddScenario ("CheckStaticConstructors"); cmm = new CodeMemberMethod (); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference (typeof (int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); // utilize constructor cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4"))); // set then get number cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i") , new CodeArgumentReferenceExpression ("a"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("t"), "i"))); cd.Members.Add (cmm); class1 = new CodeTypeDeclaration (); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add (class1); class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number")); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference (typeof (int)); prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number"))); prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"), new CodePropertySetValueReferenceExpression ())); class1.Members.Add (prop); CodeTypeConstructor ctc = new CodeTypeConstructor (); class1.Members.Add (ctc); } if (Supports (provider, GeneratorSupport.TryCatchStatements)) { AddScenario ("CheckTryCatchStatements"); cmm = new CodeMemberMethod (); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement (); tcfstmt.FinallyStatements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (5)))); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.DeclareEvents)) { AddScenario ("CheckDeclareEvents"); CodeNamespace ns = new CodeNamespace (); ns.Name = "MyNamespace"; ns.Imports.Add (new CodeNamespaceImport ("System")); ns.Imports.Add (new CodeNamespaceImport ("System.Drawing")); ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms")); ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel")); cu.Namespaces.Add (ns); class1 = new CodeTypeDeclaration ("Test"); class1.IsClass = true; class1.BaseTypes.Add (new CodeTypeReference ("Form")); ns.Types.Add (class1); CodeMemberField mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button")); class1.Members.Add (mfield); CodeConstructor ctor = new CodeConstructor (); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "Size"), new CodeObjectCreateExpression (new CodeTypeReference ("Size"), new CodePrimitiveExpression (600), new CodePrimitiveExpression (600)))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Text"), new CodePrimitiveExpression ("Test"))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "TabIndex"), new CodePrimitiveExpression (0))); ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"), "Location"), new CodeObjectCreateExpression (new CodeTypeReference ("Point"), new CodePrimitiveExpression (400), new CodePrimitiveExpression (525)))); ctor.Statements.Add (new CodeAttachEventStatement (new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler") , new CodeThisReferenceExpression (), "b_Click"))); class1.Members.Add (ctor); CodeMemberEvent evt = new CodeMemberEvent (); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference ("System.EventHandler"); evt.Attributes = MemberAttributes.Public; class1.Members.Add (evt); cmm = new CodeMemberMethod (); cmm.Name = "b_Click"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender")); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e")); class1.Members.Add (cmm); } if (Supports (provider, GeneratorSupport.MultidimensionalArrays)) { // no codedom language represents declaration of multidimensional arrays } }
public void DefaultValues() { var main = new CodeEntryPointMethod(); foreach (Type t in new[] { typeof(int), typeof(object), typeof(DateTime), typeof(string) }) { main.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Console)), "WriteLine"), new CodeExpression[] { new CodeDefaultValueExpression(new CodeTypeReference(t)) })); } AssertEqual(main, @"Public Shared Sub Main() System.Console.WriteLine(CType(Nothing, Integer)) System.Console.WriteLine(CType(Nothing, Object)) System.Console.WriteLine(CType(Nothing, Date)) System.Console.WriteLine(CType(Nothing, String)) End Sub"); AssertEqual( new CodeDefaultValueExpression(new CodeTypeReference(typeof(Guid))), "CType(Nothing, System.Guid)"); AssertEqual( new CodeDefaultValueExpression(new CodeTypeReference("Some.Type.Name")), "CType(Nothing, Some.Type.Name)"); }
public void DefaultValues() { var main = new CodeEntryPointMethod(); foreach (Type t in new[] { typeof(int), typeof(object), typeof(DateTime), typeof(string) }) { main.Statements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Console)), "WriteLine"), new CodeExpression[] { new CodeDefaultValueExpression(new CodeTypeReference(t)) })); } AssertEqual(main, "public static void Main() { " + " System.Console.WriteLine(default(int)); " + " System.Console.WriteLine(default(object)); " + " System.Console.WriteLine(default(System.DateTime)); " + " System.Console.WriteLine(default(string)); " + "}"); AssertEqual( new CodeDefaultValueExpression(new CodeTypeReference(typeof(Guid))), "default(System.Guid)"); AssertEqual( new CodeDefaultValueExpression(new CodeTypeReference("Some.Type.Name")), "default(Some.Type.Name)"); }
public void Params() { Func<string, int, CodeStatement> createStatement = (objName, iNum) => { CodeAssignStatement statement = new CodeAssignStatement(new CodeVariableReferenceExpression("str"), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(new CodeTypeReference(objName)), "Replace"), new CodeExpression[]{ new CodePrimitiveExpression("{" + iNum + "}"), new CodeMethodInvokeExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("array"), new CodePrimitiveExpression(iNum)), "ToString")})); return statement; }; CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "Class1"; ns.Types.Add(class1); CodeMemberMethod fooMethod1 = new CodeMemberMethod(); fooMethod1.Name = "Foo1"; fooMethod1.Attributes = MemberAttributes.Public; fooMethod1.ReturnType = new CodeTypeReference(typeof(string)); CodeParameterDeclarationExpression parameter1 = new CodeParameterDeclarationExpression(); parameter1.Name = "format"; parameter1.Type = new CodeTypeReference(typeof(string)); fooMethod1.Parameters.Add(parameter1); CodeParameterDeclarationExpression parameter2 = new CodeParameterDeclarationExpression(); parameter2.Name = "array"; parameter2.Type = new CodeTypeReference(typeof(object[])); parameter2.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArrayAttribute")); parameter2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.OptionalAttribute")); fooMethod1.Parameters.Add(parameter2); class1.Members.Add(fooMethod1); fooMethod1.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "str")); fooMethod1.Statements.Add(createStatement("format", 0)); fooMethod1.Statements.Add(createStatement("str", 1)); fooMethod1.Statements.Add(createStatement("str", 2)); fooMethod1.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("str"))); CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); methodMain.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("Class1"), "test1", new CodeObjectCreateExpression(new CodeTypeReference("Class1")))); methodMain.Statements.Add(new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference("test1")), "Foo1"), new CodeExpression[] { new CodePrimitiveExpression("{0} + {1} = {2}"), new CodePrimitiveExpression(1), new CodePrimitiveExpression(2), new CodePrimitiveExpression(3) }))); class1.Members.Add(methodMain); AssertEqual(ns, @"Imports System Namespace Namespace1 Public Class Class1 Public Overridable Function Foo1(ByVal format As String, <System.ParamArrayAttribute(), System.Runtime.InteropServices.OptionalAttribute()> ByVal array() As Object) As String Dim str As String str = format.Replace(""{0}"", array(0).ToString) str = str.Replace(""{1}"", array(1).ToString) str = str.Replace(""{2}"", array(2).ToString) Return str End Function Public Shared Sub Main() Dim test1 As Class1 = New Class1() test1.Foo1(""{0} + {1} = {2}"", 1, 2, 3) End Sub End Class End Namespace"); }
public void RegionsSnippetsAndLinePragmas() { var cu = new CodeCompileUnit(); 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); var 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; 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; 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)); var snippet1 = new CodeSnippetTypeMember(); var 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); cd.Members.Add(evt1); cd.Members.Add(nestedClass1); cd.Members.Add(delegate1); cd.Members.Add(snippet1); cd.Members.Add(field2); cd.Members.Add(method2); cd.Members.Add(constructor2); cd.Members.Add(property2); cd.Members.Add(typeConstructor2); cd.Members.Add(evt2); cd.Members.Add(nestedClass2); cd.Members.Add(delegate2); cd.Members.Add(snippet2); AssertEqual(cu, @"#region Compile Unit Region //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Namespace1 { #region Outer Type Region // Outer Type Comment public class Class1 { // Field 1 Comment private string field1; #region Field Region private string field2; #endregion #region Snippet Region #endregion #region Type Constructor Region static Class1() { } #endregion #region Constructor Region public Class1() { #region Statements Region this.field1 = ""value1""; this.field2 = ""value2""; #endregion } #endregion public Class1(string value1, string value2) { } public string Property1 { get { return this.field1; } } #region Property Region public string Property2 { get { return this.field2; } } #endregion public event System.EventHandler Event1; #region Event Region public event System.EventHandler Event2; #endregion public void Method1() { this.Event1(this, System.EventArgs.Empty); } public static void Main() { } #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 class NestedClass1 { } public delegate void nestedDelegate1(object sender, System.EventArgs e); #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 } #endregion } #endregion"); }
public void GenericTypesAndConstraints() { CodeNamespace ns = new CodeNamespace("NS"); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "MyDictionary"; class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), })); CodeTypeParameter kType = new CodeTypeParameter("TKey"); 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("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); ns.Types.Add(class1); // 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 = "Nop"; printMethod.TypeParameters.Add(sType); printMethod.TypeParameters.Add(tType); printMethod.Attributes = MemberAttributes.Public; class1.Members.Add(printMethod); var class2 = new CodeTypeDeclaration(); class2.Name = "Demo"; var methodMain = new CodeEntryPointMethod(); var 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))); string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[]).FullName; var dictionaryType = new CodeTypeReference(dictionaryTypeName); methodMain.Statements.Add( new CodeVariableDeclarationStatement(dictionaryType, "dict2", new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) }))); class2.Members.Add(methodMain); ns.Types.Add(class2); AssertEqual(ns, @"Imports System Imports System.Collections.Generic Namespace NS Public Class MyDictionary(Of TKey As {System.IComparable, IComparable(Of TKey), New}, TValue As System.Collections.Generic.IList(Of String)) Inherits Dictionary(Of TKey, TValue) Public Overridable Sub Nop(Of S As New, T)() End Sub End Class Public Class Demo Public Shared Sub Main() Dim dict As MyDictionary(Of Integer, List(Of String)) = New MyDictionary(Of Integer, List(Of String))() Dim dict2() As System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String)) = New System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String))() {Nothing} End Sub End Class End Namespace"); }
public void Params() { Func<string, int, CodeStatement> createStatement = (objName, iNum) => { CodeAssignStatement statement = new CodeAssignStatement(new CodeVariableReferenceExpression("str"), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression( new CodeTypeReferenceExpression(new CodeTypeReference(objName)), "Replace"), new CodeExpression[]{ new CodePrimitiveExpression("{" + iNum + "}"), new CodeMethodInvokeExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("array"), new CodePrimitiveExpression(iNum)), "ToString")})); return statement; }; CodeNamespace ns = new CodeNamespace("Namespace1"); ns.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration class1 = new CodeTypeDeclaration(); class1.Name = "Class1"; ns.Types.Add(class1); CodeMemberMethod fooMethod1 = new CodeMemberMethod(); fooMethod1.Name = "Foo1"; fooMethod1.Attributes = MemberAttributes.Public; fooMethod1.ReturnType = new CodeTypeReference(typeof(string)); CodeParameterDeclarationExpression parameter1 = new CodeParameterDeclarationExpression(); parameter1.Name = "format"; parameter1.Type = new CodeTypeReference(typeof(string)); fooMethod1.Parameters.Add(parameter1); CodeParameterDeclarationExpression parameter2 = new CodeParameterDeclarationExpression(); parameter2.Name = "array"; parameter2.Type = new CodeTypeReference(typeof(object[])); parameter2.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArrayAttribute")); parameter2.CustomAttributes.Add(new CodeAttributeDeclaration("System.Runtime.InteropServices.OptionalAttribute")); fooMethod1.Parameters.Add(parameter2); class1.Members.Add(fooMethod1); fooMethod1.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "str")); fooMethod1.Statements.Add(createStatement("format", 0)); fooMethod1.Statements.Add(createStatement("str", 1)); fooMethod1.Statements.Add(createStatement("str", 2)); fooMethod1.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("str"))); CodeEntryPointMethod methodMain = new CodeEntryPointMethod(); methodMain.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("Class1"), "test1", new CodeObjectCreateExpression(new CodeTypeReference("Class1")))); methodMain.Statements.Add(new CodeExpressionStatement( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference("test1")), "Foo1"), new CodeExpression[] { new CodePrimitiveExpression("{0} + {1} = {2}"), new CodePrimitiveExpression(1), new CodePrimitiveExpression(2), new CodePrimitiveExpression(3) }))); class1.Members.Add(methodMain); AssertEqual(ns, @"namespace Namespace1 { using System; public class Class1 { public virtual string Foo1(string format, [System.Runtime.InteropServices.OptionalAttribute()] params object[] array) { string str; str = format.Replace(""{0}"", array[0].ToString()); str = str.Replace(""{1}"", array[1].ToString()); str = str.Replace(""{2}"", array[2].ToString()); return str; } public static void Main() { Class1 test1 = new Class1(); test1.Foo1(""{0} + {1} = {2}"", 1, 2, 3); } } }"); }
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 void ProviderSupports() { CodeDomProvider provider = GetProvider(); var cu = new CodeCompileUnit(); var nspace = new CodeNamespace("NSPC"); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("System.Drawing")); nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(nspace); var cd = new CodeTypeDeclaration("TEST"); cd.IsClass = true; nspace.Types.Add(cd); // Arrays of Arrays var cmm = new CodeMemberMethod(); cmm.Name = "ArraysOfArrays"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; if (provider.Supports(GeneratorSupport.ArraysOfArrays)) { cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])), "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]), new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)), new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) })))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression( new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0)) , new CodePrimitiveExpression(1)))); } else { cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0))); } cd.Members.Add(cmm); // assembly attributes if (provider.Supports(GeneratorSupport.AssemblyAttributes)) { CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes; attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly")))); attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2")))); } CodeTypeDeclaration class1 = new CodeTypeDeclaration(); if (provider.Supports(GeneratorSupport.ChainedConstructorArguments)) { class1.Name = "Test2"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "accessStringField"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(String)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "stringField"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeConstructor cctor = new CodeConstructor(); cctor.Attributes = MemberAttributes.Public; cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString")); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null)); class1.Members.Add(cctor); CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded; cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2")); cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3")); cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression() , "stringField"), new CodeVariableReferenceExpression("p1"))); class1.Members.Add(cc); // verify chained constructors work cmm = new CodeMemberMethod(); cmm.Name = "ChainedConstructorUse"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(String)); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "accessStringField"))); cd.Members.Add(cmm); } // complex expressions if (provider.Supports(GeneratorSupport.ComplexExpressions)) { cmm = new CodeMemberMethod(); cmm.Name = "ComplexExpressions"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public; cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i")); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply, new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(3))))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEnums)) { CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum"); ce.IsEnum = true; nspace.Types.Add(ce); // things to enumerate for (int k = 0; k < 5; k++) { CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString()); Field.InitExpression = new CodePrimitiveExpression(k); ce.Members.Add(Field); } cmm = new CodeMemberMethod(); cmm.Name = "OutputDecimalEnumVal"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(3)); CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement( new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3"))); CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0)); truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0"))); condstmt = new CodeConditionStatement(eq, truestmt); cmm.Statements.Add(condstmt); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareInterfaces)) { cmm = new CodeMemberMethod(); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp"))); CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke)); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("InterfaceA"); class1.IsInterface = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); class1.Members.Add(cmm); if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers)) { CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB"); classDecl.IsInterface = true; nspace.Types.Add(classDecl); cmm = new CodeMemberMethod(); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); classDecl.Members.Add(cmm); CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp"); class2.BaseTypes.Add(new CodeTypeReference("System.Object")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceB")); class2.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class2.IsClass = true; nspace.Types.Add(class2); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class2.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp"))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA", new CodeVariableReferenceExpression("t")))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB", new CodeVariableReferenceExpression("t")))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke, CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add(cmm); } class1 = new CodeTypeDeclaration("TestSingleInterfaceImp"); class1.BaseTypes.Add(new CodeTypeReference("System.Object")); class1.BaseTypes.Add(new CodeTypeReference("InterfaceA")); class1.IsClass = true; nspace.Types.Add(class1); cmm = new CodeMemberMethod(); cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); class1.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareValueTypes)) { CodeTypeDeclaration structA = new CodeTypeDeclaration("structA"); structA.IsStruct = true; CodeTypeDeclaration structB = new CodeTypeDeclaration("structB"); structB.Attributes = MemberAttributes.Public; structB.IsStruct = true; CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1"); firstInt.Attributes = MemberAttributes.Public; structB.Members.Add(firstInt); CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct"); innerStruct.Attributes = MemberAttributes.Public; structA.Members.Add(structB); structA.Members.Add(innerStruct); nspace.Types.Add(structA); CodeMemberMethod nestedStructMethod = new CodeMemberMethod(); nestedStructMethod.Name = "NestedStructMethod"; nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int)); nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA"); nestedStructMethod.Statements.Add(varStructA); nestedStructMethod.Statements.Add ( new CodeAssignStatement ( /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"), /* Expression1 */ new CodePrimitiveExpression(3) ) ); nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"))); cd.Members.Add(nestedStructMethod); } if (provider.Supports(GeneratorSupport.EntryPointMethod)) { CodeEntryPointMethod cep = new CodeEntryPointMethod(); cd.Members.Add(cep); } // goto statements if (provider.Supports(GeneratorSupport.GotoStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "GoToMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); cmm.Parameters.Add(param); CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)), new CodeGotoStatement("comehere")); cmm.Statements.Add(condstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6))); cmm.Statements.Add(new CodeLabeledStatement("comehere", new CodeMethodReturnStatement(new CodePrimitiveExpression(7)))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.NestedTypes)) { cmm = new CodeMemberMethod(); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression(new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "publicNestedClassesMethod", new CodeVariableReferenceExpression("i")))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration("PublicNestedClassA"); class1.IsClass = true; nspace.Types.Add(class1); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; class1.Members.Add(nestedClass); nestedClass = new CodeTypeDeclaration("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; class1.Members.Add(nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add(innerNestedClass); cmm = new CodeMemberMethod(); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); innerNestedClass.Members.Add(cmm); } // Parameter Attributes if (provider.Supports(GeneratorSupport.ParameterAttributes)) { CodeMemberMethod method1 = new CodeMemberMethod(); method1.Name = "MyMethod"; method1.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah"); param1.CustomAttributes.Add( new CodeAttributeDeclaration( "System.Xml.Serialization.XmlElementAttribute", new CodeAttributeArgument( "Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")), new CodeAttributeArgument( "IsNullable", new CodePrimitiveExpression(false)))); method1.Parameters.Add(param1); cd.Members.Add(method1); } // public static members if (provider.Supports(GeneratorSupport.PublicStaticMembers)) { cmm = new CodeMemberMethod(); cmm.Name = "PublicStaticMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16))); cd.Members.Add(cmm); } // reference parameters if (provider.Supports(GeneratorSupport.ReferenceParameters)) { cmm = new CodeMemberMethod(); cmm.Name = "Work"; cmm.ReturnType = new CodeTypeReference("System.void"); cmm.Attributes = MemberAttributes.Static; // add parameter with ref direction CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i"); param.Direction = FieldDirection.Ref; cmm.Parameters.Add(param); // add parameter with out direction param = new CodeParameterDeclarationExpression(typeof(int), "j"); param.Direction = FieldDirection.Out; cmm.Parameters.Add(param); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4)))); cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"), new CodePrimitiveExpression(5))); cd.Members.Add(cmm); cmm = new CodeMemberMethod(); cmm.Name = "CallingWork"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(parames); cmm.ReturnType = new CodeTypeReference("System.int32"); cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodePrimitiveExpression(10))); cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b")); // invoke the method called "work" CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression (new CodeTypeReferenceExpression("TEST"), "Work")); // add parameter with ref direction CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression("a")); methodinvoked.Parameters.Add(parameter); // add parameter with out direction parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b")); methodinvoked.Parameters.Add(parameter); cmm.Statements.Add(methodinvoked); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.ReturnTypeAttributes)) { CodeMemberMethod function1 = new CodeMemberMethod(); function1.Name = "MyFunction"; function1.ReturnType = new CodeTypeReference(typeof(string)); function1.Attributes = MemberAttributes.Public | MemberAttributes.Final; function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute")); function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe")))); function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return"))); cd.Members.Add(function1); } if (provider.Supports(GeneratorSupport.StaticConstructors)) { cmm = new CodeMemberMethod(); cmm.Name = "TestStaticConstructor"; cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; cmm.ReturnType = new CodeTypeReference(typeof(int)); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); // utilize constructor cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4"))); // set then get number cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i") , new CodeVariableReferenceExpression("a"))); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("t"), "i"))); cd.Members.Add(cmm); class1 = new CodeTypeDeclaration(); class1.Name = "Test4"; class1.IsClass = true; nspace.Types.Add(class1); class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number")); CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = "i"; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; prop.Type = new CodeTypeReference(typeof(int)); prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number"))); prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"), new CodePropertySetValueReferenceExpression())); class1.Members.Add(prop); CodeTypeConstructor ctc = new CodeTypeConstructor(); class1.Members.Add(ctc); } if (provider.Supports(GeneratorSupport.TryCatchStatements)) { cmm = new CodeMemberMethod(); cmm.Name = "TryCatchMethod"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a"); cmm.Parameters.Add(param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement(); tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(5)))); cmm.Statements.Add(tcfstmt); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a"))); cd.Members.Add(cmm); } if (provider.Supports(GeneratorSupport.DeclareEvents)) { CodeNamespace ns = new CodeNamespace(); ns.Name = "MyNamespace"; ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.Drawing")); ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); cu.Namespaces.Add(ns); class1 = new CodeTypeDeclaration("Test"); class1.IsClass = true; class1.BaseTypes.Add(new CodeTypeReference("Form")); ns.Types.Add(class1); CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b"); mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button")); class1.Members.Add(mfield); CodeConstructor ctor = new CodeConstructor(); ctor.Attributes = MemberAttributes.Public; ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"), new CodePrimitiveExpression(600), new CodePrimitiveExpression(600)))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Text"), new CodePrimitiveExpression("Test"))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "TabIndex"), new CodePrimitiveExpression(0))); ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"), "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"), new CodePrimitiveExpression(400), new CodePrimitiveExpression(525)))); ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler") , new CodeThisReferenceExpression(), "b_Click"))); class1.Members.Add(ctor); CodeMemberEvent evt = new CodeMemberEvent(); evt.Name = "MyEvent"; evt.Type = new CodeTypeReference("System.EventHandler"); evt.Attributes = MemberAttributes.Public; class1.Members.Add(evt); cmm = new CodeMemberMethod(); cmm.Name = "b_Click"; cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender")); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e")); class1.Members.Add(cmm); } AssertEqual(cu, @"//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")] [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")] namespace NSPC { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; public class TEST { public int ArraysOfArrays() { int[][] arrayOfArrays = new int[][] { new int[] { 3, 4}, new int[] { 1}}; return arrayOfArrays[0][1]; } public static string ChainedConstructorUse() { Test2 t = new Test2(); return t.accessStringField; } public int ComplexExpressions(int i) { i = (i * (i + 3)); return i; } public static int OutputDecimalEnumVal(int i) { if ((i == 3)) { return ((int)(DecimalEnum.Num3)); } if ((i == 4)) { return ((int)(DecimalEnum.Num4)); } if ((i == 2)) { return ((int)(DecimalEnum.Num2)); } if ((i == 1)) { return ((int)(DecimalEnum.Num1)); } if ((i == 0)) { return ((int)(DecimalEnum.Num0)); } return (i + 10); } public static int TestSingleInterface(int i) { TestSingleInterfaceImp t = new TestSingleInterfaceImp(); return t.InterfaceMethod(i); } public static int TestMultipleInterfaces(int i) { TestMultipleInterfaceImp t = new TestMultipleInterfaceImp(); InterfaceA interfaceAobject = ((InterfaceA)(t)); InterfaceB interfaceBobject = ((InterfaceB)(t)); return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i)); } public static int NestedStructMethod() { structA varStructA; varStructA.innerStruct.int1 = 3; return varStructA.innerStruct.int1; } public static void Main() { } public int GoToMethod(int i) { if ((i < 1)) { goto comehere; } return 6; comehere: return 7; } public static int CallingPublicNestedScenario(int i) { PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC t = new PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC(); return t.publicNestedClassesMethod(i); } public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah) { } public static int PublicStaticMethod() { return 16; } static void Work(ref int i, out int j) { i = (i + 4); j = 5; } public static int CallingWork(int a) { a = 10; int b; TEST.Work(ref a, out b); return (a + b); } [return: System.Xml.Serialization.XmlIgnoreAttribute()] [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")] public string MyFunction() { return ""Return""; } public static int TestStaticConstructor(int a) { Test4 t = new Test4(); t.i = a; return t.i; } public static int TryCatchMethod(int a) { try { } finally { a = (a + 5); } return a; } } public class Test2 { private string stringField; public Test2() : this(""testingString"", null, null) { } public Test2(string p1, string p2, string p3) { this.stringField = p1; } public string accessStringField { get { return this.stringField; } set { this.stringField = value; } } } public enum DecimalEnum { Num0 = 0, Num1 = 1, Num2 = 2, Num3 = 3, Num4 = 4, } public interface InterfaceA { int InterfaceMethod(int a); } public interface InterfaceB { int InterfaceMethod(int a); } public class TestMultipleInterfaceImp : object, InterfaceB, InterfaceA { public int InterfaceMethod(int a) { return a; } } public class TestSingleInterfaceImp : object, InterfaceA { public virtual int InterfaceMethod(int a) { return a; } } public struct structA { public structB innerStruct; public struct structB { public int int1; } } public class PublicNestedClassA { public class PublicNestedClassB1 { } public class PublicNestedClassB2 { public class PublicNestedClassC { public int publicNestedClassesMethod(int a) { return a; } } } } public class Test4 { private int number; static Test4() { } public int i { get { return number; } set { number = value; } } } } namespace MyNamespace { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; public class Test : Form { private Button b = new Button(); public Test() { this.Size = new Size(600, 600); b.Text = ""Test""; b.TabIndex = 0; b.Location = new Point(400, 525); this.MyEvent += new EventHandler(this.b_Click); } public event System.EventHandler MyEvent; private void b_Click(object sender, System.EventArgs e) { } } }"); }