Пример #1
0
 protected override CodeMemberMethod Generate(CodeParameterDeclarationExpression[] parms)
 {
     var method = gen.LambdaMethod(parms, () => Xlat(f.body));
     GenerateTupleParameterUnpackers(method);
     LocalVariableGenerator.Generate(method);
     return method;
 }
Пример #2
0
 protected override void GenerateDefaultArgMethod(
     CodeParameterDeclarationExpression[] argList,
     CodeExpression [] paramList)
 {
     var cons = gen.Constructor(argList, () => {});
     cons.ChainedConstructorArgs.AddRange(paramList);
 }
Пример #3
0
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) {
        //cu.UserData["AllowLateBound"] = true;

        // GENERATES (C#):
        //  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;
        //          }
        //      }
        //  }

        CodeNamespace ns = new CodeNamespace("Namespace1");
        ns.Imports.Add(new CodeNamespaceImport("System"));
        cu.Namespaces.Add(ns);

        // Full Verification Objects
        CodeTypeDeclaration class1 = new CodeTypeDeclaration();
        class1.Name = "Class1";

        ns.Types.Add(class1);

        AddScenario ("CheckFoo1");
        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[]));

        if (Supports (provider, GeneratorSupport.ParameterAttributes)) {
            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(new CodeArgumentReferenceExpression ("format"), 0));
        fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 1));
        fooMethod1.Statements.Add(CreateStatement(new CodeVariableReferenceExpression ("str"), 2));
       
        fooMethod1.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("str")));
    }
Пример #4
0
 protected override CodeMemberMethod Generate(CodeParameterDeclarationExpression[] parms)
 {
     var cons = gen.Constructor(parms, () => XlatConstructor(f.body));
     GenerateTupleParameterUnpackers(cons);
     LocalVariableGenerator.Generate(cons);
     return cons;
 }
Пример #5
0
 protected virtual CodeMemberMethod Generate(CodeParameterDeclarationExpression[] parms)
 {
     CodeMemberMethod method;
     if (isStatic)
     {
         method = gen.StaticMethod(fnName, parms, () => Xlat(f.body));
     }
     else
     {
         method = gen.Method(fnName, parms, () => Xlat(f.body));
     }
     GenerateTupleParameterUnpackers(method);
     LocalVariableGenerator.Generate(method);
     return method;
 }
Пример #6
0
        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) {
                          }
                      }
                  }");
        }
Пример #7
0
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var 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);

            var 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))));

            var class1 = new CodeTypeDeclaration() { 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"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { 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"))));
            var 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);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.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(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            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);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            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);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            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;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            var 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"")]
                  [assembly: System.CLSCompliantAttribute(false)]

                  namespace MyNamespace
                  {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;
                  
                      [System.Serializable()]
                      [System.Obsolete(""Don\'t use this Class"")]
                      public class MyClass
                      {
                          [System.Xml.Serialization.XmlElementAttribute()]
                          private string myField = ""hi!"";
              
                          [System.Obsolete(""Don\'t use this Constructor"")]
                          private MyClass()
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Property"")]
                          private string MyProperty
                          {
                              get
                              {
                                  return this.myField;
                              }
                          }
              
                          [System.Obsolete(""Don\'t use this Method"")]
                          [System.ComponentModel.Editor(""This"", ""That"")]
                          private 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)
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Function"")]
                          [return: System.Xml.Serialization.XmlIgnoreAttribute()]
                          [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")]
                          private string MyFunction()
                          {
                              return ""Return"";
                          }
              
                          [global::System.ObsoleteAttribute(""Don\'t use this Function"")]
                          [return: global::System.Xml.Serialization.XmlIgnoreAttribute()]
                          private void GlobalKeywordFunction()
                          {
                          }
              
                          [System.Serializable()]
                          public class NestedClass
                          {
                          }
                      }
              
                      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);
                          }
              
                          [System.CLSCompliantAttribute(false)]
                          public event System.EventHandler MyEvent;
              
                          private void b_Click(object sender, System.EventArgs e)
                          {
                          }
                      }
                  }");
        }
Пример #8
0
    public void PostMembersHook(Smoke *smoke, Smoke.Class *klass, CodeTypeDeclaration type)
    {
        if (Util.IsQObject(klass))
        {
            CodeMemberProperty emit = new CodeMemberProperty();
            emit.Name       = "Emit";
            emit.Attributes = MemberAttributes.Family | MemberAttributes.New | MemberAttributes.Final;
            emit.HasGet     = true;
            emit.HasSet     = false;

            string            signalsIfaceName = "I" + type.Name + "Signals";
            CodeTypeReference returnType       = new CodeTypeReference(signalsIfaceName);
            emit.Type = returnType;

            emit.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
                                                                     returnType,
                                                                     new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Q_EMIT")
                                                                     )));

            type.Members.Add(emit);

            string className = ByteArrayManager.GetString(klass->className);
            int    colon     = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix    = (colon != -1) ? className.Substring(0, colon) : string.Empty;

            IList typeCollection          = Data.GetTypeCollection(prefix);
            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration(signalsIfaceName);
            ifaceDecl.IsInterface = true;

            if (className != "QObject")
            {
                string parentClassName = ByteArrayManager.GetString(smoke->classes[smoke->inheritanceList[klass->parents]].className);
                colon  = parentClassName.LastIndexOf("::", StringComparison.Ordinal);
                prefix = (colon != -1) ? parentClassName.Substring(0, colon) : string.Empty;
                if (colon != -1)
                {
                    parentClassName = parentClassName.Substring(colon + 2);
                }

                string parentInterface = (prefix != string.Empty) ? prefix.Replace("::", ".") + "." : string.Empty;
                parentInterface += "I" + parentClassName + "Signals";

                ifaceDecl.BaseTypes.Add(new CodeTypeReference(parentInterface));
            }
            Dictionary <CodeSnippetTypeMember, CodeMemberMethod> signalEvents = new Dictionary <CodeSnippetTypeMember, CodeMemberMethod>();
            GetSignals(smoke, klass, delegate(string signature, string name, string typeName, IntPtr metaMethod)
            {
                CodeMemberMethod signal = new CodeMemberMethod();
                signal.Attributes       = MemberAttributes.Abstract;

                // capitalize the first letter
                StringBuilder builder = new StringBuilder(name);
                builder[0]            = char.ToUpper(builder[0]);
                string tmp            = builder.ToString();

                signal.Name = tmp;
                bool isRef;
                try
                {
                    if (typeName == string.Empty)
                    {
                        signal.ReturnType = new CodeTypeReference(typeof(void));
                    }
                    else
                    {
                        signal.ReturnType = Translator.CppToCSharp(typeName, out isRef);
                    }
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                    return;
                }

                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Q_SIGNAL",
                                                                             new CodeAttributeArgument(new CodePrimitiveExpression(signature)));
                signal.CustomAttributes.Add(attr);

                int argNum = 1;
                StringBuilder fullNameBuilder = new StringBuilder("Slot");
                GetMetaMethodParameters(metaMethod, delegate(string paramType, string paramName)
                {
                    if (paramName == string.Empty)
                    {
                        paramName = "arg" + argNum.ToString();
                    }
                    argNum++;

                    CodeParameterDeclarationExpression param;
                    try
                    {
                        short id = smoke->IDType(paramType);
                        CodeTypeReference paramTypeRef;
                        if (id > 0)
                        {
                            paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                        }
                        else
                        {
                            if (!paramType.Contains("::"))
                            {
                                id = smoke->IDType(className + "::" + paramType);
                                if (id > 0)
                                {
                                    paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                                }
                                else
                                {
                                    paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                                }
                            }
                            else
                            {
                                paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                            }
                        }
                        param = new CodeParameterDeclarationExpression(paramTypeRef, paramName);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                        return;
                    }
                    if (isRef)
                    {
                        param.Direction = FieldDirection.Ref;
                    }
                    signal.Parameters.Add(param);
                    if (argNum == 2)
                    {
                        fullNameBuilder.Append('<');
                    }
                    fullNameBuilder.Append(param.Type.BaseType);
                    fullNameBuilder.Append(',');
                });
                if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                {
                    fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                }
                ifaceDecl.Members.Add(signal);
                CodeSnippetTypeMember signalEvent = new CodeSnippetTypeMember();
                signalEvent.Name = signal.Name;
                CodeSnippetTypeMember existing = signalEvents.Keys.FirstOrDefault(m => m.Name == signal.Name);
                if (existing != null)
                {
                    CodeSnippetTypeMember signalEventToUse;
                    CodeMemberMethod signalToUse;
                    if (signal.Parameters.Count == 0)
                    {
                        signalEventToUse = existing;
                        signalToUse      = signalEvents[existing];
                    }
                    else
                    {
                        signalEventToUse = signalEvent;
                        signalToUse      = signal;
                    }
                    string suffix = signalToUse.Parameters.Cast <CodeParameterDeclarationExpression>().Last().Name;
                    if (suffix.StartsWith("arg") && suffix.Length > 3 && char.IsDigit(suffix[3]))
                    {
                        string lastType = signalToUse.Parameters.Cast <CodeParameterDeclarationExpression>().Last().Type.BaseType;
                        suffix          = lastType.Substring(lastType.LastIndexOf('.') + 1);
                    }
                    else
                    {
                        StringBuilder lastParamBuilder = new StringBuilder(suffix);
                        lastParamBuilder[0]            = char.ToUpper(lastParamBuilder[0]);
                        suffix = lastParamBuilder.ToString();
                    }
                    signalEventToUse.Text = signalEventToUse.Text.Replace(signalEventToUse.Name, signalEventToUse.Name += suffix);
                }
                signalEvent.Text = string.Format(@"
        public event {0} {1}
		{{
			add
			{{
                QObject.Connect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
			}}
			remove
			{{
                QObject.Disconnect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
			}}
		}}"        , fullNameBuilder, signalEvent.Name, signature, signature.Substring(signature.IndexOf('(')));
                signalEvents.Add(signalEvent, signal);
            });

            typeCollection.Add(ifaceDecl);
            foreach (KeyValuePair <CodeSnippetTypeMember, CodeMemberMethod> signalEvent in signalEvents)
            {
                CodeSnippetTypeMember          implementation = signalEvent.Key;
                CodeCommentStatementCollection comments       = new CodeCommentStatementCollection();
                foreach (CodeTypeMember current in from CodeTypeMember member in type.Members
                         where member.Name == implementation.Name
                         select member)
                {
                    if (comments.Count == 0)
                    {
                        comments.AddRange(current.Comments);
                    }
                    current.Name = "On" + current.Name;
                }
                signalEvent.Value.Comments.AddRange(comments);
                signalEvent.Key.Comments.AddRange(comments);
                type.Members.Add(signalEvent.Key);
            }
        }
    }
Пример #9
0
        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);
                          }
                      }
                  }");
        }
Пример #10
0
        private void AddEvent(Project currentAssembly,
                              CodeTypeDeclaration proxyClass, CodeClass interopFormClass,
                              CodeEvent evt, CodeTypeDeclaration proxyClassEventSinkInterface)
        {
            CodeDelegate2 delegate1 = null;

            try
            {
                delegate1 = (CodeDelegate2)currentAssembly.CodeModel.CodeTypeFromFullName(evt.Type.AsFullName);
            }
            catch (Exception exception2)
            {
                foreach (CodeElement element1 in evt.ProjectItem.FileCodeModel.CodeElements)
                {
                    if (element1.IsCodeType)
                    {
                        CodeType type1 = (CodeType)element1;
                        foreach (CodeElement element2 in type1.Children)
                        {
                            if ((element2.Kind == vsCMElement.vsCMElementDelegate) &
                                (String.Compare(element2.FullName, evt.Type.AsFullName, false) == 0))
                            {
                                delegate1 = (CodeDelegate2)element2;
                            }
                        }
                        continue;
                    }
                }
            }

            if (delegate1 == null)
            {
                this.DisplayWarning(string.Format(Resource.EventErrMsg, evt.Name, evt.Type.AsFullName));
            }
            else
            {
                CodeMemberMethod method1 = null;
                foreach (CodeTypeMember member1 in proxyClass.Members)
                {
                    if (String.Compare(member1.Name, "HookCustomEvents", false) == 0)
                    {
                        method1 = (CodeMemberMethod)member1;
                    }
                }
                if (method1 == null)
                {
                    method1            = new CodeMemberMethod();
                    method1.Name       = "HookCustomEvents";
                    method1.Attributes = MemberAttributes.Family | MemberAttributes.Override;
                    method1.Statements.Add(this.GetStatementCastFormInstance(interopFormClass));
                    proxyClass.Members.Add(method1);
                }
                CodeMemberEvent event1 = new CodeMemberEvent();
                event1.Attributes = MemberAttributes.Public;
                event1.Type       = new CodeTypeReference(evt.Type.AsFullName);
                event1.Name       = evt.Name;
                CodeMemberMethod method3 = new CodeMemberMethod();
                method3.Name = evt.Name;
                CodeTypeDelegate delegate2 = new CodeTypeDelegate(evt.Name + "Handler");
                bool             flag1     = false;
                CodeMemberMethod method2   = new CodeMemberMethod();
                method2.Name = "castFormInstance_" + evt.Name;
                CodeDelegateInvokeExpression expression1 = new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), event1.Name));
                foreach (CodeParameter parameter1 in delegate1.Parameters)
                {
                    CodeParameterDeclarationExpression expression2;
                    CodeArgumentReferenceExpression    expression3;
                    CodeParameterDeclarationExpression expression4;
                    if ((parameter1.Type.CodeType != null) && this.IsEventArgs(parameter1.Type.CodeType))
                    {
                        if (!flag1)
                        {
                            proxyClass.Members.Add(delegate2);
                            event1.Type = new CodeTypeReference(delegate2.Name);
                        }
                        expression4 = new CodeParameterDeclarationExpression("System.EventArgs", parameter1.Name);
                        expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name);
                        expression3 = new CodeArgumentReferenceExpression(expression4.Name);
                        event1.Comments.Add(new CodeCommentStatement(this.EVENT_ARGS_COMMENT));
                        method3.Comments.Add(new CodeCommentStatement(this.EVENT_ARGS_COMMENT));
                    }
                    else
                    {
                        if (!this.IsSupported(parameter1.Type))
                        {
                            this.DisplayWarning(String.Format(Resource.EventErrMsg2, parameter1.Type.AsFullName, evt.Name));
                            return;
                        }
                        expression4 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name);
                        expression2 = new CodeParameterDeclarationExpression(parameter1.Type.AsFullName, parameter1.Name);
                        expression3 = new CodeArgumentReferenceExpression(expression4.Name);
                    }
                    method3.Parameters.Add(expression4);
                    delegate2.Parameters.Add(expression4);
                    method2.Parameters.Add(expression2);
                    expression1.Parameters.Add(expression3);
                }
                method2.Statements.Add(expression1);
                method1.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodeVariableReferenceExpression("castFormInstance"), event1.Name), new CodeDelegateCreateExpression(event1.Type, new CodeThisReferenceExpression(), method2.Name)));
                proxyClassEventSinkInterface.Members.Add(method3);
                proxyClass.Members.Add(method2);
                proxyClass.Members.Add(event1);
            }
        }
Пример #11
0
        public void Fixup()
        {
            var type = ml_context.ChannelType;
            var od   = context.Operation;

            CodeMemberMethod cm = new CodeMemberMethod();

            type.Members.Add(cm);
            cm.Name       = "Begin" + od.Name;
            cm.Attributes = MemberAttributes.Public
                            | MemberAttributes.Final;

            var inArgs  = new List <CodeParameterDeclarationExpression> ();
            var outArgs = new List <CodeParameterDeclarationExpression> ();

            foreach (CodeParameterDeclarationExpression p in context.BeginMethod.Parameters)
            {
                inArgs.Add(p);
                cm.Parameters.Add(p);
            }
            inArgs.RemoveAt(inArgs.Count - 1);
            inArgs.RemoveAt(inArgs.Count - 1);

//			cm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (AsyncCallback)), "asyncCallback"));
//			cm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (object)), "userState"));
            cm.ReturnType = new CodeTypeReference(typeof(IAsyncResult));

            var argsDecl = new CodeVariableDeclarationStatement(
                typeof(object []),
                "args",
                new CodeArrayCreateExpression(typeof(object), inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray()));

            cm.Statements.Add(argsDecl);

            var args = new List <CodeExpression> ();

            args.Add(new CodePrimitiveExpression(od.Name));
            args.Add(new CodeVariableReferenceExpression("args"));
            args.Add(new CodeArgumentReferenceExpression("asyncCallback"));
            args.Add(new CodeArgumentReferenceExpression("userState"));

            CodeExpression call = new CodeMethodInvokeExpression(
                new CodeBaseReferenceExpression(),
                "BeginInvoke",
                args.ToArray());

            if (cm.ReturnType.BaseType == "System.Void")
            {
                cm.Statements.Add(new CodeExpressionStatement(call));
            }
            else
            {
                cm.Statements.Add(new CodeMethodReturnStatement(call));
            }

            // EndXxx() implementation

            cm            = new CodeMemberMethod();
            cm.Attributes = MemberAttributes.Public
                            | MemberAttributes.Final;
            type.Members.Add(cm);
            cm.Name = "End" + od.Name;

            var res = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(IAsyncResult)), "result");

            cm.Parameters.Add(res);

            cm.ReturnType = context.EndMethod.ReturnType;

            string resultArgName = "result";

            argsDecl = new CodeVariableDeclarationStatement(
                typeof(object []),
                "args",
                new CodeArrayCreateExpression(typeof(object), new CodePrimitiveExpression(outArgs.Count)));
            cm.Statements.Add(argsDecl);

            call = new CodeCastExpression(
                context.EndMethod.ReturnType,
                new CodeMethodInvokeExpression(
                    new CodeBaseReferenceExpression(),
                    "EndInvoke",
                    new CodePrimitiveExpression(od.Name),
                    new CodeVariableReferenceExpression("args"),
                    new CodeArgumentReferenceExpression(resultArgName)));

            if (cm.ReturnType.BaseType == "System.Void")
            {
                cm.Statements.Add(new CodeExpressionStatement(call));
            }
            else
            {
                cm.Statements.Add(new CodeMethodReturnStatement(call));
            }
        }
Пример #12
0
 protected override void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e)
 {
     Output.Write(e.Name);
     Output.Write(": ");
     OutputType(e.Type);
 }
    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);
        }

    }
Пример #14
0
 private static bool HasCustomMarshaler(CodeParameterDeclarationExpression parameter)
 {
     return(GetCustomMarshaler(parameter) != null);
 }
Пример #15
0
        public static void Generate(ModuleGenerator generator)
        {
            var nativeMethods = generator.Types.Single(t => t.Name.EndsWith("NativeMethods"));

            CodeTypeDeclaration overloads = new CodeTypeDeclaration();

            generator.Types.Add(overloads);
            overloads.UserData.Add("FileNameSuffix", ".Extensions");
            overloads.Name          = nativeMethods.Name;
            overloads.IsPartial     = true;
            overloads.Attributes    = MemberAttributes.Public | MemberAttributes.Final;
            nativeMethods.IsPartial = true;

            overloads.Name = nativeMethods.Name;

            foreach (var method in nativeMethods.Members.OfType <CodeMemberMethod>())
            {
                bool needsPatching = method
                                     .Parameters
                                     .OfType <CodeParameterDeclarationExpression>()
                                     .Any(p => HasCustomMarshaler(p));

                if (!needsPatching)
                {
                    continue;
                }

                CodeMemberMethod customMethod = new CodeMemberMethod();
                overloads.Members.Add(customMethod);
                customMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                customMethod.Name       = method.Name;
                customMethod.ReturnType = method.ReturnType;

                bool hasReturnValue = customMethod.ReturnType != null &&
                                      customMethod.ReturnType.BaseType != "System.Void";

                var invokeStatement = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(nativeMethods.Name),
                        method.Name));

                if (!hasReturnValue)
                {
                    customMethod.Statements.Add(invokeStatement);
                }
                else
                {
                    var resultStatement = new CodeVariableDeclarationStatement(
                        customMethod.ReturnType,
                        "returnValue",
                        invokeStatement);

                    customMethod.Statements.Add(resultStatement);
                }

                foreach (CodeParameterDeclarationExpression parameter in method.Parameters)
                {
                    var customParameter =
                        new CodeParameterDeclarationExpression(
                            parameter.Type,
                            parameter.Name);
                    customParameter.Direction = parameter.Direction;

                    customMethod.Parameters.Add(customParameter);

                    var marshalerAttribute = GetCustomMarshaler(parameter);

                    if (marshalerAttribute != null)
                    {
                        Debug.Assert(marshalerAttribute.Name.EndsWith("MarshalAsAttribute"), "Marshaler");
                        var marshaler = ((CodeTypeOfExpression)marshalerAttribute.Arguments[1].Value).Type;

                        parameter.CustomAttributes.Clear();
                        bool marshalInput  = parameter.Direction == FieldDirection.In || parameter.Direction == FieldDirection.Ref;
                        bool marshalOutput = parameter.Direction == FieldDirection.Out || parameter.Direction == FieldDirection.Ref;

                        // Create the marshaler
                        // ICustomMarshaler [paramName]marshaler = [Marshaler].GetInstance(null);
                        customMethod.Statements.Insert(0,
                                                       new CodeVariableDeclarationStatement(
                                                           new CodeTypeReference(typeof(ICustomMarshaler)),
                                                           parameter.Name + "Marshaler",
                                                           new CodeMethodInvokeExpression(
                                                               new CodeMethodReferenceExpression(
                                                                   new CodeTypeReferenceExpression(marshaler),
                                                                   "GetInstance"),
                                                               new CodePrimitiveExpression(null))));

                        // If the variable is [in] or [ref],
                        // marshal the type from managed to unmanaged,
                        // else, initialize to IntPtr.Zero
                        if (marshalInput)
                        {
                            customMethod.Statements.Insert(1,
                                                           new CodeVariableDeclarationStatement(
                                                               new CodeTypeReference(typeof(IntPtr)),
                                                               parameter.Name + "Native",
                                                               new CodeMethodInvokeExpression(
                                                                   new CodeMethodReferenceExpression(
                                                                       new CodeVariableReferenceExpression(parameter.Name + "Marshaler"),
                                                                       "MarshalManagedToNative"),
                                                                   new CodeArgumentReferenceExpression(
                                                                       parameter.Name))));
                        }
                        else
                        {
                            customMethod.Statements.Insert(1,
                                                           new CodeVariableDeclarationStatement(
                                                               new CodeTypeReference(typeof(IntPtr)),
                                                               parameter.Name + "Native",
                                                               new CodePropertyReferenceExpression(
                                                                   new CodeTypeReferenceExpression(typeof(IntPtr)),
                                                                   "Zero")));
                        }

                        // Invoke the method with the base type
                        invokeStatement.Parameters.Add(
                            new CodeDirectionExpression(
                                parameter.Direction,
                                new CodeVariableReferenceExpression(parameter.Name + "Native")));

                        // Convert from unmanaged to managed, if required
                        if (marshalOutput)
                        {
                            customMethod.Statements.Add(
                                new CodeAssignStatement(
                                    new CodeArgumentReferenceExpression(parameter.Name),
                                    new CodeCastExpression(
                                        parameter.Type,
                                        new CodeMethodInvokeExpression(
                                            new CodeMethodReferenceExpression(
                                                new CodeVariableReferenceExpression(parameter.Name + "Marshaler"),
                                                "MarshalNativeToManaged"),
                                            new CodeArgumentReferenceExpression(
                                                parameter.Name + "Native")))));

                            customMethod.Statements.Add(
                                new CodeMethodInvokeExpression(
                                    new CodeMethodReferenceExpression(
                                        new CodeVariableReferenceExpression(parameter.Name + "Marshaler"),
                                        "CleanUpNativeData"),
                                    new CodeArgumentReferenceExpression(
                                        parameter.Name + "Native")));
                        }

                        // Set the unmanaged type to the primitive
                        parameter.Type = new CodeTypeReference(typeof(IntPtr));
                    }
                    else
                    {
                        invokeStatement.Parameters.Add(
                            new CodeDirectionExpression(
                                parameter.Direction,
                                new CodeArgumentReferenceExpression(parameter.Name)));
                    }
                }

                if (hasReturnValue)
                {
                    customMethod.Statements.Add(
                        new CodeMethodReturnStatement(
                            new CodeVariableReferenceExpression("returnValue")));
                }
            }
        }
        private static CodeMemberMethod DeclareConvertToTargetMethod(Type toTargetType, string methodName, CodeParameterDeclarationExpression from)
        {
            var method = methodName.DeclareMethod(toTargetType, MemberAttributes.Public | MemberAttributes.Static, from);

            return(method);
        }
Пример #17
0
        private static CodeTypeDeclaration BuildDatabaseAccessHandlerFacadeType(KnownDibixTypes dbx, Type databaseAccessorType)
        {
            string typeName = databaseAccessorType.Name + "DatabaseAccessHandlerFacade"; // CommandHandlerFacade
            CodeTypeDeclaration typedecl = new CodeTypeDeclaration()
            {
                Name    = typeName,
                IsClass = true,
                //Attributes = MemberAttributes.Final | MemberAttributes.Assembly,// dont use it for now! MemberAttributes.Public
            };

            typedecl.TypeAttributes = (typedecl.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NestedAssembly;


            //typedecl.Comments.Add(new CodeCommentStatement("Generated (at:" + DateTime.UtcNow + ")", true));
            typedecl.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.ComponentModel.DescriptionAttribute)), new CodeAttributeArgument(new_CodePrimitiveExpression("Generated (at:" + DateTime.UtcNow + ")"))));

            foreach (MethodInfo accessMethod in databaseAccessorType.GetMethods(BindingFlags.Public | BindingFlags.Static))
            {
                ParameterInfo[] acessMethodParameters = accessMethod.GetParameters();
                if (acessMethodParameters.Length == 0)
                {
                    throw new StoreLakeSdkException("Access method signature not correct. Method:" + accessMethod.Name + ", Type:" + databaseAccessorType.FullName);
                }

                // first parameter must be of type 'IDatabaseAccessorFactory'
                if (acessMethodParameters[0].ParameterType.Name != "IDatabaseAccessorFactory")
                {
                    throw new StoreLakeSdkException("Access method parameter signature not correct. Parameter:" + acessMethodParameters[0].Name + ", Method:" + accessMethod.Name + ", Type:" + databaseAccessorType.FullName);
                }

                CodeMemberMethod code_method = new CodeMemberMethod()
                {
                    Name       = accessMethod.Name,
                    Attributes = MemberAttributes.Public
                };
                typedecl.Members.Add(code_method);
                code_method.ReturnType = new CodeTypeReference(accessMethod.ReturnType);
                code_method.Statements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(NotImplementedException)))));

                code_method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(DataSet), "db"));

                if (acessMethodParameters.Length > 1)
                {
                    // second parameter can be 'long actioncontextid'
                    for (int parameter_index = 1; parameter_index < acessMethodParameters.Length; parameter_index++)
                    {
                        ParameterInfo accessMethodParameter = acessMethodParameters[parameter_index];
                        Type          parameterType         = accessMethodParameter.ParameterType.IsByRef ? accessMethodParameter.ParameterType.GetElementType() : accessMethodParameter.ParameterType;

                        CodeTypeReference parameterTypeRef;
                        if (IsUDT(dbx, parameterType))
                        {
                            //parameterType = typeof(IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>);
                            parameterTypeRef = CreateUdtParameterType(parameterType);
                        }
                        else
                        {
                            string accessParameterTypeName = TypeNameAsText(parameterType);
                            parameterTypeRef = new CodeTypeReference(parameterType);
                        }

                        CodeParameterDeclarationExpression prm_decl = new CodeParameterDeclarationExpression(parameterTypeRef, accessMethodParameter.Name);
                        code_method.Parameters.Add(prm_decl);
                        prm_decl.Direction = accessMethodParameter.IsOut
                                                    ? FieldDirection.Out
                                                    : (accessMethodParameter.ParameterType.IsByRef) ? FieldDirection.Ref : FieldDirection.In;

                        if (accessMethodParameter.IsOut)
                        {
                        }
                    }
                }
            }

            return(typedecl);
        }
Пример #18
0
    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 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 override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // create a namespace
        CodeNamespace ns = new CodeNamespace ("NS");
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");
        cu.Namespaces.Add (ns);

        // create a class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Test";
        class1.IsClass = true;
        ns.Types.Add (class1);


        // create method to test casting enum -> int
        //     GENERATE (C#):
        //        public int EnumToInt(System.Windows.Forms.AnchorStyles enum1) {
        //            return ((int)(enum1));
        //        }
        AddScenario ("CheckEnumToInt1", "Check the return value of EnumToInt() with a single flag");
        AddScenario ("CheckEnumToInt2", "Check the return value of EnumToInt() with multiple flags");
        CodeMemberMethod enumToInt = new CodeMemberMethod ();
        enumToInt.Name = "EnumToInt";
        enumToInt.ReturnType = new CodeTypeReference (typeof (int));
        enumToInt.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (System.Windows.Forms.AnchorStyles), "enum1");
        enumToInt.Parameters.Add (param);
        enumToInt.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeArgumentReferenceExpression ("enum1"))));
        class1.Members.Add (enumToInt);

        // create method to test casting enum -> int
        //     GENERATE (C#):
        //       public virtual int CastReturnValue(string value) {
        //          float val = System.Single.Parse(value, System.Globalization.CultureInfo.InvariantCulture);
        //          return ((int) val);
        //       }
        AddScenario ("CheckCastReturnValue", "Check the return value of CastReturnValue()");
        CodeMemberMethod castReturnValue = new CodeMemberMethod ();
        castReturnValue.Name = "CastReturnValue";
        castReturnValue.ReturnType = new CodeTypeReference (typeof (int));
        castReturnValue.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression strParam = new CodeParameterDeclarationExpression (typeof (string), "value");
        castReturnValue.Parameters.Add (strParam);
        castReturnValue.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "val",
                    CDHelper.CreateMethodInvoke (new CodeTypeReferenceExpression (new CodeTypeReference ("System.Int32")), // F#: Type conversion "int -> float" is not a type-cast!
                        "Parse", new CodeArgumentReferenceExpression ("value"),
                        new CodePropertyReferenceExpression (new CodeTypeReferenceExpression ("System.Globalization.CultureInfo"),
                            "InvariantCulture"))));
        castReturnValue.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new CodeVariableReferenceExpression ("val"))));
        class1.Members.Add (castReturnValue);


        // create method to test casting interface -> class
        //     GENERATE (C#):
        //        public string CastInterface(System.ICloneable value) {
        //            return ((string)(value));
        //        }
        AddScenario ("CheckCastInterface", "Check the return value of CastInterface()");
        CodeMemberMethod castInterface = new CodeMemberMethod ();
        castInterface.Name = "CastInterface";
        castInterface.ReturnType = new CodeTypeReference (typeof (string));
        castInterface.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression interfaceParam = new CodeParameterDeclarationExpression (typeof (System.ICloneable), "value");
        castInterface.Parameters.Add (interfaceParam);
        castInterface.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (string), new CodeArgumentReferenceExpression ("value"))));
        class1.Members.Add (castInterface);

        // create method to test casting value type -> reference type
        //     GENERATE (C#):
        //         public object ValueToReference(int value) {
        //             return ((object)(value));
        //         }
        AddScenario ("CheckValueToReference", "Check the return value of ValueToReference()");
        CodeMemberMethod valueToReference = new CodeMemberMethod ();
        valueToReference.Name = "ValueToReference";
        valueToReference.ReturnType = new CodeTypeReference (typeof (System.Object));
        valueToReference.Attributes = MemberAttributes.Public;
        CodeParameterDeclarationExpression valueParam = new CodeParameterDeclarationExpression (typeof (int), "value");
        valueToReference.Parameters.Add (valueParam);
        valueToReference.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (typeof (System.Object), new CodeArgumentReferenceExpression ("value"))));
        class1.Members.Add (valueToReference);

    }
Пример #21
0
    public CodeMemberMethod GenerateBasicMethodDefinition(Smoke* smoke, Smoke.Method* method, string cppSignature,
	                                                      CodeTypeReference iface)
    {
        // do we actually want that method?
        string className = ByteArrayManager.GetString(smokeClass->className);
        string completeSignature = className + "::" + cppSignature;
        if (translator.ExcludedMethods.Any(regex => regex.IsMatch(completeSignature)))
        {
            return null;
        }

        CodeParameterDeclarationExpressionCollection args = new CodeParameterDeclarationExpressionCollection();
        int count = 1;
        bool isRef;

        // make instance operators static and bring the arguments in the correct order
        string methName = ByteArrayManager.GetString(smoke->methodNames[method->name]);
        bool isOperator = false;
        string explicitConversionType = null;
        if (methName.StartsWith("operator"))
        {
            string op = methName.Substring(8);
            if (unsupportedOperators.Contains(op))
            {
                // not supported
                Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                return null;
            }

            if (op == "<<")
            {
                methName = "Write";
            }
            else if (op == ">>")
            {
                methName = "Read";
            }

            // binary/unary operator
            if (binaryOperators.Contains(op) || unaryOperators.Contains(op))
            {
                // instance operator
                if (smoke->classes[method->classId].size > 0)
                {
                    if (op == "*" && method->numArgs == 0 || (op == "++" || op == "--") && method->numArgs == 1)
                    {
                        // dereference operator and postfix in-/decrement operator are not supported
                        Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                        return null;
                    }

                    try
                    {
                        CodeParameterDeclarationExpression exp =
                            new CodeParameterDeclarationExpression(translator.CppToCSharp(className, type, out isRef), "one");
                        args.Add(exp);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                        return null;
                    }
                }
                else
                {
                    // global operator
                    if (op == "*" && method->numArgs == 0 || (op == "++" || op == "--") && method->numArgs == 2)
                    {
                        // dereference operator and postfix in-/decrement operator are not supported
                        Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                        return null;
                    }
                }
                isOperator = true;
            }
            else if (op[0] == ' ')
            {
                // conversion operator
                explicitConversionType = op.Substring(1);
                if (explicitConversionType.Contains("QVariant"))
                {
                    return null;
                }
                try
                {
                    explicitConversionType = translator.CppToCSharp(explicitConversionType, type, out isRef).GetStringRepresentation();
                    if (smoke->classes[method->classId].size > 0)
                    {
                        CodeParameterDeclarationExpression exp =
                            new CodeParameterDeclarationExpression(translator.CppToCSharp(className, type, out isRef), "value");
                        args.Add(exp);
                    }
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                    return null;
                }
                isOperator = true;
            }
        }

        // translate return type
        CodeTypeReference returnType;
        try
        {
            returnType = translator.CppToCSharp(smoke->types + method->ret, type, out isRef);
        }
        catch (NotSupportedException)
        {
            Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
            return null;
        }

        CodeMemberMethod cmm;
        if ((method->flags & (uint) Smoke.MethodFlags.mf_ctor) > 0)
        {
            cmm = new CodeConstructor();
            cmm.Attributes = 0; // initialize to 0 so we can do |=
            ((CodeConstructor) cmm).ChainedConstructorArgs.Add(new CodeSnippetExpression("(System.Type) null"));
        }
        else
        {
            cmm = new CodeMemberMethod();
            cmm.Attributes = 0; // initialize to 0 so we can do |=

            string csName = methName;
            if (!isOperator && methName != "finalize")
            {
                // capitalize the first letter
                StringBuilder builder = new StringBuilder(csName);
                builder[0] = char.ToUpper(builder[0]);
                string tmp = builder.ToString();

                // If the new name clashes with a name of a type declaration, keep the lower-case name.
                var typesWithSameName = from member in data.GetAccessibleMembers(smokeClass)
                                        where member.Type == MemberTypes.NestedType && member.Name == tmp
                                        select member;

                var propertiesWithSameName = (from member in data.GetAccessibleMembers(smokeClass)
                                              where member.Type == MemberTypes.Property && member.Name == tmp
                                              select member).ToList();

                if (iface != null && propertiesWithSameName.Count() == 1 &&
                    (method->flags & (uint) Smoke.MethodFlags.mf_protected) == 0 &&
                    (method->flags & (uint) Smoke.MethodFlags.mf_virtual) == 0)
                {
                    cmm.PrivateImplementationType = iface;
                    csName = tmp;
                }
                else
                {
                    if (propertiesWithSameName.Any())
                    {
                        if ((method->flags & (uint) Smoke.MethodFlags.mf_virtual) == 0)
                        {
                            Debug.Print(
                                "  |--Conflicting names: method/(type or property): {0} in class {1} - keeping original method name", tmp,
                                className);
                        }
                        else
                        {
                            csName = tmp;
                        }
                    }
                    else if (typesWithSameName.Any())
                    {
                        Debug.Print("  |--Conflicting names: method/classname: {0} in class {1} - keeping original method name", tmp,
                                    className);
                    }
                    else
                    {
                        csName = tmp;
                    }
                }
            }

            if (explicitConversionType != null)
            {
                cmm.Name = "explicit operator " + explicitConversionType;
                cmm.ReturnType = new CodeTypeReference(" ");
            }
            else
            {
                cmm.Name = csName;
                cmm.ReturnType = returnType;
            }
        }

        // translate arguments
        string[] methodArgs = this.GetMethodArgs(smoke, method);
        for (short* typeIndex = smoke->argumentList + method->args; *typeIndex > 0; typeIndex++)
        {
            try
            {
                args.Add(this.GetArgument(smoke, typeIndex, methodArgs, args, ref count));
            }
            catch (NotSupportedException)
            {
                Debug.Print("  |--Won't wrap method {0}::{1}", className, cppSignature);
                return null;
            }
        }
        this.RemovePreviousOverload(args, cmm.Name);

        // for destructors we already have this stuff set
        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) == 0)
        {
            // set access
            if ((method->flags & (uint) Smoke.MethodFlags.mf_protected) > 0)
            {
                cmm.Attributes |= MemberAttributes.Family;
            }
            else
            {
                cmm.Attributes |= MemberAttributes.Public;
            }

            if (isOperator)
            {
                cmm.Attributes |= MemberAttributes.Final | MemberAttributes.Static;
            }
            else if (cmm.Name == "ToString" && args.Count == 0 && cmm.ReturnType.BaseType == "System.String")
            {
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            }
            else
            {
                if ((method->flags & (uint) Smoke.MethodFlags.mf_static) > 0)
                {
                    cmm.Attributes |= MemberAttributes.Static;
                }
                else
                {
                    // virtual/final
                    MemberAttributes access;
                    bool foundInInterface;
                    bool isOverride = MethodOverrides(smoke, method, out access, out foundInInterface);

                    // methods that have to be implemented from interfaces can't override anything
                    if (iface == null && isOverride)
                    {
                        cmm.Attributes = access | MemberAttributes.Override;
                    }
                    else if (foundInInterface)
                    {
                        cmm.Attributes = access;
                    }

                    if ((method->flags & (uint) Smoke.MethodFlags.mf_purevirtual) > 0)
                    {
                        if (!m_internalImplementation)
                        {
                            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Abstract;

                            // The code generator doesn't like MemberAttributes.Abstract | MemberAttributes.Override being set.
                            if (isOverride && !type.IsInterface)
                            {
                                cmm.ReturnType.BaseType = "override " + cmm.ReturnType.BaseType == "System.Void"
                                                          	? "void"
                                                          	: cmm.ReturnType.BaseType;
                            }
                        }
                        else
                        {
                            cmm.Attributes |= MemberAttributes.Override;
                        }
                    }

                    if ((method->flags & (uint) Smoke.MethodFlags.mf_virtual) == 0 &&
                        (method->flags & (uint) Smoke.MethodFlags.mf_purevirtual) == 0 &&
                        !isOverride)
                    {
                        cmm.Attributes |= MemberAttributes.Final | MemberAttributes.New;
                    }
                }
            }
        }
        else
        {
            // hack, so we don't have to use CodeSnippetTypeMember to generator the destructor
            cmm.ReturnType = new CodeTypeReference(" ");
        }

        // add the parameters
        foreach (CodeParameterDeclarationExpression exp in args)
        {
            cmm.Parameters.Add(exp);
        }
        this.DocumentMemberFromInterface(iface, cmm);
        this.DistributeMethod(cmm);
        if (PostMethodDefinitionHooks != null)
        {
            PostMethodDefinitionHooks(smoke, method, cmm, this.type);
        }
        this.CorrectParameterNames(cmm);
        return cmm;
    }
Пример #22
0
        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) {

        // 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
        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.Obsolete("Don\'t use this Method")]
        //         [System.ComponentModel.Editor("This", "That")]
        //         public void MyMethod(string blah, 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");

        method1.Parameters.Add (param1);
        CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit");

        method1.Parameters.Add (param2);
        class1.Members.Add (method1);

        // 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);

        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);
        }

    }
Пример #24
0
        private static void BuildEndMethod(
            CodeTypeDeclaration declaration,
            string methodName,
            string rpcMethodName,
            Type[] argTypes,
            string[] argNames,
            Type returnType,
            Type implementationType)
        {
            string endMethodName = "";

            CodeMemberMethod cmm = new CodeMemberMethod();

            // set the attributes and name
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            if (methodName.StartsWith(DEFAULT_END) == true)
            {
                // strip method name prefix
                cmm.Name = methodName.Substring(DEFAULT_END.Length, methodName.Length - DEFAULT_END.Length);
            }
            endMethodName = String.Format(CultureInfo.InvariantCulture, "{0}{1}", DEFAULT_END, methodName);

            cmm.Name = endMethodName;

            //!cmm.ImplementationTypes.Add(implementationType);

            // set the return type
            CodeTypeReference ctrReturn = new CodeTypeReference(returnType);

            cmm.ReturnType = ctrReturn;

            // set the parameter list (always a single IAsyncResult)
            CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression();

            cpde.Name = DEFAULT_RESULT;
            cpde.Type = new CodeTypeReference(typeof(System.IAsyncResult));

            cmm.Parameters.Add(cpde);

            // generate the method body:

            // if non-void return, declared locals for processing return value
            if (returnType != typeof(void))
            {
                // add some local variables:
                MakeTempVariable(cmm, typeof(System.Object));
                MakeReturnVariable(cmm, returnType);
            }

            // construct a call to the base EndInvoke method

            CodeThisReferenceExpression ctre = new CodeThisReferenceExpression();

            CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(ctre, "EndInvoke");

            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();

            cmie.Method = cmre;
            cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_RESULT));

            CodeIndexerExpression cie = new CodeIndexerExpression();

            cie.TargetObject = cmie;
            cie.Indices.Add(new CodePrimitiveExpression(0));

            if (returnType != typeof(void))
            {
                // assign the result to tempRetVal
                CodeAssignStatement casTemp = new CodeAssignStatement();
                casTemp.Left = new CodeVariableReferenceExpression(DEFAULT_TEMP);
                //!casTemp.Right = cie;
                casTemp.Right = cmie;

                cmm.Statements.Add(casTemp);
            }
            else
            {
                // discard return type
                //!cmm.Statements.Add(cie);
                cmm.Statements.Add(cmie);
            }

            MakeReturnStatement(cmm, returnType);

            // add the finished method to the type
            declaration.Members.Add(cmm);
        }
Пример #25
0
        public CodeTypeDeclaration BuildDomainServiceInterface(String DataLayerNamespace, String DataBaseName, TSQL.Table table)
        {
            String FullEntityTypeName        = DataLayerNamespace + "." + DataBaseName + "." + table.Name;
            CodeTypeDeclaration ctdInterface = new CodeTypeDeclaration("I" + table.Name + "DomainService");
            CodeTypeReference   IEnumEntity  = new CodeTypeReference("IEnumerable<" + FullEntityTypeName + ">");
            CodeTypeReference   IIntReturn   = new CodeTypeReference("System.Int32");
            CodeTypeReference   IEntity      = new CodeTypeReference(FullEntityTypeName);
            CodeTypeReference   IEntityOrder = new CodeTypeReference("Func<" + FullEntityTypeName + ",Object>");
            CodeTypeReference   IEntityRule  = new CodeTypeReference("Func<" + FullEntityTypeName + ",Int32>");

            CodeParameterDeclarationExpression cpEntityQuery   = new CodeParameterDeclarationExpression(IEntity, "Query");
            CodeParameterDeclarationExpression cpEntityRule    = new CodeParameterDeclarationExpression(IEntityRule, "BusinessRule");
            CodeParameterDeclarationExpression cpEntityOrderBy = new CodeParameterDeclarationExpression(IEntityOrder, "Orderby");
            CodeParameterDeclarationExpression cpSkip          = new CodeParameterDeclarationExpression(new CodeTypeReference("Int32"), "Skip");
            CodeParameterDeclarationExpression cpTake          = new CodeParameterDeclarationExpression(new CodeTypeReference("Int32"), "Take");

            // Build Interface
            ctdInterface.Attributes  = MemberAttributes.Public;
            ctdInterface.IsInterface = true;
            ctdInterface.CustomAttributes.Add(new CodeAttributeDeclaration("ServiceContract"));


            CodeMemberMethod mSearch = this.CreateServiceInterfaceMethodBase("Search");

            mSearch.Parameters.AddRange(new CodeParameterDeclarationExpression[] { cpEntityQuery, cpSkip, cpTake });
            mSearch.ReturnType = IEnumEntity;

            CodeMemberMethod mFullSearch = this.CreateServiceInterfaceMethodBase("FullSearch");

            mFullSearch.Parameters.AddRange(new CodeParameterDeclarationExpression[] { cpEntityQuery, cpEntityOrderBy, cpSkip, cpTake });
            mFullSearch.ReturnType = IEnumEntity;

            CodeMemberMethod mUpdate = this.CreateServiceInterfaceMethodBase("Update");

            mUpdate.Parameters.Add(cpEntityQuery);
            mUpdate.ReturnType = IIntReturn;

            CodeMemberMethod mInsert = this.CreateServiceInterfaceMethodBase("Insert");

            mInsert.Parameters.Add(cpEntityQuery);
            mInsert.ReturnType = IIntReturn;

            CodeMemberMethod mDelete = this.CreateServiceInterfaceMethodBase("Delete");

            mDelete.Parameters.Add(cpEntityQuery);
            mDelete.ReturnType = IIntReturn;

            CodeMemberMethod mRule = this.CreateServiceInterfaceMethodBase("Rule");

            mRule.Parameters.Add(cpEntityRule);
            mRule.ReturnType = IIntReturn;

            ctdInterface.Members.Add(mSearch);
            ctdInterface.Members.Add(mFullSearch);
            ctdInterface.Members.Add(mUpdate);
            ctdInterface.Members.Add(mInsert);
            ctdInterface.Members.Add(mDelete);
            ctdInterface.Members.Add(mRule);

            return(ctdInterface);
        }
Пример #26
0
        public string CompileScript(ref Dictionary <string, Dictionary <string, object> > Exp_Vars, string Code,
                                    string NameClassScript, LanguageScript Language)
        {
            string returnData = null;

            _NameScript = NameClassScript;

            CodeDomProvider codeProvider = null;

            switch (Language)
            {
            case LanguageScript.C_Sharp:
                codeProvider = new CSharpCodeProvider();
                break;

            case LanguageScript.Visual_Basic:
                codeProvider = new VBCodeProvider();
                break;

            default:
                codeProvider = new CSharpCodeProvider();
                break;
            }

            CodeCompileUnit compileUnit = new CodeCompileUnit();

            CodeNamespace _NameSpace = new CodeNamespace("Tempur");

            // Add the new namespace to the compile unit.
            compileUnit.Namespaces.Add(_NameSpace);

            // Add the new namespace import for the System namespace.
            _NameSpace.Imports.Add(new CodeNamespaceImport("System"));
            _NameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            _NameSpace.Imports.Add(new CodeNamespaceImport("System.Reflection"));


            CodeTypeDeclaration _ClassTemp = new CodeTypeDeclaration(NameClassScript);

            // Add the new type to the namespace type collection.
            _NameSpace.Types.Add(_ClassTemp);

            foreach (KeyValuePair <string, Dictionary <string, object> > exp in Exp_Vars)
            {
                foreach (KeyValuePair <string, object> variable in exp.Value)
                {
                    CodeMemberField field1 = new CodeMemberField(variable.Value.GetType(), exp.Key + "_" + variable.Key);
                    field1.Attributes = MemberAttributes.Static;
                    CodePrimitiveExpression sd = new CodePrimitiveExpression(variable.Value);
                    field1.InitExpression = sd;
                    _ClassTemp.Members.Add(field1);
                }
            }

            CodeSnippetStatement codeSnippet = new CodeSnippetStatement(Code);
            char comilla = '"';


            CodeMemberMethod Method = new CodeMemberMethod
            {
                Name       = "MethodScript",
                Attributes = MemberAttributes.Public
            };
            CodeParameterDeclarationExpression param = null;

            switch (Language)
            {
            case LanguageScript.C_Sharp:
                param =
                    new CodeParameterDeclarationExpression("System.Collections.Generic.Dictionary<String, Dictionary<String, Object>>",
                                                           "Variables");
                break;

            case LanguageScript.Visual_Basic:
                param =
                    new CodeParameterDeclarationExpression("System.Collections.Generic.Dictionary(Of String, Dictionary(Of String, Object))",
                                                           "Variables");
                break;

            case LanguageScript.C_Plus_Plus:
                param =
                    new CodeParameterDeclarationExpression("System.Collections.Generic.Dictionary<String, Dictionary<String, Object>>",
                                                           "Variables");
                break;

            default:
                param =
                    new CodeParameterDeclarationExpression("System.Collections.Generic.Dictionary<String, Dictionary<String, Object>>",
                                                           "Variables");
                break;
            }

            //param.Direction = FieldDirection.Ref;
            Method.Parameters.Add(param);

            foreach (KeyValuePair <string, Dictionary <string, object> > exp in Exp_Vars)
            {
                string index = "";
                switch (Language)
                {
                case LanguageScript.C_Sharp:
                    index = "Variables[" + comilla + exp.Key + comilla + "]";
                    break;

                case LanguageScript.Visual_Basic:
                    index = "Variables(" + comilla + exp.Key + comilla + ")";
                    break;

                case LanguageScript.C_Plus_Plus:
                    index = "Variables[L" + comilla + exp.Key + comilla + "]";
                    break;

                default:
                    index = "Variables[" + comilla + exp.Key + comilla + "]";
                    break;
                }

                foreach (KeyValuePair <string, object> variable in exp.Value)
                {
                    CodeVariableReferenceExpression field1 = new CodeVariableReferenceExpression(exp.Key + "_" + variable.Key);

                    CodeArgumentReferenceExpression arg = new CodeArgumentReferenceExpression(index);

                    CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression("Convert"), "ChangeType", new CodeExpression[] {
                        new CodeArrayIndexerExpression(arg, new CodePrimitiveExpression(variable.Key)),
                        new CodeTypeOfExpression(new CodeTypeReference(variable.Value.GetType()))
                    });

                    CodeAssignStatement assin = new CodeAssignStatement(field1,
                                                                        new CodeCastExpression(variable.Value.GetType(),
                                                                                               cmie));
                    Method.Statements.Add(assin);
                }
            }

            Method.Statements.Add(codeSnippet);
            foreach (KeyValuePair <string, Dictionary <string, object> > exp in Exp_Vars)
            {
                foreach (KeyValuePair <string, object> variable in exp.Value)
                {
                    string index = "";
                    switch (Language)
                    {
                    case LanguageScript.C_Sharp:
                        index = "Variables[" + comilla + exp.Key + comilla + "]";
                        break;

                    case LanguageScript.Visual_Basic:
                        index = "Variables(" + comilla + exp.Key + comilla + ")";
                        break;

                    case LanguageScript.C_Plus_Plus:
                        index = "Variables[L" + comilla + exp.Key + comilla + "]";
                        break;

                    default:
                        index = "Variables[" + comilla + exp.Key + comilla + "]";
                        break;
                    }
                    CodeVariableReferenceExpression field1 = new CodeVariableReferenceExpression(exp.Key + "_" + variable.Key);
                    CodeArgumentReferenceExpression arg    = new CodeArgumentReferenceExpression(index);
                    CodeAssignStatement             assin  = new CodeAssignStatement(new CodeArrayIndexerExpression(arg,
                                                                                                                    new CodePrimitiveExpression(variable.Key)), field1);
                    Method.Statements.Add(assin);
                }
            }
            _ClassTemp.Members.Add(Method);


            CodeEntryPointMethod start = new CodeEntryPointMethod();

            _ClassTemp.Members.Add(start);

            //IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter("Script//" + NameClassScript, false), "    ");
            //// Generate source code using the code generator.

            //codeProvider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
            //// Close the output file.
            //tw.Close();

            //string PathDir = Environment.CurrentDirectory + "\\Script\\" + NameClassScript + ".dll";

            CompilerParameters parameters = new CompilerParameters
            {
                GenerateInMemory = true
            };

            CompilerResults results = codeProvider.CompileAssemblyFromDom(parameters, new CodeCompileUnit[] { compileUnit });

            if (results.Errors.Count > 0)
            {
                var errorMessage = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    errorMessage.AppendFormat("{0} {1}", error.Line,
                                              error.ErrorText);
                }
                returnData = errorMessage.ToString();
            }
            else
            {
                _Assembly = results.CompiledAssembly;
                classType = _Assembly.GetType("Tempur." + NameClassScript);;

                object o = classType.InvokeMember(null,
                                                  BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic |
                                                  BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);

                classType.InvokeMember("MethodScript", BindingFlags.DeclaredOnly |
                                       BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
                                       null, o, new object[] { Exp_Vars });
            }

            return(returnData);
        }
Пример #27
0
        public void Properties()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            // create a class
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Test";
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference(typeof(Exception)));
            ns.Types.Add(class1);

            CodeMemberField int1 = new CodeMemberField(typeof(int), "int1");
            class1.Members.Add(int1);

            CodeMemberField tempString = new CodeMemberField(typeof(string), "tempString");
            class1.Members.Add(tempString);

            // basic property with get/set
            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "prop1";
            prop1.Type = new CodeTypeReference(typeof(int));
            prop1.Attributes = MemberAttributes.Public;
            prop1.HasGet = true;
            prop1.HasSet = true;
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
            prop1.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("int1"), new CodeVariableReferenceExpression("value")));
            class1.Members.Add(prop1);

            // override Property
            CodeMemberProperty overrideProp = new CodeMemberProperty();
            overrideProp.Name = "Text";
            overrideProp.Type = new CodeTypeReference(typeof(string));
            overrideProp.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            overrideProp.HasGet = true;
            overrideProp.HasSet = true;
            overrideProp.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("tempString"), new CodeVariableReferenceExpression("value")));
            overrideProp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello World")));

            class1.Members.Add(overrideProp);

            foreach (MemberAttributes attrs in new[] { MemberAttributes.Private, MemberAttributes.Family, MemberAttributes.Assembly })
            {
                CodeMemberProperty configuredProp = new CodeMemberProperty();
                configuredProp.Name = attrs.ToString() + "Prop";
                configuredProp.Type = new CodeTypeReference(typeof(int));
                configuredProp.Attributes = attrs;
                configuredProp.HasGet = true;
                configuredProp.HasSet = true;
                configuredProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
                configuredProp.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("int1"), new CodeVariableReferenceExpression("value")));
                class1.Members.Add(configuredProp);
            }

            // Static property
            CodeMemberProperty staticProp = new CodeMemberProperty();
            staticProp.Name = "staticProp";
            staticProp.Type = new CodeTypeReference(typeof(int));
            staticProp.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            staticProp.HasGet = true;
            staticProp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(99)));
            class1.Members.Add(staticProp);

            // this reference
            CodeMemberMethod thisRef = new CodeMemberMethod();
            thisRef.Name = "thisRef";
            thisRef.ReturnType = new CodeTypeReference(typeof(int));
            thisRef.Attributes = MemberAttributes.Public;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "value");
            thisRef.Parameters.Add(param);

            thisRef.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "privProp1"), new CodeVariableReferenceExpression("value")));
            thisRef.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "privProp1")));
            class1.Members.Add(thisRef);

            // set value
            CodeMemberMethod setProp = new CodeMemberMethod();
            setProp.Name = "setProp";
            setProp.ReturnType = new CodeTypeReference(typeof(int));
            setProp.Attributes = MemberAttributes.Public;
            CodeParameterDeclarationExpression intParam = new CodeParameterDeclarationExpression(typeof(int), "value");
            setProp.Parameters.Add(intParam);

            setProp.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "prop1"), new CodeVariableReferenceExpression("value")));
            setProp.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("int1")));
            class1.Members.Add(setProp);

            AssertEqual(ns,
                @"Imports System
                  Namespace NS
                      Public Class Test
                          Inherits System.Exception
                          Private int1 As Integer
                          Private tempString As String
                          Public Overridable Property prop1() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Public Overrides Property Text() As String
                              Get
                                  Return ""Hello World""
                              End Get
                              Set
                                  tempString = value
                              End Set
                          End Property
                          Private Property PrivateProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Protected Overridable Property FamilyProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Friend Overridable Property AssemblyProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Public Shared ReadOnly Property staticProp() As Integer
                              Get
                                  Return 99
                              End Get
                          End Property
                          Public Overridable Function thisRef(ByVal value As Integer) As Integer
                              Me.privProp1 = value
                              Return Me.privProp1
                          End Function
                          Public Overridable Function setProp(ByVal value As Integer) As Integer
                              Me.prop1 = value
                              Return int1
                          End Function
                      End Class
                  End Namespace");
        }
Пример #28
0
        public CodeTypeDeclaration BuildDomainObject(String DataLayerNamespace, String DataBaseName, TSQL.TableViewTableTypeBase table)
        {
            String FullEntityDAL      = DataLayerNamespace + "." + DataBaseName + "." + table.Name + "DAL";
            String FullEntityTypeName = DataLayerNamespace + "." + DataBaseName + "." + table.Name;

            String TypeName    = table.Name + "DomainObject";
            String DalTypeName = FullEntityDAL;

            CodeTypeDeclaration ctdService   = FrameFactory.GetPartialClassFrame(TypeName);
            CodeTypeReference   IEnumEntity  = new CodeTypeReference("IEnumerable<" + FullEntityTypeName + ">");
            CodeTypeReference   IEntity      = new CodeTypeReference((FullEntityTypeName));
            CodeTypeReference   IIntReturn   = new CodeTypeReference("System.Int32");
            CodeTypeReference   IEntityOrder = new CodeTypeReference("Func<" + FullEntityTypeName + ",Object>");
            CodeTypeReference   IEntityRule  = new CodeTypeReference("Func<" + FullEntityTypeName + ",Int32>");
            CodeParameterDeclarationExpression cpEntityQuery   = new CodeParameterDeclarationExpression(IEntity, "Query");
            CodeParameterDeclarationExpression cpEntityRule    = new CodeParameterDeclarationExpression(IEntityRule, "BusinessRule");
            CodeParameterDeclarationExpression cpEntityOrderBy = new CodeParameterDeclarationExpression(IEntityOrder, "Orderby");
            CodeParameterDeclarationExpression cpSkip          = new CodeParameterDeclarationExpression(new CodeTypeReference("Int32"), "Skip");
            CodeParameterDeclarationExpression cpTake          = new CodeParameterDeclarationExpression(new CodeTypeReference("Int32"), "Take");

            CodeTypeReference ctrDal = new CodeTypeReference(DalTypeName);
            CodeVariableDeclarationStatement varDal = new CodeVariableDeclarationStatement(ctrDal, "dal", new CodeSnippetExpression(" new " + DalTypeName + "()"));

            #region [ Search Methods ]
            CodeMemberMethod mSearchBasic = this.CreateServiceMethodBase("Search");
            mSearchBasic.Parameters.AddRange(new CodeParameterDeclarationExpression[] { cpEntityQuery });
            mSearchBasic.Statements.Add(varDal);
            mSearchBasic.Statements.Add(new CodeSnippetExpression("return dal.SelectObjects(Query)"));
            mSearchBasic.ReturnType = IEnumEntity;
            ctdService.Members.Add(mSearchBasic);

            CodeMemberMethod mSearch = this.CreateServiceMethodBase("Search");
            mSearch.Parameters.AddRange(new CodeParameterDeclarationExpression[] { cpEntityQuery, cpSkip, cpTake });
            mSearch.Statements.Add(varDal);
            mSearch.Statements.Add(new CodeSnippetExpression("return dal.SelectObjects(Query).Skip(Skip).Take(Take)"));
            mSearch.ReturnType = IEnumEntity;
            ctdService.Members.Add(mSearch);

            CodeMemberMethod mFullSearch = this.CreateServiceMethodBase("FullSearch");
            mFullSearch.Parameters.AddRange(new CodeParameterDeclarationExpression[] { cpEntityQuery, cpEntityOrderBy, cpSkip, cpTake });
            mFullSearch.Statements.Add(varDal);
            mFullSearch.Statements.Add(new CodeSnippetExpression("return dal.SelectObjects(Query).OrderBy(Orderby).Skip(Skip).Take(Take)"));
            mFullSearch.ReturnType = IEnumEntity;
            ctdService.Members.Add(mFullSearch);
            #endregion

            #region [ OML Methods ]
            /// If the parameter object is a Table then Generate OML methods
            if (table.GetType() == typeof(TSQL.Table))
            {
                CodeMemberMethod mUpdate = this.CreateServiceMethodBase("Update");
                mUpdate.Parameters.Add(cpEntityQuery);
                mUpdate.Statements.Add(varDal);
                // mUpdate.Statements.Add(new CodeSnippetExpression(" return dal.Update(Query)"));
                mUpdate.Statements.Add(FuncAction("dal", "Update", "Query"));
                mUpdate.ReturnType = IIntReturn;
                ctdService.Members.Add(mUpdate);

                CodeMemberMethod mInsert = this.CreateServiceMethodBase("Insert");
                mInsert.Parameters.Add(cpEntityQuery);
                mInsert.Statements.Add(varDal);
                mInsert.Statements.Add(new CodeSnippetExpression("Int32 rCode = new Int32()"));
                mInsert.Statements.Add(new CodeSnippetExpression("rCode = dal.Insert(Query)"));
                mInsert.Statements.Add(new CodeSnippetExpression("return rCode"));
                mInsert.ReturnType = IIntReturn;
                ctdService.Members.Add(mInsert);



                CodeMemberMethod mDelete = this.CreateServiceMethodBase("Delete");
                mDelete.Parameters.Add(cpEntityQuery);
                mDelete.Statements.Add(varDal);
                mDelete.Statements.Add(new CodeSnippetExpression("return dal.Delete(Query)"));
                mDelete.ReturnType = IIntReturn;
                ctdService.Members.Add(mDelete);
            }
            #endregion

            #region [ Validation Methods ]
            CodeMemberMethod cmVal = this.CreateServiceMethodBase("ValidateNew");
            cmVal.Parameters.Add(cpEntityQuery);
            cmVal.Statements.AddRange(GraphAttributeSet.BuildValidationSetStatement(table));
            cmVal.Statements.Add(new CodeSnippetExpression("return bResult"));
            cmVal.ReturnType = new CodeTypeReference("Boolean");
            //ctdService.Members.Add(cmVal);
            #endregion

            return(ctdService);
        }
Пример #29
0
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var 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);

            var 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))));

            var class1 = new CodeTypeDeclaration() { 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"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { 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"))));
            var 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);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.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(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            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);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            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);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            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;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            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);

            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""),  _
                   Assembly: System.CLSCompliantAttribute(false)>

                  Namespace MyNamespace

                      <System.Serializable(),  _
                       System.Obsolete(""Don't use this Class"")>  _
                      Public Class [MyClass]

                          <System.Xml.Serialization.XmlElementAttribute()>  _
                          Private myField As String = ""hi!""

                          <System.Obsolete(""Don't use this Constructor"")>  _
                          Private Sub New()
                              MyBase.New
                          End Sub

                          <System.Obsolete(""Don't use this Property"")>  _
                          Private ReadOnly Property MyProperty() As String
                              Get
                                  Return Me.myField
                              End Get
                          End Property

                          <System.Obsolete(""Don't use this Method""),  _
                           System.ComponentModel.Editor(""This"", ""That"")>  _
                          Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer)
                          End Sub

                          <System.Obsolete(""Don't use this Function"")>  _
                          Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          <Global.System.ObsoleteAttribute(""Don't use this Function"")>  _
                          Private Sub GlobalKeywordFunction()
                          End Sub

                          <System.Serializable()>  _
                          Public Class NestedClass
                          End Class
                      End Class

                      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

                          <System.CLSCompliantAttribute(false)>  _
                          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");
        }
Пример #30
0
        override protected void PostHandleSignal(IDLInterface idlIntf, IDLSignal idlSignal, CodeCompileUnit unit, CodeNamespace ns, CodeTypeDeclaration typeInterface)
        {
            string nsName, intf;
            int    lastDot = idlIntf.Name.LastIndexOf('.');

            intf   = idlIntf.Name.Substring(lastDot + 1);
            nsName = CodeBuilderCommon.GetNamespace(idlIntf.Name, new InterfaceVisitor());
            CodeFieldReferenceExpression fieldrefCallback = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), CodeBuilderCommon.callback);
            CodeFieldReferenceExpression fieldrefTarget   = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), CodeBuilderCommon.targetName);
            CodeNamespace nsClient      = this.GetClientNamespace(unit, idlIntf.Name);
            CodeNamespace nsClientTypes = nsClient;

            if (this.typedeclCallbackInterface == null) // If no callback interface yet
            {
                CodeTypeReference typerefInterface = new CodeTypeReference(typeInterface.Name);

                // Declare callback interface and hold onto it in field.
                // * public interface I<interface>Callback
                // * {
                string nsWCFName, intfWCF;
                nsWCFName = CodeBuilderCommon.GetNamespace(idlIntf.Name, this.visitorType);
                intfWCF   = CodeBuilderCommon.GetName(idlIntf.Name, null);
                string callbackInterfaceName = CodeBuilderCommon.GetSignalCallbackInterfaceName(intfWCF);
                typedeclCallbackInterface             = new CodeTypeDeclaration(callbackInterfaceName);
                typedeclCallbackInterface.Attributes  = MemberAttributes.Public;
                typedeclCallbackInterface.IsInterface = true;
                ns.Types.Add(typedeclCallbackInterface);

                // * class <interface>CallbackClient : I<interface>Callback
                string            wcfCallbackClientName    = CodeBuilderCommon.GetSignalCompilableName(intfWCF) + "CallbackClient";
                CodeTypeReference typerefCallbackInterface = new CodeTypeReference(typedeclCallbackInterface.Name);

                CodeAttributeDeclaration attribdeclServiceContract = new CodeAttributeDeclaration(CodeBuilderCommon.typerefServiceContract,
                                                                                                  new CodeAttributeArgument("CallbackContract", new CodeTypeOfExpression(typerefCallbackInterface))
                                                                                                  );
                typeInterface.CustomAttributes.Add(attribdeclServiceContract);

                //string scopedCallbackInterfaceName = CodeBuilderCommon.GetScopedName(nsWCFName, proxyInterfaceName);
                //typedeclCallbackClient = new CodeTypeDeclaration(CodeBuilderCommon.GetSignalCallbackName(intf));
                typedeclCallbackClient = new CodeTypeDeclaration(wcfCallbackClientName);
                CodeTypeReference typerefWCFCallbackInterface = new CodeTypeReference(typedeclCallbackInterface.Name);
                typedeclCallbackClient.BaseTypes.Add(typerefWCFCallbackInterface);

                nsClientTypes.Types.Add(typedeclCallbackClient);

                // * public class <interface>Proxy : Udbus.WCF.Client.CallbackProxy< <wcf_contracts.interface>, <interface>CallbackClient >
                this.typedeclProxy = new CodeTypeDeclaration(CodeBuilderCommon.GetSignalProxyName(intfWCF));
                CodeTypeReference typerefCallbackProxy  = new CodeTypeReference(typeof(Udbus.WCF.Client.CallbackProxy <,>));
                CodeTypeReference typerefCallbackClient = new CodeTypeReference(typedeclCallbackClient.Name);
                typerefCallbackProxy.TypeArguments.Add(typerefInterface);
                typerefCallbackProxy.TypeArguments.Add(typerefCallbackClient);
                this.typedeclProxy.BaseTypes.Add(typerefCallbackProxy);

                AddProxyConstructors(this.typedeclProxy);

                nsClientTypes.Types.Add(this.typedeclProxy);
            } // Ends if no callback interface yet

            // Add signal property to Proxy.
            CodeMemberProperty propProxySignal = CodeBuilderCommon.CreateSignalEventProperty(idlSignal);

            propProxySignal.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodePropertyReferenceExpression proprefProxyInterface     = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ProxyInterface");
            CodePropertyReferenceExpression proprefProxyCallback      = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Callback");
            CodePropertyReferenceExpression proprefProxyCallbackEvent = new CodePropertyReferenceExpression(proprefProxyCallback, propProxySignal.Name);

            propProxySignal.GetStatements.Add(new CodeMethodReturnStatement(proprefProxyCallbackEvent));
            propProxySignal.SetStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(proprefProxyCallbackEvent, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null))
                                                                         , new CodeExpressionStatement(new CodeMethodInvokeExpression(proprefProxyInterface, CodeBuilderCommon.GetSignalRegisterFunction(idlSignal.Name)))
                                                                         ));
            propProxySignal.SetStatements.Add(new CodeAssignStatement(proprefProxyCallbackEvent, new CodePropertySetValueReferenceExpression()));
            this.typedeclProxy.Members.Add(propProxySignal);

            // Add callback method to callback interface.
            // * [System.ServiceModel.OperationContract(IsOneWay=true)]
            // * void On<signal>(<interface_ns>.<signal>Args args);
            CodeMemberMethod methodOnSignal = new CodeMemberMethod();

            methodOnSignal.Name = CodeBuilderCommon.GetSignalCallbackMethodName(idlSignal.Name);
            string signalArgsTypeName       = CodeBuilderCommon.GetSignalEventTypeName(idlSignal.Name);
            string scopedSignalArgsTypeName = CodeBuilderCommon.GetScopedName(nsName, signalArgsTypeName);
            CodeParameterDeclarationExpression paramdeclSignalArgs = new CodeParameterDeclarationExpression(scopedSignalArgsTypeName,
                                                                                                            CodeBuilderCommon.SignalArgsName);

            methodOnSignal.Parameters.Add(paramdeclSignalArgs);
            methodOnSignal.CustomAttributes.Add(CodeBuilderCommon.attribOperationContractOneWay);
            typedeclCallbackInterface.Members.Add(methodOnSignal);

            // Add registration method to wcf interface.
            // * [System.ServiceModel.OperationContract]
            // * void RegisterForStorageSpaceLow();
            CodeMemberMethod methodRegister = new CodeMemberMethod();

            methodRegister.Name = CodeBuilderCommon.GetSignalRegisterFunction(idlSignal.Name);
            methodRegister.CustomAttributes.Add(CodeBuilderCommon.attribOperationContract);
            typeInterface.Members.Add(methodRegister);

            // Add event to callback client implementation.

            // * private event System.EventHandler< <signal>Args > <signal>Event;
            CodeMemberEvent eventSignal = CodeBuilderCommon.CreateSignalEvent(idlSignal);

            typedeclCallbackClient.Members.Add(eventSignal);

            // * public virtual System.EventHandler< <signal>Args > <signal>
            // * {
            // *     get { return this.<signal>Event; }
            // *     set { this.<signal>Event = value; }
            // * }
            CodeMemberProperty propSignal = CodeBuilderCommon.CreateSignalEventProperty(idlSignal);

            propSignal.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeEventReferenceExpression eventrefSignal = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), eventSignal.Name);

            propSignal.GetStatements.Add(new CodeMethodReturnStatement(eventrefSignal));
            propSignal.SetStatements.Add(new CodeAssignStatement(eventrefSignal, new CodePropertySetValueReferenceExpression()));
            typedeclCallbackClient.Members.Add(propSignal);

            // * public void On<signal>(<ns>.<signal>Args args)
            // * {
            // *     if (this.<signal> != null)
            // *     {
            // *         this.<signal>(this, args);
            // *     }
            //}
            CodeMemberMethod methodSignal = new CodeMemberMethod();

            methodSignal.Name       = CodeBuilderCommon.GetSignalCallbackMethodName(idlSignal.Name);
            methodSignal.Attributes = MemberAttributes.Public;
            methodSignal.Parameters.Add(paramdeclSignalArgs);
            CodePropertyReferenceExpression proprefSignal = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), propSignal.Name);

            methodSignal.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(eventrefSignal, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null))
                                                                   , new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), eventrefSignal.EventName, new CodeThisReferenceExpression(), new CodeArgumentReferenceExpression(paramdeclSignalArgs.Name)))
                                                                   ));
            typedeclCallbackClient.Members.Add(methodSignal);
        }
Пример #31
0
        void CreateAsyncMethods()
        {
            CodeMemberMethod method = new CodeMemberMethod();
            CodeParameterDeclarationExpression arg;
            CodeMethodInvokeExpression         invoke;

            // public virtual System.IAsyncResult BeginProcessRequest(System.Web.HttpContext context, System.AsyncCallback cb, object data);
            method.ReturnType = new CodeTypeReference(typeof(IAsyncResult));
            method.Name       = "BeginProcessRequest";
            method.Attributes = MemberAttributes.Public;

            arg      = new CodeParameterDeclarationExpression();
            arg.Type = new CodeTypeReference(typeof(HttpContext));
            arg.Name = "context";
            method.Parameters.Add(arg);

            arg      = new CodeParameterDeclarationExpression();
            arg.Type = new CodeTypeReference(typeof(AsyncCallback));
            arg.Name = "cb";
            method.Parameters.Add(arg);

            arg      = new CodeParameterDeclarationExpression();
            arg.Type = new CodeTypeReference(typeof(object));
            arg.Name = "data";
            method.Parameters.Add(arg);

            invoke = new CodeMethodInvokeExpression(thisRef, "AsyncPageBeginProcessRequest");
            invoke.Parameters.Add(new CodeArgumentReferenceExpression("context"));
            invoke.Parameters.Add(new CodeArgumentReferenceExpression("cb"));
            invoke.Parameters.Add(new CodeArgumentReferenceExpression("data"));

            method.Statements.Add(new CodeMethodReturnStatement(invoke));
            mainClass.Members.Add(method);

            // public virtual void EndProcessRequest(System.IAsyncResult ar);
            method            = new CodeMemberMethod();
            method.ReturnType = new CodeTypeReference(typeof(void));
            method.Name       = "EndProcessRequest";
            method.Attributes = MemberAttributes.Public;

            arg      = new CodeParameterDeclarationExpression();
            arg.Type = new CodeTypeReference(typeof(IAsyncResult));
            arg.Name = "ar";
            method.Parameters.Add(arg);

            invoke = new CodeMethodInvokeExpression(thisRef, "AsyncPageEndProcessRequest");
            invoke.Parameters.Add(new CodeArgumentReferenceExpression("ar"));

            method.Statements.Add(invoke);
            mainClass.Members.Add(method);

            // public override void ProcessRequest(System.Web.HttpContext context);
            method            = new CodeMemberMethod();
            method.ReturnType = new CodeTypeReference(typeof(void));
            method.Name       = "ProcessRequest";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Override;

            arg      = new CodeParameterDeclarationExpression();
            arg.Type = new CodeTypeReference(typeof(HttpContext));
            arg.Name = "context";
            method.Parameters.Add(arg);

            invoke = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "ProcessRequest");
            invoke.Parameters.Add(new CodeArgumentReferenceExpression("context"));

            method.Statements.Add(invoke);
            mainClass.Members.Add(method);
        }
Пример #32
0
        override protected void PostHandleInterface(IDLInterface idlIntf, CodeCompileUnit unit, CodeNamespace ns, CodeTypeDeclaration typeInterface)
        {
            if (idlIntf.Signals == null || idlIntf.Signals.Count == 0) // If no signals
            {
                typeInterface.CustomAttributes.Add(CodeBuilderCommon.attribServiceContract);
            } // Ends if no signals

            // Add DbusServiceRelativeAddress constant to Constants class.
            // * public partial class Constants {
            CodeTypeDeclaration typedeclConstants = new CodeTypeDeclaration(CodeBuilderCommon.nameConstantsClass);

            typedeclConstants.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            typedeclConstants.IsPartial  = true;
            // *    public const string DbusServiceRelativeAddress = "<contract_name>";
            // * }

            CodeMemberField fieldRelativeAddress = new CodeMemberField(typeof(string), CodeBuilderCommon.nameRelativeAddress);

            fieldRelativeAddress.Attributes     = MemberAttributes.Const | MemberAttributes.Public;
            fieldRelativeAddress.InitExpression = new CodePrimitiveExpression(idlIntf.Name.Replace('.', '/'));
            typedeclConstants.Members.Add(fieldRelativeAddress);

            ns.Types.Add(typedeclConstants);

            CodeTypeReference typerefInterface      = new CodeTypeReference(CodeBuilderCommon.GetScopedName(ns.Name, typeInterface.Name));
            CodeTypeReference typerefInterfaceProxy = new CodeTypeReference(typeof(Udbus.WCF.Client.Proxy <>));

            typerefInterfaceProxy.TypeArguments.Add(typerefInterface);

            CodeTypeReference typerefProxy; // Worked out in following code...

            if (this.typedeclProxy == null) // If no proxy type defined yet
            {
                // Just knock up a nice vanilla one for consistency's sake.
                string nsWCFName, intfWCF;
                nsWCFName = CodeBuilderCommon.GetNamespace(idlIntf.Name, this.visitorType);
                intfWCF   = CodeBuilderCommon.GetName(idlIntf.Name, null);

                CodeTypeDeclaration typedeclProxy = new CodeTypeDeclaration(CodeBuilderCommon.GetSignalProxyName(intfWCF));
                typedeclProxy.BaseTypes.Add(typerefInterfaceProxy);

                AddProxyConstructors(typedeclProxy);

                CodeNamespace nsClient = this.GetClientNamespace(unit, idlIntf.Name);
                nsClient.Types.Add(typedeclProxy);

                typerefProxy = new CodeTypeReference(CodeBuilderCommon.GetScopedName(nsClient.Name, typedeclProxy.Name));
            }    // Ends if no proxy type defined yet
            else // Else added proxy type
            {
                // Grab holder of scoped type reference.
                string nsWCFClient = CodeBuilderCommon.GetNamespace(idlIntf.Name, new WCFClientVisitor());
                typerefProxy = new CodeTypeReference(CodeBuilderCommon.GetScopedName(nsWCFClient, this.typedeclProxy.Name));
            } // Ends else added proxy type

            // Reset helper types for next time.
            this.typedeclCallbackInterface = null;
            this.typedeclCallbackClient    = null;
            this.typedeclProxy             = null;

            // Add Proxy creation function to ProxyBuilder class via extension method.
            CodeTypeReference           typerefEndpointComponents     = new CodeTypeReference(typeof(Udbus.WCF.Client.DbusEndpointUriComponents));
            CodeTypeReferenceExpression typerefexprEndpointComponents = new CodeTypeReferenceExpression(typerefEndpointComponents);
            CodeTypeReference           typerefProxyManager           = new CodeTypeReference(typeof(Udbus.WCF.Client.ProxyManager));
            CodeTypeReferenceExpression typerefexprProxyManager       = new CodeTypeReferenceExpression(typerefProxyManager);
            CodeTypeReference           typerefProxyBuilder           = new CodeTypeReference(typeof(Udbus.WCF.Client.ProxyBuilder));
            CodeTypeReference           typerefProxyBuilderExtension  = new CodeTypeReference("this " + typerefProxyBuilder.BaseType); // No CodeDom support for extension methods. Awesome.
            CodeTypeReferenceExpression typerefexprProxyBuilder       = new CodeTypeReferenceExpression(typerefProxyBuilder);

            CodeTypeReferenceExpression        typerefexprConstants           = new CodeTypeReferenceExpression(CodeBuilderCommon.GetScopedName(ns.Name, typedeclConstants.Name));
            CodeParameterDeclarationExpression paramdeclInterfaceProxy        = new CodeParameterDeclarationExpression(typerefInterfaceProxy, proxy);
            CodeParameterDeclarationExpression paramdeclProxyManagerExtension = new CodeParameterDeclarationExpression(typerefProxyBuilderExtension, proxyBuilder);
            CodeParameterDeclarationExpression paramdeclEndpointUri           = new CodeParameterDeclarationExpression(typerefEndpointComponents, dbusEndpointUri);
            CodeArgumentReferenceExpression    argrefProxy       = new CodeArgumentReferenceExpression(proxy);
            CodeArgumentReferenceExpression    argrefEndpointUri = new CodeArgumentReferenceExpression(paramdeclEndpointUri.Name);
            CodeExpression exprRelativeAddress = new CodeFieldReferenceExpression(typerefexprConstants, fieldRelativeAddress.Name);
            CodeArgumentReferenceExpression argrefProxyBuilder    = new CodeArgumentReferenceExpression(proxyBuilder);
            CodePropertyReferenceExpression proprefBindingFactory = new CodePropertyReferenceExpression(argrefProxyBuilder, BindingFactory);

            // * static public partial class ProxyBuilderExtensions
            // * {
            CodeTypeDeclaration typedeclProxyBuilderExtensions = new CodeTypeDeclaration(CodeBuilderCommon.nameProxyBuilderExtensionsClass);

            typedeclProxyBuilderExtensions.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            typedeclProxyBuilderExtensions.IsPartial  = true;
            // http://stackoverflow.com/questions/6308310/creating-extension-method-using-codedom
            typedeclProxyBuilderExtensions.Attributes = MemberAttributes.Public;
            typedeclProxyBuilderExtensions.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, Environment.NewLine + "\tstatic"));
            typedeclProxyBuilderExtensions.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            // *     static public void Create(this Udbus.WCF.Client.ProxyBuilder proxyBuilder, out Udbus.WCF.Client.Proxy< <wcf_contract> > proxy
            // *         , Udbus.WCF.Client.DbusEndpointUriComponents dbusEndpointUri)
            // *     {
            // *         proxy = Udbus.WCF.Client.ProxyManager.Create< <wcf_contract> >(
            // *             dbusEndpointUri.CreateUri(<wcf_namespace>.wcf.Contracts.Constants.DbusServiceRelativeAddress)
            // *             , proxyBuilder.BindingFactory
            // *         );
            // *     }
            CodeMemberMethod methodCreateInterfaceProxyWithEndpoint = new CodeMemberMethod();

            methodCreateInterfaceProxyWithEndpoint.Name       = "Create";
            methodCreateInterfaceProxyWithEndpoint.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            paramdeclInterfaceProxy.Direction = FieldDirection.Out;
            methodCreateInterfaceProxyWithEndpoint.Parameters.Add(paramdeclProxyManagerExtension);
            methodCreateInterfaceProxyWithEndpoint.Parameters.Add(paramdeclInterfaceProxy);
            methodCreateInterfaceProxyWithEndpoint.Parameters.Add(paramdeclEndpointUri);
            // * dbusEndpointUri.CreateUri(<ns>.wcf.Contracts.Constants.DbusServiceRelativeAddress)
            CodeMethodInvokeExpression invokeCreateUri          = new CodeMethodInvokeExpression(argrefEndpointUri, CreateUri, exprRelativeAddress);
            CodeMethodInvokeExpression invokeProxyManagerCreate = new CodeMethodInvokeExpression(typerefexprProxyManager, "Create", invokeCreateUri, proprefBindingFactory);

            invokeProxyManagerCreate.Method.TypeArguments.Add(typerefInterface);
            methodCreateInterfaceProxyWithEndpoint.Statements.Add(
                new CodeAssignStatement(
                    argrefProxy
                    , invokeProxyManagerCreate
                    )
                );
            typedeclProxyBuilderExtensions.Members.Add(methodCreateInterfaceProxyWithEndpoint);

            // *     static public void Create(this Udbus.WCF.Client.ProxyBuilder proxyBuilder, out Udbus.WCF.Client.Proxy< <wcf_contract> > proxy)
            // *     {
            // *         proxyBuilder.Create(out proxy, Udbus.WCF.Client.DbusEndpointUriComponents.Create(proxyBuilder.AbsoluteUribuilder));
            // *     }
            CodeMemberMethod methodCreateInterfaceProxy = new CodeMemberMethod();

            methodCreateInterfaceProxy.Name       = "Create";
            methodCreateInterfaceProxy.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            methodCreateInterfaceProxy.Parameters.Add(paramdeclProxyManagerExtension);
            methodCreateInterfaceProxy.Parameters.Add(paramdeclInterfaceProxy);
            CodeMethodInvokeExpression invokeProxyManagerExtensionCreate = new CodeMethodInvokeExpression(
                argrefProxyBuilder
                , "Create"
                , new CodeDirectionExpression(FieldDirection.Out, argrefProxy)
                , new CodeMethodInvokeExpression(
                    typerefexprEndpointComponents
                    , "Create"
                    , new CodePropertyReferenceExpression(argrefProxyBuilder, AbsoluteUribuilder)
                    )
                );

            methodCreateInterfaceProxy.Statements.Add(invokeProxyManagerExtensionCreate);
            typedeclProxyBuilderExtensions.Members.Add(methodCreateInterfaceProxy);

            CodeParameterDeclarationExpression paramdeclProxy = new CodeParameterDeclarationExpression(typerefProxy, proxy);

            paramdeclProxy.Direction = FieldDirection.Out;

            // * public static void Create(this Udbus.WCF.Client.ProxyBuilder proxyBuilder, out <namespace>.Contracts.Clients.<interface>Proxy proxy, Udbus.WCF.Client.DbusEndpointUriComponents dbusEndpointUri)
            // * {
            // *     proxy = new <wcf_namespace>.Contracts.Clients.<interface>Proxy(proxyBuilder.BindingFactory, dbusEndpointUri.CreateUri(<namespace>.wcf.Contracts.Constants.DbusServiceRelativeAddress));
            // * }
            CodeMemberMethod methodCreateProxyWithEndpoint = new CodeMemberMethod();

            methodCreateProxyWithEndpoint.Name       = "Create";
            methodCreateProxyWithEndpoint.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            methodCreateProxyWithEndpoint.Parameters.Add(paramdeclProxyManagerExtension);
            methodCreateProxyWithEndpoint.Parameters.Add(paramdeclProxy);
            methodCreateProxyWithEndpoint.Parameters.Add(paramdeclEndpointUri);
            methodCreateProxyWithEndpoint.Statements.Add(new CodeAssignStatement(
                                                             argrefProxy
                                                             , new CodeObjectCreateExpression(typerefProxy
                                                                                              , proprefBindingFactory
                                                                                              , invokeCreateUri
                                                                                              )
                                                             ));
            typedeclProxyBuilderExtensions.Members.Add(methodCreateProxyWithEndpoint);

            // * public static void Create(this Udbus.WCF.Client.ProxyBuilder proxyBuilder, out <namespace>.Contracts.Clients.<interface>Proxy proxy)
            // * {
            // *     proxyBuilder.Create(out proxy, Udbus.WCF.Client.DbusEndpointUriComponents.Create(proxyBuilder.AbsoluteUribuilder));
            // * }
            CodeMemberMethod methodCreateProxy = new CodeMemberMethod();

            methodCreateProxy.Name       = "Create";
            methodCreateProxy.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            methodCreateProxy.Parameters.Add(paramdeclProxyManagerExtension);
            methodCreateProxy.Parameters.Add(paramdeclProxy);
            methodCreateProxy.Statements.Add(invokeProxyManagerExtensionCreate);
            typedeclProxyBuilderExtensions.Members.Add(methodCreateProxy);

            CodeNamespace nsClientExtensions = new CodeNamespace(CodeBuilderCommon.nsClientExtensions);

            nsClientExtensions.Types.Add(typedeclProxyBuilderExtensions);
            unit.Namespaces.Add(nsClientExtensions);
            // * }
        }
Пример #33
0
        public void Properties()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            // create a class
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Test";
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference(typeof(Exception)));
            ns.Types.Add(class1);

            CodeMemberField int1 = new CodeMemberField(typeof(int), "int1");
            class1.Members.Add(int1);

            CodeMemberField tempString = new CodeMemberField(typeof(string), "tempString");
            class1.Members.Add(tempString);

            // basic property with get/set
            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "prop1";
            prop1.Type = new CodeTypeReference(typeof(int));
            prop1.Attributes = MemberAttributes.Public;
            prop1.HasGet = true;
            prop1.HasSet = true;
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
            prop1.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("int1"), new CodeVariableReferenceExpression("value")));
            class1.Members.Add(prop1);

            // override Property
            CodeMemberProperty overrideProp = new CodeMemberProperty();
            overrideProp.Name = "Text";
            overrideProp.Type = new CodeTypeReference(typeof(string));
            overrideProp.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            overrideProp.HasGet = true;
            overrideProp.HasSet = true;
            overrideProp.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("tempString"), new CodeVariableReferenceExpression("value")));
            overrideProp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Hello World")));

            class1.Members.Add(overrideProp);

            foreach (MemberAttributes attrs in new[] { MemberAttributes.Private, MemberAttributes.Family, MemberAttributes.Assembly })
            {
                CodeMemberProperty configuredProp = new CodeMemberProperty();
                configuredProp.Name = attrs.ToString() + "Prop";
                configuredProp.Type = new CodeTypeReference(typeof(int));
                configuredProp.Attributes = attrs;
                configuredProp.HasGet = true;
                configuredProp.HasSet = true;
                configuredProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("int1"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));
                configuredProp.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("int1"), new CodeVariableReferenceExpression("value")));
                class1.Members.Add(configuredProp);
            }

            // Static property
            CodeMemberProperty staticProp = new CodeMemberProperty();
            staticProp.Name = "staticProp";
            staticProp.Type = new CodeTypeReference(typeof(int));
            staticProp.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            staticProp.HasGet = true;
            staticProp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(99)));
            class1.Members.Add(staticProp);

            // this reference
            CodeMemberMethod thisRef = new CodeMemberMethod();
            thisRef.Name = "thisRef";
            thisRef.ReturnType = new CodeTypeReference(typeof(int));
            thisRef.Attributes = MemberAttributes.Public;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "value");
            thisRef.Parameters.Add(param);

            thisRef.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "privProp1"), new CodeVariableReferenceExpression("value")));
            thisRef.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "privProp1")));
            class1.Members.Add(thisRef);

            // set value
            CodeMemberMethod setProp = new CodeMemberMethod();
            setProp.Name = "setProp";
            setProp.ReturnType = new CodeTypeReference(typeof(int));
            setProp.Attributes = MemberAttributes.Public;
            CodeParameterDeclarationExpression intParam = new CodeParameterDeclarationExpression(typeof(int), "value");
            setProp.Parameters.Add(intParam);

            setProp.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "prop1"), new CodeVariableReferenceExpression("value")));
            setProp.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("int1")));
            class1.Members.Add(setProp);

            AssertEqual(ns,
                @"namespace NS {
                      using System;


                      public class Test : System.Exception {

                          private int int1;

                          private string tempString;

                          public virtual int prop1 {
                              get {
                                  return (int1 + 1);
                              }
                              set {
                                  int1 = value;
                              }
                          }

                          public override string Text {
                              get {
                                  return ""Hello World"";
                              }
                              set {
                                  tempString = value;
                              }
                          }

                          private int PrivateProp
                          {
                              get
                              {
                                  return (int1 + 1);
                              }
                              set
                              {
                                  int1 = value;
                              }
                          }
                      
                          protected virtual int FamilyProp
                          {
                              get
                              {
                                  return (int1 + 1);
                              }
                              set
                              {
                                  int1 = value;
                              }
                          }
                      
                          internal virtual int AssemblyProp
                          {
                              get
                              {
                                  return (int1 + 1);
                              }
                              set
                              {
                                  int1 = value;
                              }
                          }
                      
                          public static int staticProp
                          {
                              get
                              {
                                  return 99;
                              }
                          }
                      
                          public virtual int thisRef(int value)
                          {
                              this.privProp1 = value;
                              return this.privProp1;
                          }
                      
                          public virtual int setProp(int value)
                          {
                              this.prop1 = value;
                              return int1;
                          }
                      }
                  }");
        }
Пример #34
0
        private static void ProvideWriteLineMethod2(CodeTypeMemberCollection members, CodeParameterDeclarationExpression argsParam)
        {
            CodeMemberMethod codeMemberMethod = CodeDomHelpers.CreateMethod(null, "WriteLine", "Write formatted text directly into the generated output", (MemberAttributes)24578, CodeDomHelpers.Call("WriteLine", CodeDomHelpers.Call(typeof(string), "Format", typeof(CultureInfo).Expr().Prop("CurrentCulture"), new CodeVariableReferenceExpression("format"), new CodeVariableReferenceExpression("args"))));

            codeMemberMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "format"));
            codeMemberMethod.Parameters.Add(argsParam);
            members.Add(codeMemberMethod);
        }
Пример #35
0
        public void Goto()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Test";
            class1.IsClass = true;
            ns.Types.Add(class1);

            // create first method to test gotos that jump ahead to a defined label with statement
            var cmm = new CodeMemberMethod();
            cmm.Name = "FirstMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            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))));
            class1.Members.Add(cmm);

            // create second method to test gotos that jump ahead to a defined label without a statement attached to it
            cmm = new CodeMemberMethod();
            cmm.Name = "SecondMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "i");
            cmm.Parameters.Add(param);
            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"));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(7)));
            class1.Members.Add(cmm);

            // create third method to test gotos that jump to a previously defined label
            cmm = new CodeMemberMethod();
            cmm.Name = "ThirdMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "i");
            cmm.Parameters.Add(param);
            CodeAssignStatement assignmt = new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                                new CodeBinaryOperatorExpression
                                (new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                                new CodePrimitiveExpression(5)));
            cmm.Statements.Add(new CodeLabeledStatement("label", assignmt));
            condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                                new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
                                new CodeGotoStatement("label"));
            cmm.Statements.Add(condstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
            class1.Members.Add(cmm);

            AssertEqual(ns,
                @"namespace NS {
                      using System;

                      public class Test {
                          public static int FirstMethod(int i) {
                              if ((i < 1)) {
                                  goto comehere;
                              }
                              return 6;
                          comehere:
                              return 7;
                          }

                          public static int SecondMethod(int i) {
                              if ((i < 1)) {
                                  goto comehere;
                              }
                              return 6;
                          comehere:
                              return 7;
                          }

                          public static int ThirdMethod(int i) {
                          label:
                              i = (i + 5);
                              if ((i < 1)) {
                                  goto label;
                              }
                              return i;
                          }
                      }
                  }");
        }
        /// <summary>
        /// Generates a domain method on the domain service.
        /// </summary>
        /// <param name="domainMethod">The domain method to generate code for.</param>
        private void GenerateDomainOperationEntry(DomainOperationEntry domainMethod)
        {
            // ----------------------------------------------------------------
            // Method decl
            // ----------------------------------------------------------------
            CodeMemberMethod method = new CodeMemberMethod();

            method.Name       = domainMethod.Name;
            method.Attributes = MemberAttributes.Public | MemberAttributes.Final;

            // ----------------------------------------------------------------
            // generate domain method body:
            //    entity.<methodName>(params);
            // ----------------------------------------------------------------
            List <CodeExpression> invokeParams = new List <CodeExpression>();

            // The domain method parameter list is the same as the domain operation entries.
            DomainOperationParameter[] paramInfos = domainMethod.Parameters.ToArray();

            // Generate the <summary> and <param> doc comments
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_DomainClient_Custom_Method_Summary_Comment, domainMethod.Name, domainMethod.AssociatedType.Name);

            method.Comments.AddRange(CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Generate <param> doc comment for all the parameters
            // The first param is the entity
            comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_DomainContext_Custom_Method_Entity_Parameter_Comment, domainMethod.AssociatedType.Name);
            method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment(paramInfos[0].Name, comment, this.ClientProxyGenerator.IsCSharp));

            // All subsequent params
            for (int i = 1; i < paramInfos.Length; ++i)
            {
                comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_DomainContext_Custom_Method_Parameter_Comment, paramInfos[i].Name);
                method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment(paramInfos[i].Name, comment, this.ClientProxyGenerator.IsCSharp));
            }

            // Create an expression for each parameter
            for (int i = 0; i < paramInfos.Length; i++)
            {
                DomainOperationParameter paramInfo = paramInfos[i];

                // build up the method parameter signature from the DomainOperationEntry.MethodInfo
                CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(
                    CodeGenUtilities.GetTypeReference(
                        CodeGenUtilities.TranslateType(paramInfo.ParameterType),
                        this.ClientProxyGenerator,
                        this._proxyClass),
                    paramInfo.Name);

                method.Parameters.Add(paramDecl);

                // Skip the entity parameter.
                if (i > 0)
                {
                    // build up the invoke call parameters
                    invokeParams.Add(new CodeVariableReferenceExpression(paramInfo.Name));
                }
            }

            method.Statements.Add(
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression(paramInfos[0].Name), domainMethod.Name, invokeParams.ToArray())));

            this._proxyClass.Members.Add(method);
        }
Пример #37
0
        public void MethodWithRefParameter()
        {
            var cd = new CodeTypeDeclaration("TEST");
            cd.IsClass = true;

            var 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);

            AssertEqual(cd,
                @"public class TEST {
                      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);
                      }
                  }");
        }
        private void GenerateEntityQueryMethod(DomainOperationEntry domainOperationEntry)
        {
            string queryMethodName = domainOperationEntry.Name + QuerySuffix;

            Type entityType = TypeUtility.GetElementType(domainOperationEntry.ReturnType);

            CodeMemberMethod queryMethod = new CodeMemberMethod();

            queryMethod.Name       = queryMethodName;
            queryMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; // Final needed, else becomes virtual

            queryMethod.ReturnType = CodeGenUtilities.GetTypeReference(TypeConstants.EntityQueryTypeFullName, this._domainServiceDescription.DomainServiceType.Namespace, false);
            queryMethod.ReturnType.TypeArguments.Add(CodeGenUtilities.GetTypeReference(entityType.FullName, this._domainServiceDescription.DomainServiceType.Namespace, true));

            DomainOperationParameter[] domainOperationEntryParameters = domainOperationEntry.Parameters.ToArray();

            // Generate <summary> doc comment
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Summary_DomainContext, entityType.Name, domainOperationEntry.Name);

            queryMethod.Comments.AddRange(CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Generate <param> doc comments
            foreach (DomainOperationParameter paramInfo in domainOperationEntryParameters)
            {
                comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Query_Method_Parameter_Comment, paramInfo.Name);
                queryMethod.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment(paramInfo.Name, comment, this.ClientProxyGenerator.IsCSharp));
            }

            // Generate <returns> doc comments
            comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Query_Method_Returns_Comment, domainOperationEntry.AssociatedType.Name);
            queryMethod.Comments.AddRange(CodeGenUtilities.GenerateReturnsCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Propagate custom validation attributes
            IEnumerable <Attribute> methodAttributes = domainOperationEntry.Attributes.Cast <Attribute>();

            CustomAttributeGenerator.GenerateCustomAttributes(
                this.ClientProxyGenerator,
                this._proxyClass,
                ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethod, ex.Message, queryMethod.Name, this._proxyClass.Name, ex.InnerException.Message),
                methodAttributes,
                queryMethod.CustomAttributes,
                queryMethod.Comments);

            // add any domain operation entry parameters first

            CodeVariableReferenceExpression paramsRef = new CodeVariableReferenceExpression("parameters");

            if (domainOperationEntryParameters.Length > 0)
            {
                // need to generate the user parameters dictionary
                CodeTypeReference dictionaryTypeReference = CodeGenUtilities.GetTypeReference(
                    typeof(Dictionary <string, object>),
                    this.ClientProxyGenerator,
                    this._proxyClass);

                CodeVariableDeclarationStatement paramsDef = new CodeVariableDeclarationStatement(
                    dictionaryTypeReference,
                    "parameters",
                    new CodeObjectCreateExpression(dictionaryTypeReference, new CodeExpression[0]));
                queryMethod.Statements.Add(paramsDef);
            }
            foreach (DomainOperationParameter paramInfo in domainOperationEntryParameters)
            {
                CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(
                    CodeGenUtilities.GetTypeReference(
                        CodeGenUtilities.TranslateType(paramInfo.ParameterType),
                        this.ClientProxyGenerator,
                        this._proxyClass),
                    paramInfo.Name);

                // Propagate parameter level validation attributes
                IEnumerable <Attribute> paramAttributes = paramInfo.Attributes.Cast <Attribute>();

                string commentHeader =
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resource.ClientCodeGen_Attribute_Parameter_FailedToGenerate,
                        paramInfo.Name);

                CustomAttributeGenerator.GenerateCustomAttributes(
                    this.ClientProxyGenerator,
                    this._proxyClass,
                    ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethodParameter, ex.Message, paramDecl.Name, queryMethod.Name, this._proxyClass.Name, ex.InnerException.Message),
                    paramAttributes,
                    paramDecl.CustomAttributes,
                    queryMethod.Comments,
                    commentHeader);

                // add the parameter to the query method
                queryMethod.Parameters.Add(paramDecl);

                // add the parameter and value to the params dictionary
                queryMethod.Statements.Add(new CodeMethodInvokeExpression(
                                               new CodeMethodReferenceExpression(paramsRef, "Add"),
                                               new CodePrimitiveExpression(paramInfo.Name),
                                               new CodeVariableReferenceExpression(paramInfo.Name)));
            }

            // add argument for queryName
            CodeExpressionCollection arguments = new CodeExpressionCollection();

            arguments.Add(new CodePrimitiveExpression(domainOperationEntry.Name));

            // add argument for parameters
            if (domainOperationEntryParameters.Length > 0)
            {
                arguments.Add(paramsRef);
            }
            else
            {
                arguments.Add(new CodePrimitiveExpression(null));
            }

            // add argument for hasSideEffects
            QueryAttribute queryAttribute = (QueryAttribute)domainOperationEntry.OperationAttribute;

            arguments.Add(new CodePrimitiveExpression(queryAttribute.HasSideEffects));

            // add argument for isComposable
            arguments.Add(new CodePrimitiveExpression(queryAttribute.IsComposable));

            // this.ValidateMethod("methodName", parameters);
            CodeExpression paramsExpr = new CodePrimitiveExpression(null);

            if (domainOperationEntryParameters.Length > 0)
            {
                paramsExpr = paramsRef;
            }
            CodeExpressionStatement validateMethodCall = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    "ValidateMethod",
                    new CodeExpression[]
            {
                new CodePrimitiveExpression(queryMethodName),
                paramsExpr
            }));

            queryMethod.Statements.Add(validateMethodCall);

            // ----------------------------------------------------------------
            // method call: base.CreateQuery(arguments...)
            // ----------------------------------------------------------------
            CodeTypeReference             entityTypeRef     = CodeGenUtilities.GetTypeReference(entityType.FullName, this._domainServiceDescription.DomainServiceType.Namespace, true);
            CodeMethodReferenceExpression createQueryMethod = new CodeMethodReferenceExpression(new CodeBaseReferenceExpression(), "CreateQuery", entityTypeRef);
            CodeMethodReturnStatement     createQueryCall   = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(createQueryMethod, arguments.Cast <CodeExpression>().ToArray()));

            queryMethod.Statements.Add(createQueryCall);

            this._proxyClass.Members.Add(queryMethod);
        }
Пример #39
0
        public void CastingOperations()
        {
            var cd = new CodeTypeDeclaration();
            cd.Name = "Test";
            cd.IsClass = true;

            // create method to test casting float to int
            CodeMemberMethod castReturnValue = new CodeMemberMethod();
            castReturnValue.Name = "CastReturnValue";
            castReturnValue.ReturnType = new CodeTypeReference(typeof(int));
            castReturnValue.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression strParam = new CodeParameterDeclarationExpression(typeof(string), "value");
            castReturnValue.Parameters.Add(strParam);
            castReturnValue.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Single"), "Parse", new CodeExpression[] { new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.Globalization.CultureInfo"), "InvariantCulture") }))));
            cd.Members.Add(castReturnValue);

            // create method to test casting interface -> class
            CodeMemberMethod castInterface = new CodeMemberMethod();
            castInterface.Name = "CastInterface";
            castInterface.ReturnType = new CodeTypeReference(typeof(string));
            castInterface.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression interfaceParam = new CodeParameterDeclarationExpression(typeof(System.ICloneable), "value");
            castInterface.Parameters.Add(interfaceParam);
            castInterface.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(string), new CodeVariableReferenceExpression("value"))));
            cd.Members.Add(castInterface);

            // create method to test casting value type -> reference type
            CodeMemberMethod valueToReference = new CodeMemberMethod();
            valueToReference.Name = "ValueToReference";
            valueToReference.ReturnType = new CodeTypeReference(typeof(System.Object));
            valueToReference.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression valueParam = new CodeParameterDeclarationExpression(typeof(int), "value");
            valueToReference.Parameters.Add(valueParam);
            valueToReference.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(System.Object), new CodeVariableReferenceExpression("value"))));
            cd.Members.Add(valueToReference);

            AssertEqual(cd,
                @"public class Test {
                     public static int CastReturnValue(string value) {
                         return ((int)(float.Parse(value, System.Globalization.CultureInfo.InvariantCulture)));
                     }
                     public static string CastInterface(System.ICloneable value) {
                         return ((string)(value));
                     }
                     public static object ValueToReference(int value) {
                         return ((object)(value));
                     }
                 }");
        }
        CodeMemberMethod GenerateMethod(CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember)
        {
            CodeIdentifiers  pids        = new CodeIdentifiers();
            CodeMemberMethod method      = new CodeMemberMethod();
            CodeMemberMethod methodBegin = new CodeMemberMethod();
            CodeMemberMethod methodEnd   = new CodeMemberMethod();

            method.Attributes      = MemberAttributes.Public;
            methodBegin.Attributes = MemberAttributes.Public;
            methodEnd.Attributes   = MemberAttributes.Public;

            // Find unique names for temporary variables

            for (int n = 0; n < inputMembers.Count; n++)
            {
                pids.AddUnique(inputMembers[n].MemberName, inputMembers[n]);
            }

            string varAsyncResult = pids.AddUnique("asyncResult", "asyncResult");
            string varCallback    = pids.AddUnique("callback", "callback");
            string varAsyncState  = pids.AddUnique("asyncState", "asyncState");

            string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name), method);

            method.Name      = Operation.Name;
            methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name), method);
            methodEnd.Name   = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name), method);

            method.ReturnType    = new CodeTypeReference(typeof(void));
            methodEnd.ReturnType = new CodeTypeReference(typeof(void));
            methodEnd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), varAsyncResult));

            CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];

            for (int n = 0; n < inputMembers.Count; n++)
            {
                string ptype = GetSimpleType(inputMembers[n]);
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(ptype, inputMembers[n].MemberName);

                param.Direction = FieldDirection.In;
                method.Parameters.Add(param);
                methodBegin.Parameters.Add(param);
                paramArray [n] = new CodeVariableReferenceExpression(param.Name);
            }

            bool isVoid = true;

            if (outputMember != null)
            {
                method.ReturnType    = new CodeTypeReference(outputMember.TypeFullName);
                methodEnd.ReturnType = new CodeTypeReference(outputMember.TypeFullName);
                xmlExporter.AddMappingMetadata(method.ReturnTypeCustomAttributes, outputMember, "");
                isVoid = false;
            }

            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), varCallback));
            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), varAsyncState));
            methodBegin.ReturnType = new CodeTypeReference(typeof(IAsyncResult));

            // Array of input parameters

            CodeArrayCreateExpression methodParams;

            if (paramArray.Length > 0)
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), paramArray);
            }
            else
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), 0);
            }

            // Generate method url

            CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();

            CodeExpression               thisURlExp        = new CodeFieldReferenceExpression(ethis, "Url");
            CodePrimitiveExpression      metUrl            = new CodePrimitiveExpression(httpOper.Location);
            CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression(thisURlExp, CodeBinaryOperatorType.Add, metUrl);

            // Invoke call

            CodePrimitiveExpression    varMsgName = new CodePrimitiveExpression(messageName);
            CodeMethodInvokeExpression inv;

            inv = new CodeMethodInvokeExpression(ethis, "Invoke", varMsgName, expMethodLocation, methodParams);
            if (!isVoid)
            {
                method.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, inv)));
            }
            else
            {
                method.Statements.Add(inv);
            }

            // Begin Invoke Call

            CodeExpression expCallb  = new CodeVariableReferenceExpression(varCallback);
            CodeExpression expAsyncs = new CodeVariableReferenceExpression(varAsyncState);

            inv = new CodeMethodInvokeExpression(ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs);
            methodBegin.Statements.Add(new CodeMethodReturnStatement(inv));

            // End Invoke call

            CodeExpression varAsyncr = new CodeVariableReferenceExpression(varAsyncResult);

            inv = new CodeMethodInvokeExpression(ethis, "EndInvoke", varAsyncr);
            if (!isVoid)
            {
                methodEnd.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(methodEnd.ReturnType, inv)));
            }
            else
            {
                methodEnd.Statements.Add(inv);
            }

            // Attributes

            CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.HttpMethodAttribute");

            att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetOutMimeFormatter())));
            att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetInMimeFormatter())));
            AddCustomAttribute(method, att, true);

            CodeTypeDeclaration.Members.Add(method);
            CodeTypeDeclaration.Members.Add(methodBegin);
            CodeTypeDeclaration.Members.Add(methodEnd);

            return(method);
        }
Пример #41
0
 private CodeParameterDeclarationExpression GetArgument(Smoke* smoke, short* typeIndex, IList<string> methodArgs, IEnumerable args, ref int count)
 {
     bool isRef;
     CodeTypeReference argType = translator.CppToCSharp(smoke->types + *typeIndex, type, out isRef);
     string argName = this.GetArgName(smoke, typeIndex, methodArgs, ref count, isRef, argType);
     if (!argName.Contains(" = "))
     {
         RemoveDefaultValuesFromPreviousArgs(args);
     }
     CodeParameterDeclarationExpression arg = new CodeParameterDeclarationExpression(argType, argName);
     if (isRef)
     {
         arg.Direction = FieldDirection.Ref;
     }
     return arg;
 }
Пример #42
0
        private void CreateVertexInputMethods()
        {
            AsmListing asmVS = this.source.GetAsmTechnique(this.techniqueName, this.platform).VertexShader;

            //create the GetVertexInputCount() and GetVertexInput() methods

            CodeMemberMethod count = new CodeMemberMethod();

            count.Name       = "GetVertexInputCount";
            count.Attributes = MemberAttributes.Family | MemberAttributes.Override;
            count.ReturnType = new CodeTypeReference(typeof(int));

            Comment(count, "Returns the number of vertex inputs used by this shader");
            count.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(asmVS.InputCount)));
            classDom.Members.Add(count);

            //inputs are stored in a static array

            //create it...

            int[] arrayValues = new int[asmVS.InputCount * 2];
            for (int i = 0; i < asmVS.InputCount; i++)
            {
                arrayValues[i] = (int)asmVS.GetInput(i).Usage;
                arrayValues[i + asmVS.InputCount] = (int)asmVS.GetInput(i).Index;
            }

            this.vsInputField                = new CodeMemberField(typeof(int[]), "vin");
            this.vsInputField.Attributes     = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
            this.vsInputField.InitExpression = ShaderBytes.ToArray(arrayValues, this.directives);

            CodeFieldReferenceExpression vsInputRef = new CodeFieldReferenceExpression(ShaderClassEx, vsInputField.Name);

            //protected internal abstract void GetVertexInput(int index, out VertexElementUsage elementUsage, out int elementIndex);

            CodeMemberMethod getInput = new CodeMemberMethod();

            getInput.Name       = "GetVertexInput";
            getInput.Attributes = MemberAttributes.Family | MemberAttributes.Override;

            CodeParameterDeclarationExpression indexParam = new CodeParameterDeclarationExpression(typeof(int), "i");

            getInput.Parameters.Add(indexParam);

            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(VertexElementUsage), "usage");

            param.Direction = FieldDirection.Out;
            getInput.Parameters.Add(param);

            param           = new CodeParameterDeclarationExpression(typeof(int), "index");
            param.Direction = FieldDirection.Out;
            getInput.Parameters.Add(param);

            CodeArgumentReferenceExpression indexRef = new CodeArgumentReferenceExpression(indexParam.Name);

            //the element index is stored at 'i + asmVS.InputCount'
            CodeExpression indexArray = new CodeArrayIndexerExpression(vsInputRef,
                                                                       new CodeBinaryOperatorExpression(indexRef, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(asmVS.InputCount)));

            //and the usage must be cast
            CodeExpression usageCast = new CodeCastExpression(typeof(VertexElementUsage), new CodeArrayIndexerExpression(vsInputRef, indexRef));

            getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("usage"), usageCast));
            getInput.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("index"), indexArray));

            Comment(getInput, "Returns a vertex input used by this shader");

            classDom.Members.Add(getInput);
        }
Пример #43
0
    public void PostMembersHook(Smoke* smoke, Smoke.Class* klass, CodeTypeDeclaration type)
    {
        if (Util.IsQObject(klass))
        {
            CodeMemberProperty emit = new CodeMemberProperty();
            emit.Name = "Emit";
            emit.Attributes = MemberAttributes.Family | MemberAttributes.New | MemberAttributes.Final;
            emit.HasGet = true;
            emit.HasSet = false;

            string signalsIfaceName = "I" + type.Name + "Signals";
            CodeTypeReference returnType = new CodeTypeReference(signalsIfaceName);
            emit.Type = returnType;

            emit.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(
                returnType,
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Q_EMIT")
            )));

            type.Members.Add(emit);

            string className = ByteArrayManager.GetString(klass->className);
            int colon = className.LastIndexOf("::", StringComparison.Ordinal);
            string prefix = (colon != -1) ? className.Substring(0, colon) : string.Empty;

            IList typeCollection = Data.GetTypeCollection(prefix);
            CodeTypeDeclaration ifaceDecl = new CodeTypeDeclaration(signalsIfaceName);
            ifaceDecl.IsInterface = true;

            if (className != "QObject")
            {
                string parentClassName = ByteArrayManager.GetString(smoke->classes[smoke->inheritanceList[klass->parents]].className);
                colon = parentClassName.LastIndexOf("::", StringComparison.Ordinal);
                prefix = (colon != -1) ? parentClassName.Substring(0, colon) : string.Empty;
                if (colon != -1)
                {
                    parentClassName = parentClassName.Substring(colon + 2);
                }

                string parentInterface = (prefix != string.Empty) ? prefix.Replace("::", ".") + "." : string.Empty;
                parentInterface += "I" + parentClassName + "Signals";

                ifaceDecl.BaseTypes.Add(new CodeTypeReference(parentInterface));
            }
            Dictionary<CodeSnippetTypeMember, CodeMemberMethod> signalEvents = new Dictionary<CodeSnippetTypeMember, CodeMemberMethod>();
            GetSignals(smoke, klass, delegate(string signature, string name, string typeName, IntPtr metaMethod)
            {
                CodeMemberMethod signal = new CodeMemberMethod();
                signal.Attributes = MemberAttributes.Abstract;

                // capitalize the first letter
                StringBuilder builder = new StringBuilder(name);
                builder[0] = char.ToUpper(builder[0]);
                string tmp = builder.ToString();

                signal.Name = tmp;
                bool isRef;
                try
                {
                    if (typeName == string.Empty)
                        signal.ReturnType = new CodeTypeReference(typeof(void));
                    else
                        signal.ReturnType = Translator.CppToCSharp(typeName, out isRef);
                }
                catch (NotSupportedException)
                {
                    Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                    return;
                }

                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("Q_SIGNAL",
                    new CodeAttributeArgument(new CodePrimitiveExpression(signature)));
                signal.CustomAttributes.Add(attr);

                int argNum = 1;
                StringBuilder fullNameBuilder = new StringBuilder("Slot");
                GetMetaMethodParameters(metaMethod, delegate(string paramType, string paramName)
                {
                    if (paramName == string.Empty)
                    {
                        paramName = "arg" + argNum.ToString();
                    }
                    argNum++;

                    CodeParameterDeclarationExpression param;
                    try
                    {
                        short id = smoke->IDType(paramType);
                        CodeTypeReference paramTypeRef;
                        if (id > 0)
                        {
                            paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                        }
                        else
                        {
                            if (!paramType.Contains("::"))
                            {
                                id = smoke->IDType(className + "::" + paramType);
                                if (id > 0)
                                {
                                    paramTypeRef = Translator.CppToCSharp(smoke->types + id, out isRef);
                                }
                                else
                                {
                                    paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                                }
                            }
                            else
                            {
                                paramTypeRef = Translator.CppToCSharp(paramType, out isRef);
                            }
                        }
                        param = new CodeParameterDeclarationExpression(paramTypeRef, paramName);
                    }
                    catch (NotSupportedException)
                    {
                        Debug.Print("  |--Won't wrap signal {0}::{1}", className, signature);
                        return;
                    }
                    if (isRef)
                    {
                        param.Direction = FieldDirection.Ref;
                    }
                    signal.Parameters.Add(param);
                    if (argNum == 2)
                    {
                        fullNameBuilder.Append('<');
                    }
                    fullNameBuilder.Append(param.Type.BaseType);
                    fullNameBuilder.Append(',');
                });
                if (fullNameBuilder[fullNameBuilder.Length - 1] == ',')
                {
                    fullNameBuilder[fullNameBuilder.Length - 1] = '>';
                }
                ifaceDecl.Members.Add(signal);
                CodeSnippetTypeMember signalEvent = new CodeSnippetTypeMember();
                signalEvent.Name = signal.Name;
                CodeSnippetTypeMember existing = signalEvents.Keys.FirstOrDefault(m => m.Name == signal.Name);
                if (existing != null)
                {
                    CodeSnippetTypeMember signalEventToUse;
                    CodeMemberMethod signalToUse;
                    if (signal.Parameters.Count == 0)
                    {
                        signalEventToUse = existing;
                        signalToUse = signalEvents[existing];
                    }
                    else
                    {
                        signalEventToUse = signalEvent;
                        signalToUse = signal;
                    }
                    string suffix = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Name;
                    if (suffix.StartsWith("arg") && suffix.Length > 3 && char.IsDigit(suffix[3]))
                    {
                        string lastType = signalToUse.Parameters.Cast<CodeParameterDeclarationExpression>().Last().Type.BaseType;
                        suffix = lastType.Substring(lastType.LastIndexOf('.') + 1);
                    }
                    else
                    {
                        StringBuilder lastParamBuilder = new StringBuilder(suffix);
                        lastParamBuilder[0] = char.ToUpper(lastParamBuilder[0]);
                        suffix = lastParamBuilder.ToString();
                    }
                    signalEventToUse.Text = signalEventToUse.Text.Replace(signalEventToUse.Name, signalEventToUse.Name += suffix);
                }
                signalEvent.Text = string.Format(@"
        public event {0} {1}
        {{
            add
            {{
                QObject.Connect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
            remove
            {{
                QObject.Disconnect(this, Qt.SIGNAL(""{2}""), (QObject) value.Target, Qt.SLOT(value.Method.Name + ""{3}""));
            }}
        }}", fullNameBuilder, signalEvent.Name, signature, signature.Substring(signature.IndexOf('(')));
                signalEvents.Add(signalEvent, signal);
            });

            typeCollection.Add(ifaceDecl);
            foreach (KeyValuePair<CodeSnippetTypeMember, CodeMemberMethod> signalEvent in signalEvents)
            {
                CodeSnippetTypeMember implementation = signalEvent.Key;
                CodeCommentStatementCollection comments = new CodeCommentStatementCollection();
                foreach (CodeTypeMember current in from CodeTypeMember member in type.Members
                                                   where member.Name == implementation.Name
                                                   select member)
                {
                    if (comments.Count == 0)
                    {
                        comments.AddRange(current.Comments);
                    }
                    current.Name = "On" + current.Name;
                }
                signalEvent.Value.Comments.AddRange(comments);
                signalEvent.Key.Comments.AddRange(comments);
                type.Members.Add(signalEvent.Key);
            }
        }
    }
Пример #44
0
        //the method that creates SetAttribute methods

        private void CreateSetAttributeMethod(Type type, string method, string typename)
        {
            //create complex method...
            //which looks like:

            /*
             *              protected override bool SetAttribute(Xen.Graphics.ShaderSystem.IShaderSystem state, int name_uid, ref Microsoft.Xna.Framework.Matrix value)
             *              {
             *                      if ((ParticleStoreLife128.init_gd != state.DeviceUniqueIndex))
             *                      {
             *                              ParticleStoreLife128._init(state);
             *                      }
             *                      if ((name_uid == ParticleStoreLife128.id_1))
             *                      {
             *                              this.SetTest(ref value);
             *                              return true;
             *                      }
             *                      return false;
             *              }
             */

            //first, try and grab the setter statements.
            CodeStatementCollection statements = new CodeStatementCollection();

            foreach (DomBase dom in this.domList)
            {
                dom.AddSetAttribute(this, delegate(CodeStatement s) { statements.Add(s); }, type);
            }

            if (statements.Count == 0)
            {
                return;                 // this is most common. no need for the method.
            }
            //ok, does need the method

            CodeMemberMethod attrib = new CodeMemberMethod();

            attrib.Name       = method;
            attrib.Attributes = MemberAttributes.Family | MemberAttributes.Override;
            attrib.ReturnType = new CodeTypeReference(typeof(bool));
            attrib.Parameters.Add(ShaderSystemArg);

            CodeParameterDeclarationExpression parm = new CodeParameterDeclarationExpression(typeof(int), setAttribIdRef.ParameterName);

            attrib.Parameters.Add(parm);

            parm = new CodeParameterDeclarationExpression(type, setAttribValueRef.ParameterName);
            if (type.IsClass == false && System.Runtime.InteropServices.Marshal.SizeOf(type) > 4)
            {
                parm.Direction = FieldDirection.Ref;
            }
            attrib.Parameters.Add(parm);

            //first, add a check to make sure the device is warmed
            attrib.Statements.Add(this.validateDeviceIdAndWarmShader);

            //add the assignment checkers
            attrib.Statements.AddRange(statements);

            //otherwise return false
            attrib.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));

            Comment(attrib, string.Format("Set a shader {2} of type '{0}' by global unique ID, see <see cref=\"{1}.GetNameUniqueID\"/> for details.", type.Name, typeof(IShaderSystem).FullName, typename));

            classDom.Members.Add(attrib);
        }
Пример #45
0
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace ns = new CodeNamespace ("Namespace1");

        cu.Namespaces.Add (ns);

        CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST");
        cd.IsClass = true;
        ns.Types.Add (cd);

        if (Supports (provider, GeneratorSupport.DeclareEnums)) {
            // GENERATE (C#):
            //    public enum DecimalEnum {
            //        Num0 = 0,
            //        Num1 = 1,
            //        Num2 = 2,
            //        Num3 = 3,
            //        Num4 = 4,
            //    }

            CodeTypeDeclaration ce = new CodeTypeDeclaration ("DecimalEnum");
            ce.IsEnum = true;
            ns.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);
            }

            // GENERATE (C#):
            //    public enum BinaryEnum {
            //        Bin1 = 1,
            //        Bin2 = 2,
            //        Bin3 = 4,
            //        Bin4 = 8,
            //        Bin5 = 16,
            //    }

            ce = new CodeTypeDeclaration ("BinaryEnum");
            ce.IsEnum = true;
            ns.Types.Add (ce);

            // things to enumerate
            int i = 0x01;
            for (int k = 1; k < 6; k++) {
                CodeMemberField Field = new CodeMemberField (typeof (int), "Bin" + (k).ToString ());
                Field.InitExpression = new CodePrimitiveExpression (i);
                i = i * 2;
                ce.Members.Add (Field);
            }

#if WHIDBEY
            // GENERATE (C#):
            //    public enum MyEnum: System.UInt64 {
            //        small = 0,
            //        medium = Int64.MaxValue/10,
            //        large = Int64.MaxValue,
            //    }
            ce = new CodeTypeDeclaration ("MyEnum");
            ce.BaseTypes.Add (new CodeTypeReference (typeof (UInt64)));
            ce.IsEnum = true;
            ns.Types.Add (ce);

            // Add fields     
            ce.Members.Add (CreateFieldMember ("Small", 0));
            ce.Members.Add (CreateFieldMember ("Medium", Int64.MaxValue / 10));
            ce.Members.Add (CreateFieldMember ("Large", Int64.MaxValue));
#endif

            // GENERATE (C#):
            //        public 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);
            //            }
    
            // generate 5 scenarios for OutputDecimalEnumVal
            for (int k = 0; k < 5; k++)
                AddScenario ("CheckOutputDecimalEnumVal" + k);

            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "OutputDecimalEnumVal";
            cmm.Attributes = MemberAttributes.Public;
            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);


            // GENERATE (C#):
            //        public int OutputBinaryEnumVal(int i) {
            //            if ((i == 3)) {
            //                return ((int)(BinaryEnum.Bin3));
            //            }
            //            if ((i == 4)) {
            //                return ((int)(BinaryEnum.Bin4));
            //            }
            //            if ((i == 2)) {
            //                return ((int)(BinaryEnum.Bin2));
            //            }
            //            if ((i == 1)) {
            //                return ((int)(BinaryEnum.Bin1));
            //            }
            //            if ((i == 5)) {
            //                return ((int)(BinaryEnum.Bin5));
            //            }
            //            return (i + 10);
            //        }

            // generate 6 scenarios for OutputBinaryEnumVal
            for (int k = 1; k < 6; k++)
                AddScenario ("CheckOutputBinaryEnumVal" + k);
           AddScenario ("CheckOutputBinaryEnumValRet17", "Check for a return value of 17");

            cmm = new CodeMemberMethod ();
            cmm.Name = "OutputBinaryEnumVal";
            cmm.Attributes = MemberAttributes.Public;
            param = new CodeParameterDeclarationExpression (typeof (int), "i");
            cmm.Parameters.Add (param);
            eq = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (3));
            truestmt = new CodeMethodReturnStatement (
                new CodeCastExpression (typeof (int),
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin3")));
            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 ("BinaryEnum"), "Bin4")));
            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 ("BinaryEnum"), "Bin2")));
            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 ("BinaryEnum"), "Bin1")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (5));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin5")));
            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 WHIDBEY
            // GENERATE (C#):
            //        public long VerifyMyEnumExists(int num) {
            //            if ((num == Int32.MaxValue)) {
            //                return ((int)(MyEnum.Large));
            //            }
            //            return 0;
            //        }

            AddScenario ("CheckVerifyMyEnumExists");
            cmm = new CodeMemberMethod ();
            cmm.Name = "VerifyMyEnumExists";
            cmm.Attributes = MemberAttributes.Public;
            param = new CodeParameterDeclarationExpression (typeof (int), "num");
            cmm.Parameters.Add (param);
            cmm.ReturnType = new CodeTypeReference ("System.Int64");
            eq = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("num"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (Int32.MaxValue));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (long),
                        new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("MyEnum"),
                            "Large")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (0)));
            cd.Members.Add (cmm);
#endif
        }
    }
Пример #46
0
        protected override void RenderImplementation()
        {
            var httpMethodName = HttpMethod.ToString().ToLower();

            string contentOptionsWithHeadersHandlerForString = $"{{ method: '{httpMethodName}', headers: headersHandler ? Object.assign(headersHandler(), {{ 'Content-Type': '{contentType}' }}): {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";
            var    ContentOptionsForString = settings.HandleHttpRequestHeaders ? contentOptionsWithHeadersHandlerForString : $"{{ method: '{httpMethodName}', headers: {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";

            string contentOptionsWithHeadersHandlerForResponse = $"{{ method: '{httpMethodName}', headers: headersHandler ? Object.assign(headersHandler(), {{ 'Content-Type': '{contentType}' }}): {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";
            var    ContentOptionsForResponse = settings.HandleHttpRequestHeaders ? contentOptionsWithHeadersHandlerForResponse : $"{{ method: '{httpMethodName}', headers: {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";

            string optionsWithHeadersHandlerAndContent = $"{{ method: '{httpMethodName}', headers: headersHandler ? Object.assign(headersHandler(), {{ 'Content-Type': '{contentType}' }}): {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";
            var    OptionsWithContent = settings.HandleHttpRequestHeaders ? optionsWithHeadersHandlerAndContent : $"{{ method: '{httpMethodName}', headers: {{ 'Content-Type': '{contentType}' }}, body: JSON.stringify(requestBody) }}";

            string optionsWithHeadersHandlerForString = $"{{ method: '{httpMethodName}', headers: headersHandler ? headersHandler() : undefined }}";
            var    OptionsForString = settings.HandleHttpRequestHeaders ? optionsWithHeadersHandlerForString : $"{{ method: '{httpMethodName}' }}";

            string optionsWithHeadersHandlerForResponse = $"{{ method: '{httpMethodName}', headers: headersHandler ? headersHandler() : undefined }}";
            var    OptionsForResponse = settings.HandleHttpRequestHeaders ? optionsWithHeadersHandlerForResponse : $"{{ method: '{httpMethodName}' }}";

            string optionsWithHeadersHandler = $"{{ method: '{httpMethodName}', headers: headersHandler ? headersHandler() : undefined }}";
            var    Options = settings.HandleHttpRequestHeaders ? optionsWithHeadersHandler : $"{{ method: '{httpMethodName}' }}";

            CodeParameterDeclarationExpression[] parameters = ParameterDescriptions.Select(d =>
                                                                                           new CodeParameterDeclarationExpression(TypeMapper.MapCodeTypeReferenceToTsText(d.ParameterTypeReference), d.Name))
                                                              .ToArray();

            Method.Parameters.AddRange(parameters);

            if (RequestBodyCodeTypeReference != null)
            {
                CodeParameterDeclarationExpression p = new CodeParameterDeclarationExpression(RequestBodyCodeTypeReference, "requestBody");
                Method.Parameters.Add(p);
            }

            if (settings.HandleHttpRequestHeaders)
            {
                Method.Parameters.Add(new CodeParameterDeclarationExpression(
                                          "() => {[header: string]: string}", "headersHandler?"));
            }

            string jsUriQuery = UriQueryHelper.CreateUriQueryForTs(RelativePath, ParameterDescriptions);
            string uriText    = jsUriQuery == null ? $"this.baseUri + '{RelativePath}'" :
                                RemoveTrialEmptyString($"this.baseUri + '{jsUriQuery}'");

            if (ReturnTypeReference != null && ReturnTypeReference.BaseType == "System.String" && ReturnTypeReference.ArrayElementType == null)            //stringAsString is for .NET Core Web API
            {
                if (httpMethodName == "get" || httpMethodName == "delete")
                {
                    Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsForString}).then(d => d.text());"));                     //todo: type cast is not really needed.
                    return;
                }

                if (httpMethodName == "post" || httpMethodName == "put" || httpMethodName == "patch")
                {
                    if (RequestBodyCodeTypeReference == null)
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsForString}).then(d => d.text());"));
                    }
                    else
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {ContentOptionsForString}).then(d => d.text());"));
                    }

                    return;
                }
            }
            //else if (returnTypeText == FetchHttpStringResponse)//translated from response to this
            //{
            //	if (httpMethodName == "post" || httpMethodName == "put" || httpMethodName == "patch")
            //	{
            //		Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsForResponse}).then(d => d.text());"));
            //		return;
            //	}

            //	if (httpMethodName == "post" || httpMethodName == "put" || httpMethodName == "patch")
            //	{
            //		if (RequestBodyCodeTypeReference == null)
            //		{
            //			Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, null, {OptionsForResponse}).then(d => d.text());"));
            //		}
            //		else
            //		{
            //			Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, JSON.stringify(requestBody), {ContentOptionsForResponse});"));
            //		}

            //		return;
            //	}

            //}
            else if (returnTypeText == FetchHttpResponse)             // client should care about only status
            {
                if (httpMethodName == "get" || httpMethodName == "delete")
                {
                    Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {Options});"));
                    return;
                }

                if (httpMethodName == "post" || httpMethodName == "put" || httpMethodName == "patch")
                {
                    if (RequestBodyCodeTypeReference == null)
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {Options});"));
                    }
                    else
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsWithContent});"));
                    }

                    return;
                }
            }
            else
            {
                string returnTypeCast = returnTypeText == null ? String.Empty : $"<{returnTypeText}>";

                if (httpMethodName == "get" || httpMethodName == "delete")
                {
                    if (returnTypeText == null)
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsForResponse});"));                         //only http response needed
                    }
                    else
                    {
                        Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {Options}).then(d => d.json());"));
                    }
                }
                else if (httpMethodName == "post" || httpMethodName == "put" || httpMethodName == "patch")
                {
                    if (returnTypeText == null)                    //http response
                    {
                        if (RequestBodyCodeTypeReference == null)  //no content body
                        {
                            Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsForResponse});"));
                        }
                        else
                        {
                            Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {ContentOptionsForResponse});"));
                        }
                    }
                    else                                          // type is returned
                    {
                        if (RequestBodyCodeTypeReference == null) // no body
                        {
                            Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {Options}).then(d => d.json());"));
                        }
                        else
                        {
                            Method.Statements.Add(new CodeSnippetStatement($"return fetch({uriText}, {OptionsWithContent}).then(d => d.json());"));
                        }
                    }
                }
                else
                {
                    Debug.Assert(false, $"How come with {httpMethodName}?");
                }
            }
        }
    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)) {
            //    GENERATE (C#):      
            //    void Work(ref int i, out int j) {
            //             i = (i + 4);
            //             j = 5;
            //   }

            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "Work";
            cmm.ReturnType = new CodeTypeReference ("System.Void");
            // 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);

            // add a method that calls method work to verify that ref and out are working properly 
            // GENERATE (C#):
            //       public int CallingWork(int a) {
            //        a = 10;
            //        int b;
            //        Work(ref a, out b);
            //        return (a + b);
            //        }
            AddScenario ("CheckCallingWork", "Check the return value of CallingWork().");
            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 CodeMethodReferenceExpression (null,
                        "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);
        }
    }
Пример #48
0
        CodeMemberMethod GenerateMethod(CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers)
        {
            CodeIdentifiers  pids        = new CodeIdentifiers();
            CodeMemberMethod method      = new CodeMemberMethod();
            CodeMemberMethod methodBegin = new CodeMemberMethod();
            CodeMemberMethod methodEnd   = new CodeMemberMethod();

            method.Attributes      = MemberAttributes.Public | MemberAttributes.Final;
            methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            methodEnd.Attributes   = MemberAttributes.Public | MemberAttributes.Final;

            SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style;

            // Find unique names for temporary variables

            for (int n = 0; n < inputMembers.Count; n++)
            {
                pids.AddUnique(inputMembers[n].MemberName, inputMembers[n]);
            }

            if (outputMembers != null)
            {
                for (int n = 0; n < outputMembers.Count; n++)
                {
                    pids.AddUnique(outputMembers[n].MemberName, outputMembers[n]);
                }
            }

            string varAsyncResult = pids.AddUnique("asyncResult", "asyncResult");
            string varResults     = pids.AddUnique("results", "results");
            string varCallback    = pids.AddUnique("callback", "callback");
            string varAsyncState  = pids.AddUnique("asyncState", "asyncState");

            string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name), method);

            method.Name = CodeIdentifier.MakeValid(Operation.Name);
            if (method.Name == ClassName)
            {
                method.Name += "1";
            }
            methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name), method);
            methodEnd.Name   = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name), method);

            method.ReturnType    = new CodeTypeReference(typeof(void));
            methodEnd.ReturnType = new CodeTypeReference(typeof(void));
            methodEnd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), varAsyncResult));

            CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];
            CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0];

            for (int n = 0; n < inputMembers.Count; n++)
            {
                CodeParameterDeclarationExpression param = GenerateParameter(inputMembers[n], FieldDirection.In);
                method.Parameters.Add(param);
                GenerateMemberAttributes(inputMembers, inputMembers[n], bodyBinding.Use, param);
                methodBegin.Parameters.Add(GenerateParameter(inputMembers[n], FieldDirection.In));
                paramArray [n] = new CodeVariableReferenceExpression(param.Name);
            }

            if (outputMembers != null)
            {
                bool hasReturn = false;
                for (int n = 0; n < outputMembers.Count; n++)
                {
                    CodeParameterDeclarationExpression cpd = GenerateParameter(outputMembers[n], FieldDirection.Out);
                    outParams [n] = cpd;

                    bool found = false;
                    foreach (CodeParameterDeclarationExpression ip in method.Parameters)
                    {
                        if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType)
                        {
                            ip.Direction = FieldDirection.Ref;
                            methodEnd.Parameters.Add(GenerateParameter(outputMembers[n], FieldDirection.Out));
                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        continue;
                    }

                    if (!hasReturn)
                    {
                        hasReturn            = true;
                        method.ReturnType    = cpd.Type;
                        methodEnd.ReturnType = cpd.Type;
                        GenerateReturnAttributes(outputMembers, outputMembers[n], bodyBinding.Use, method);
                        outParams [n] = null;
                        continue;
                    }

                    method.Parameters.Add(cpd);
                    GenerateMemberAttributes(outputMembers, outputMembers[n], bodyBinding.Use, cpd);
                    methodEnd.Parameters.Add(GenerateParameter(outputMembers[n], FieldDirection.Out));
                }
            }

            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), varCallback));
            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), varAsyncState));
            methodBegin.ReturnType = new CodeTypeReference(typeof(IAsyncResult));

            // Array of input parameters

            CodeArrayCreateExpression methodParams;

            if (paramArray.Length > 0)
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), paramArray);
            }
            else
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), 0);
            }

            // Assignment of output parameters

            CodeStatementCollection         outAssign = new CodeStatementCollection();
            CodeVariableReferenceExpression arrVar    = new CodeVariableReferenceExpression(varResults);

            for (int n = 0; n < outParams.Length; n++)
            {
                CodeExpression index = new CodePrimitiveExpression(n);
                if (outParams[n] == null)
                {
                    CodeExpression res = new CodeCastExpression(method.ReturnType, new CodeArrayIndexerExpression(arrVar, index));
                    outAssign.Add(new CodeMethodReturnStatement(res));
                }
                else
                {
                    CodeExpression res = new CodeCastExpression(outParams[n].Type, new CodeArrayIndexerExpression(arrVar, index));
                    CodeExpression var = new CodeVariableReferenceExpression(outParams[n].Name);
                    outAssign.Insert(0, new CodeAssignStatement(var, res));
                }
            }

            if (Style == ServiceDescriptionImportStyle.Client)
            {
                // Invoke call

                CodeThisReferenceExpression      ethis      = new CodeThisReferenceExpression();
                CodePrimitiveExpression          varMsgName = new CodePrimitiveExpression(messageName);
                CodeMethodInvokeExpression       inv;
                CodeVariableDeclarationStatement dec;

                inv = new CodeMethodInvokeExpression(ethis, "Invoke", varMsgName, methodParams);
                if (outputMembers != null && outputMembers.Count > 0)
                {
                    dec = new CodeVariableDeclarationStatement(typeof(object[]), varResults, inv);
                    method.Statements.Add(dec);
                    method.Statements.AddRange(outAssign);
                }
                else
                {
                    method.Statements.Add(inv);
                }

                // Begin Invoke Call

                CodeExpression expCallb  = new CodeVariableReferenceExpression(varCallback);
                CodeExpression expAsyncs = new CodeVariableReferenceExpression(varAsyncState);
                inv = new CodeMethodInvokeExpression(ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs);
                methodBegin.Statements.Add(new CodeMethodReturnStatement(inv));

                // End Invoke call

                CodeExpression varAsyncr = new CodeVariableReferenceExpression(varAsyncResult);
                inv = new CodeMethodInvokeExpression(ethis, "EndInvoke", varAsyncr);
                if (outputMembers != null && outputMembers.Count > 0)
                {
                    dec = new CodeVariableDeclarationStatement(typeof(object[]), varResults, inv);
                    methodEnd.Statements.Add(dec);
                    methodEnd.Statements.AddRange(outAssign);
                }
                else
                {
                    methodEnd.Statements.Add(inv);
                }
            }
            else
            {
                method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
            }

            // Attributes

            ImportHeaders(method);

            CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.WebMethodAttribute");

            if (messageName != method.Name)
            {
                att.Arguments.Add(GetArg("MessageName", messageName));
            }
            AddCustomAttribute(method, att, (Style == ServiceDescriptionImportStyle.Server));

            if (style == SoapBindingStyle.Rpc)
            {
                att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapRpcMethodAttribute");
                att.Arguments.Add(GetArg(soapOper.SoapAction));
                if (inputMembers.ElementName != method.Name)
                {
                    att.Arguments.Add(GetArg("RequestElementName", inputMembers.ElementName));
                }
                if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response"))
                {
                    att.Arguments.Add(GetArg("ResponseElementName", outputMembers.ElementName));
                }
                att.Arguments.Add(GetArg("RequestNamespace", inputMembers.Namespace));
                if (outputMembers != null)
                {
                    att.Arguments.Add(GetArg("ResponseNamespace", outputMembers.Namespace));
                }
                if (outputMembers == null)
                {
                    att.Arguments.Add(GetArg("OneWay", true));
                }
            }
            else
            {
                if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" ||
                                              inputMembers.ElementName != "" && outputMembers.ElementName == ""))
                {
                    throw new InvalidOperationException("Parameter style is not the same for the input message and output message");
                }

                att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapDocumentMethodAttribute");
                att.Arguments.Add(GetArg(soapOper.SoapAction));
                if (inputMembers.ElementName != "")
                {
                    if (inputMembers.ElementName != method.Name)
                    {
                        att.Arguments.Add(GetArg("RequestElementName", inputMembers.ElementName));
                    }
                    if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response"))
                    {
                        att.Arguments.Add(GetArg("ResponseElementName", outputMembers.ElementName));
                    }
                    att.Arguments.Add(GetArg("RequestNamespace", inputMembers.Namespace));
                    if (outputMembers != null)
                    {
                        att.Arguments.Add(GetArg("ResponseNamespace", outputMembers.Namespace));
                    }
                    att.Arguments.Add(GetEnumArg("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped"));
                }
                else
                {
                    att.Arguments.Add(GetEnumArg("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare"));
                }

                if (outputMembers == null)
                {
                    att.Arguments.Add(GetArg("OneWay", true));
                }

                att.Arguments.Add(GetEnumArg("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString()));
            }

            AddCustomAttribute(method, att, true);

            CodeTypeDeclaration.Members.Add(method);

            if (Style == ServiceDescriptionImportStyle.Client)
            {
                CodeTypeDeclaration.Members.Add(methodBegin);
                CodeTypeDeclaration.Members.Add(methodEnd);
            }

            return(method);
        }
Пример #49
0
        protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e)
        {
            if (e.CustomAttributes.Count > 0)
            {
                OutputAttributeDeclarations(e.CustomAttributes);
                Output.Write(' ');
            }

            OutputDirection(e.Direction);
            OutputTypeNamePair(e.Type, e.Name);
        }
Пример #50
0
 void GenerateMemberAttributes(XmlMembersMapping members, XmlMemberMapping member, SoapBindingUse use, CodeParameterDeclarationExpression param)
 {
     if (use == SoapBindingUse.Literal)
     {
         xmlExporter.AddMappingMetadata(param.CustomAttributes, member, members.Namespace);
     }
     else
     {
         soapExporter.AddMappingMetadata(param.CustomAttributes, member);
     }
 }
Пример #51
0
 protected virtual void GenerateDefaultArgMethod(
     CodeParameterDeclarationExpression[] argList,
     CodeExpression[] paramList)
 {
     if (isStatic)
     {
         gen.StaticMethod(fnName, argList, () =>
         {
             gen.Return(gen.Appl(
                 new CodeVariableReferenceExpression(fnName),
                 paramList));
         });
     }
     else
     {
         gen.Method(fnName, argList, () =>
         {
             gen.Return(gen.Appl(
                 new CodeVariableReferenceExpression(fnName),
                 paramList));
         });
     }
 }
Пример #52
0
        protected CodeStatementCollection CreateMethodSignature(CodeTypeDeclaration tgtType, GMethod method,
                                                                bool isProxy)
        {
            bool add = true;
            CodeStatementCollection tgtStatements;
            CodeTypeMember          tgtMember;
            CodeMemberMethod        tgtMethod = null;
            CodeMemberPropertyEx    tgtProperty;
            CodeMemberPropertyEx    tgtEvent;

            if (method.IsConstructor)
            {
                var tgtConstructor = new CodeConstructor();
                tgtMethod     = tgtConstructor;
                tgtMember     = tgtMethod;
                tgtStatements = tgtMethod.Statements;
                if (!type.IsRootType)
                {
                    tgtConstructor.BaseConstructorArgs.Add(
                        new CodeCastExpression(TypeReference("net.sf.jni4net.jni.JNIEnv"),
                                               new CodePrimitiveExpression(null)));
                }
            }
            else if (method.IsField)
            {
                var p = new CodeMemberProperty();
                tgtMember     = p;
                tgtStatements = p.GetStatements;
                p.Name        = method.CLRName;
                p.Type        = method.ReturnType.CLRReference;
            }
            else if (method.IsEvent)
            {
                tgtEvent        = new CodeMemberPropertyEx();
                tgtEvent.Getter = method.CLRPropertyAdd;
                tgtEvent.Setter = method.CLRPropertyRemove;
                tgtEvent.Name   = method.CLRName;
                if (method.UseExplicitInterface)
                {
                    tgtEvent.PrivateImplementationType = method.DeclaringType.CLRReference;
                }

                foreach (CodeTypeMember m in tgtType.Members)
                {
                    var member = m as CodeMemberPropertyEx;
                    if (member != null)
                    {
                        if (member.Getter == method || member.Setter == method)
                        {
                            tgtEvent = member;
                            add      = false;
                            break;
                        }
                    }
                }
                int count = method.Parameters.Count - 1;
                tgtEvent.Type = method.Parameters[count].CLRReference;
                if (add)
                {
                    for (int i = 0; i < count; i++)
                    {
                        var tgtParameter = new CodeParameterDeclarationExpression();
                        tgtParameter.Name = method.ParameterNames[i];
                        tgtParameter.Type = method.Parameters[i].CLRReference;
                        tgtEvent.Parameters.Add(tgtParameter);
                    }
                    tgtEvent.Comments.Add(new CodeCommentStatement("__event__"));
                }

                tgtMember = tgtEvent;
                if (method.IsCLRPropertyAdd)
                {
                    tgtEvent.GetStatements.Add(new CodeCommentStatement("__add__"));
                    tgtStatements = tgtEvent.GetStatements;
                }
                else
                {
                    tgtEvent.SetStatements.Add(new CodeCommentStatement("__remove__"));
                    tgtStatements = tgtEvent.SetStatements;
                }
            }
            else if (method.IsProperty)
            {
                tgtProperty        = new CodeMemberPropertyEx();
                tgtProperty.Setter = method.CLRPropertySetter;
                tgtProperty.Getter = method.CLRPropertyGetter;
                tgtProperty.Name   = method.CLRName;
                if (method.UseExplicitInterface)
                {
                    tgtProperty.PrivateImplementationType = method.DeclaringType.CLRReference;
                }

                foreach (CodeTypeMember m in tgtType.Members)
                {
                    var member = m as CodeMemberPropertyEx;
                    if (member != null)
                    {
                        if (member.Getter == method || member.Setter == method)
                        {
                            tgtProperty = member;
                            add         = false;
                            break;
                        }
                    }
                }
                int count = method.Parameters.Count;
                if (!method.IsCLRPropertyGetter)
                {
                    count--;
                }
                if (add)
                {
                    for (int i = 0; i < count; i++)
                    {
                        var tgtParameter = new CodeParameterDeclarationExpression();
                        tgtParameter.Name = method.ParameterNames[i];
                        tgtParameter.Type = method.Parameters[i].CLRReference;
                        tgtProperty.Parameters.Add(tgtParameter);
                    }
                }

                if (method.IsCLRPropertyGetter)
                {
                    tgtProperty.Type = method.ReturnType.CLRReference;
                    tgtStatements    = tgtProperty.GetStatements;
                }
                else
                {
                    tgtProperty.Type = method.Parameters[count].CLRReference;
                    tgtStatements    = tgtProperty.SetStatements;
                }
                tgtMember = tgtProperty;
            }
            else
            {
                tgtMethod            = new CodeMemberMethod();
                tgtMethod.Name       = method.CLRName;
                tgtMethod.ReturnType = method.ReturnType.CLRReference;
                tgtMember            = tgtMethod;
                tgtStatements        = tgtMethod.Statements;
                if (method.UseExplicitInterface)
                {
                    tgtMethod.PrivateImplementationType = method.DeclaringType.CLRReference;
                }
            }
            if (!config.SkipSignatures && !isProxy)
            {
                Utils.AddAttribute(tgtMember, "net.sf.jni4net.attributes.JavaMethodAttribute", method.JVMSignature);
            }
            tgtMember.Attributes = method.Attributes;
            if (isProxy)
            {
                tgtMember.Attributes |= MemberAttributes.Final;
            }
            if (tgtMethod != null)
            {
                GenerateParameters(method, tgtMethod);
            }
            if (add)
            {
                tgtType.Members.Add(tgtMember);
            }
            return(tgtStatements);
        }
Пример #53
0
        public void TryCatchThrow()
        {
            var cd = new CodeTypeDeclaration();
            cd.Name = "Test";
            cd.IsClass = true;

            // try catch statement with just finally
            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "FirstScenario";
            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);

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Divide, new CodeVariableReferenceExpression("a"));
            CodeAssignStatement assignStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("a"), cboExpression);

            // try catch statement with just catch
            cmm = new CodeMemberMethod();
            cmm.Name = "SecondScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            CodeCatchClause catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(3)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);
            tcfstmt.FinallyStatements.Add(CreateVariableIncrementExpression("a", 1));

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));

            cd.Members.Add(cmm);

            // try catch statement with multiple catches
            cmm = new CodeMemberMethod();
            cmm.Name = "ThirdScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e", new CodeTypeReference(typeof(ArgumentNullException)));
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);

            // add a second catch clause
            catchClause = new CodeCatchClause("f", new CodeTypeReference(typeof(Exception)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "ToString")));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            tcfstmt.CatchClauses.Add(catchClause);

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            // catch throws exception
            cmm = new CodeMemberMethod();
            cmm.Name = "FourthScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeCommentStatement("Error handling"));
            catchClause.Statements.Add(new CodeThrowExceptionStatement(new CodeArgumentReferenceExpression("e")));
            tcfstmt.CatchClauses.Add(catchClause);
            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            AssertEqual(cd,
                @"Public Class Test
                      Public Shared Function FirstScenario(ByVal a As Integer) As Integer
                          Try
                          Finally
                              a = (a + 5)
                          End Try
                          Return a
                      End Function
                      Public Shared Function SecondScenario(ByVal a As Integer, ByVal exceptionMessage As String) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.Exception
                              a = 3
                              exceptionMessage = e.ToString
                          Finally
                              a = (a + 1)
                          End Try
                          Return a
                      End Function
                      Public Shared Function ThirdScenario(ByVal a As Integer, ByVal exceptionMessage As String) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.ArgumentNullException
                              a = 9
                              exceptionMessage = e.ToString
                          Catch f As System.Exception
                              exceptionMessage = f.ToString
                              a = 9
                          End Try
                          Return a
                      End Function
                      Public Shared Function FourthScenario(ByVal a As Integer) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.Exception
                              'Error handling
                              Throw e
                          End Try
                          Return a
                      End Function
                  End Class");
        }
Пример #54
0
        /// <summary>Generate a text description for the specified DiscoveryClientProtocol.</summary>
        /// <param name="protocol">A DiscoveryClientProtocol containing the information for the service.</param>
        /// <returns>An XmlDocument containing the generated xml for the specified discovery protocol.</returns>
        public static void GenerateWsdlXml(StringBuilder text, DiscoveryClientProtocol protocol)
        {
            // Code Namespace & Compile Unit
            var codeNamespace = new CodeNamespace();
            var codeUnit      = new CodeCompileUnit();

            codeUnit.Namespaces.Add(codeNamespace);

            // Import and set the warning
            ServiceDescriptionImporter importer = ReadServiceDescriptionImporter(protocol);

            importer.Import(codeNamespace, codeUnit);

            foreach (CodeTypeDeclaration type in codeNamespace.Types)
            {
                if (type.BaseTypes.Count == 0 || type.BaseTypes[0].BaseType != "System.Web.Services.Protocols.SoapHttpClientProtocol")
                {
                    continue;
                }

                text.AppendFormat("<big><b><u>{0}</u></b></big>\n\n", type.Name);
                string coms = GetCommentElements(type);
                if (coms != null)
                {
                    text.Append(coms).Append("\n\n");
                }

                foreach (CodeTypeMember mem in type.Members)
                {
                    var met = mem as CodeMemberMethod;
                    if (met != null && !(mem is CodeConstructor))
                    {
                        // Method
                        // Asynch Begin & End Results
                        string returnType = met.ReturnType.BaseType;
                        if (met.Name.StartsWith("Begin", StringComparison.Ordinal) && returnType == "System.IAsyncResult")
                        {
                            continue;                                   // BeginXXX method
                        }
                        if (met.Name.EndsWith("Async", StringComparison.Ordinal))
                        {
                            continue;
                        }
                        if (met.Name.StartsWith("On", StringComparison.Ordinal) && met.Name.EndsWith("Completed", StringComparison.Ordinal))
                        {
                            continue;
                        }
                        if (met.Parameters.Count > 0)
                        {
                            CodeParameterDeclarationExpression par = met.Parameters [met.Parameters.Count - 1];
                            if (met.Name.StartsWith("End", StringComparison.Ordinal) && par.Type.BaseType == "System.IAsyncResult")
                            {
                                continue;                                       // EndXXX method
                            }
                        }
                        text.AppendFormat("<b>{0}</b> (", met.Name);
                        // Parameters
                        for (int n = 0; n < met.Parameters.Count; n++)
                        {
                            CodeParameterDeclarationExpression par = met.Parameters [n];
                            if (n > 0)
                            {
                                text.Append(", ");
                            }
                            text.AppendFormat("{0}: <i>{1}</i>", par.Name, par.Type.BaseType);
                        }
                        text.Append(")");
                        if (returnType != "System.Void")
                        {
                            text.AppendFormat(": <i>{0}</i>", returnType);
                        }

                        // Comments
                        coms = GetCommentElements(met);
                        if (coms != null)
                        {
                            text.Append("\n").Append(coms);
                        }
                        text.Append("\n\n");
                    }
                }
            }
        }
Пример #55
0
        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");
        }
Пример #56
0
 internal static CodeVariableReferenceExpression Ref(this CodeParameterDeclarationExpression parameter)
 {
     return(new CodeVariableReferenceExpression(parameter.Name));
 }
Пример #57
0
        public void MethodWithRefParameter()
        {
            CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST");
            cd.IsClass = true;

            CodeMemberMethod 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);

            AssertEqual(cd,
                @"Public Class TEST
                  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
              End Class");
        }
Пример #58
0
 public void Visit(CodeParameterDeclarationExpression o)
 {
     g.GenerateParameterDeclarationExpression(o);
 }
Пример #59
0
        public void CastingOperations()
        {
            var cd = new CodeTypeDeclaration();
            cd.Name = "Test";
            cd.IsClass = true;

            // create method to test casting float to int
            CodeMemberMethod castReturnValue = new CodeMemberMethod();
            castReturnValue.Name = "CastReturnValue";
            castReturnValue.ReturnType = new CodeTypeReference(typeof(int));
            castReturnValue.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression strParam = new CodeParameterDeclarationExpression(typeof(string), "value");
            castReturnValue.Parameters.Add(strParam);
            castReturnValue.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(int), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Single"), "Parse", new CodeExpression[] { new CodeVariableReferenceExpression("value"), new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.Globalization.CultureInfo"), "InvariantCulture") }))));
            cd.Members.Add(castReturnValue);

            // create method to test casting interface -> class
            CodeMemberMethod castInterface = new CodeMemberMethod();
            castInterface.Name = "CastInterface";
            castInterface.ReturnType = new CodeTypeReference(typeof(string));
            castInterface.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression interfaceParam = new CodeParameterDeclarationExpression(typeof(System.ICloneable), "value");
            castInterface.Parameters.Add(interfaceParam);
            castInterface.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(string), new CodeVariableReferenceExpression("value"))));
            cd.Members.Add(castInterface);

            // create method to test casting value type -> reference type
            CodeMemberMethod valueToReference = new CodeMemberMethod();
            valueToReference.Name = "ValueToReference";
            valueToReference.ReturnType = new CodeTypeReference(typeof(System.Object));
            valueToReference.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression valueParam = new CodeParameterDeclarationExpression(typeof(int), "value");
            valueToReference.Parameters.Add(valueParam);
            valueToReference.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(typeof(System.Object), new CodeVariableReferenceExpression("value"))));
            cd.Members.Add(valueToReference);

            AssertEqual(cd,
                @"Public Class Test
                      Public Shared Function CastReturnValue(ByVal value As String) As Integer
                          Return CType(Single.Parse(value, System.Globalization.CultureInfo.InvariantCulture),Integer)
                      End Function
                      Public Shared Function CastInterface(ByVal value As System.ICloneable) As String
                          Return CType(value,String)
                      End Function
                      Public Shared Function ValueToReference(ByVal value As Integer) As Object
                          Return CType(value,Object)
                      End Function
                  End Class");
        }
Пример #60
0
        /// <summary>
        /// Generates an invoke operation.
        /// </summary>
        /// <param name="domainOperationEntry">The invoke operation.</param>
        /// <param name="invokeKind">the type of invoke method to generate.</param>
        private void GenerateInvokeOperation(DomainOperationEntry domainOperationEntry, InvokeKind invokeKind)
        {
            // Determine the name of the generated invoke function
            string methodName = domainOperationEntry.Name;

            // ----------------------------------------------------------------
            // Check for name conflicts
            // ----------------------------------------------------------------
            if ((invokeKind == InvokeKind.WithCallback) && this._proxyClass.Members.Cast <CodeTypeMember>().Any(c => c.Name == methodName && c.GetType() != typeof(CodeMemberMethod)))
            {
                this.ClientProxyGenerator.LogError(
                    string.Format(CultureInfo.CurrentCulture,
                                  Resource.ClientCodeGen_NamingCollision_MemberAlreadyExists,
                                  this._proxyClass.Name,
                                  methodName));
                return;
            }

            // ----------------------------------------------------------------
            // InvokeResult<T> InvokeOperation(args);
            //
            // InvokeResult<T> InvokeOperation(args, callback, userState);
            //
            // Task<T> InvokeOperationAsync(args);
            // ----------------------------------------------------------------
            CodeTypeReference operationReturnType = null;
            Type returnType           = CodeGenUtilities.TranslateType(domainOperationEntry.ReturnType);
            var  methodReturnTypeName = (invokeKind == InvokeKind.Async) ? TypeConstants.InvokeResultTypeFullName: TypeConstants.InvokeOperationTypeFullName;

            CodeTypeReference invokeOperationType = CodeGenUtilities.GetTypeReference(methodReturnTypeName, (string)this._proxyClass.UserData["Namespace"], false);

            if (returnType != typeof(void))
            {
                // If this is an enum type, we need to ensure it is either shared or
                // can be generated.  Failure to use this enum is only a warning and causes
                // this invoke operation to be skipped.  The test for legality also causes
                // the enum to be generated if required.
                Type enumType = TypeUtility.GetNonNullableType(returnType);
                if (enumType.IsEnum)
                {
                    string errorMessage = null;
                    if (!this.ClientProxyGenerator.CanExposeEnumType(enumType, out errorMessage))
                    {
                        this.ClientProxyGenerator.LogError(string.Format(CultureInfo.CurrentCulture,
                                                                         Resource.ClientCodeGen_Domain_Op_Enum_Error,
                                                                         methodName,
                                                                         this._proxyClass.Name,
                                                                         enumType.FullName,
                                                                         errorMessage));
                        return;
                    }
                    else
                    {
                        // Register use of this enum type, which could cause deferred generation
                        this.ClientProxyGenerator.RegisterUseOfEnumType(enumType);
                    }
                }

                operationReturnType          = CodeGenUtilities.GetTypeReference(returnType, this.ClientProxyGenerator, this._proxyClass);
                operationReturnType.Options |= CodeTypeReferenceOptions.GenericTypeParameter;
                invokeOperationType.TypeArguments.Add(operationReturnType);
            }

            // InvokeResults are wrapped in task (always)
            if (invokeKind == InvokeKind.Async)
            {
                invokeOperationType = new CodeTypeReference(typeof(Task).FullName, invokeOperationType);
            }


            CodeMemberMethod method = new CodeMemberMethod()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name       = (invokeKind == InvokeKind.Async) ? (methodName + "Async") : methodName,
                ReturnType = invokeOperationType,
            };

            this._proxyClass.Members.Add(method);

            ReadOnlyCollection <DomainOperationParameter> operationParameters = domainOperationEntry.Parameters;

            // Generate the <summary> doc comments
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_DomainContext_Invoke_Method_Summary_Comment, domainOperationEntry.Name);

            method.Comments.AddRange(CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Generate <param> doc comments
            foreach (DomainOperationParameter parameter in operationParameters)
            {
                comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_DomainContext_Invoke_Method_Parameter_Comment, parameter.Name);
                method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment(parameter.Name, comment, this.ClientProxyGenerator.IsCSharp));
            }

            // Conditionally add the callback and userState <param> doc comments
            if (invokeKind == InvokeKind.WithCallback)
            {
                method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment("callback", Resource.CodeGen_DomainContext_Invoke_Method_Callback_Parameter_Comment, this.ClientProxyGenerator.IsCSharp));
                method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment("userState", Resource.CodeGen_DomainContext_Invoke_Method_UserState_Parameter_Comment, this.ClientProxyGenerator.IsCSharp));
            }
            else if (invokeKind == InvokeKind.Async)
            {
                method.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment("cancellationToken", Resource.CodeGen_DomainContext_Invoke_Method_CancellationToken_Parameter_Comment, this.ClientProxyGenerator.IsCSharp));
            }

            // Generate <returns> doc comments
            method.Comments.AddRange(CodeGenUtilities.GenerateReturnsCodeComment(Resource.CodeGen_DomainContext_Invoke_Returns_Comment, this.ClientProxyGenerator.IsCSharp));

            // Propagate custom validation attributes from the DomainOperationEntry to this invoke operation.
            IEnumerable <Attribute> methodAttributes = domainOperationEntry.Attributes.Cast <Attribute>();

            CustomAttributeGenerator.GenerateCustomAttributes(
                this.ClientProxyGenerator,
                this._proxyClass,
                ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethod, ex.Message, method.Name, this._proxyClass.Name, ex.InnerException.Message),
                methodAttributes,
                method.CustomAttributes,
                method.Comments);

            // ----------------------------------------------------------------
            // generate invoke operation body:
            //     return base.InvokeOperation<T>(methodName, typeof(T), parameters, hasSideEffects, callback, userState);
            // or  return base.InvokeOperationAsync<T>(methodName, parameters, hasSideEffects);
            // ----------------------------------------------------------------
            List <CodeExpression> invokeParams = new List <CodeExpression>();

            invokeParams.Add(new CodePrimitiveExpression(methodName));

            // add the return Type parameter
            if (invokeKind != InvokeKind.Async)
            {
                invokeParams.Add(new CodeTypeOfExpression(operationReturnType));
            }

            // add any operation parameters

            CodeVariableReferenceExpression paramsRef = new CodeVariableReferenceExpression("parameters");

            if (operationParameters.Count > 0)
            {
                // need to generate the user parameters dictionary
                CodeTypeReference dictionaryTypeReference = CodeGenUtilities.GetTypeReference(
                    typeof(Dictionary <string, object>),
                    this.ClientProxyGenerator,
                    this._proxyClass);

                CodeVariableDeclarationStatement paramsDef = new CodeVariableDeclarationStatement(
                    dictionaryTypeReference,
                    "parameters",
                    new CodeObjectCreateExpression(dictionaryTypeReference, Array.Empty <CodeExpression>()));
                method.Statements.Add(paramsDef);
            }
            foreach (DomainOperationParameter paramInfo in operationParameters)
            {
                // If this is an enum type, we need to ensure it is either shared or
                // can be generated.  Failure to use this enum logs an error and exits.
                // The test for legality also causes the enum to be generated if required.
                Type enumType = TypeUtility.GetNonNullableType(paramInfo.ParameterType);
                if (enumType.IsEnum)
                {
                    string errorMessage = null;
                    if (!this.ClientProxyGenerator.CanExposeEnumType(enumType, out errorMessage))
                    {
                        this.ClientProxyGenerator.LogError(string.Format(CultureInfo.CurrentCulture,
                                                                         Resource.ClientCodeGen_Domain_Op_Enum_Error,
                                                                         method.Name,
                                                                         this._proxyClass.Name,
                                                                         enumType.FullName,
                                                                         errorMessage));
                        return;
                    }
                    else
                    {
                        // Register use of this enum type, which could cause deferred generation
                        this.ClientProxyGenerator.RegisterUseOfEnumType(enumType);
                    }
                }

                // add the parameter to the method
                CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(
                    CodeGenUtilities.GetTypeReference(
                        CodeGenUtilities.TranslateType(paramInfo.ParameterType),
                        this.ClientProxyGenerator,
                        this._proxyClass),
                    paramInfo.Name);

                // Propagate parameter level validation attributes from domain operation entry
                IEnumerable <Attribute> paramAttributes = paramInfo.Attributes.Cast <Attribute>();

                string commentHeader =
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resource.ClientCodeGen_Attribute_Parameter_FailedToGenerate,
                        paramInfo.Name);

                CustomAttributeGenerator.GenerateCustomAttributes(
                    this.ClientProxyGenerator,
                    this._proxyClass,
                    ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethodParameter, ex.Message, paramDecl.Name, method.Name, this._proxyClass.Name, ex.InnerException.Message),
                    paramAttributes,
                    paramDecl.CustomAttributes,
                    method.Comments,
                    commentHeader);

                method.Parameters.Add(paramDecl);

                // add the parameter and value to the params dictionary
                method.Statements.Add(new CodeMethodInvokeExpression(
                                          new CodeMethodReferenceExpression(paramsRef, "Add"),
                                          new CodePrimitiveExpression(paramInfo.Name),
                                          new CodeVariableReferenceExpression(paramInfo.Name)));
            }

            // add parameters if present
            if (operationParameters.Count > 0)
            {
                invokeParams.Add(paramsRef);
            }
            else
            {
                invokeParams.Add(new CodePrimitiveExpression(null));
            }

            InvokeAttribute invokeAttribute = (InvokeAttribute)domainOperationEntry.OperationAttribute;

            invokeParams.Add(new CodePrimitiveExpression(invokeAttribute.HasSideEffects));

            switch (invokeKind)
            {
            case InvokeKind.WithCallback:
            {
                CodeTypeReference callbackType = CodeGenUtilities.GetTypeReference(typeof(Action).FullName, (string)this._proxyClass.UserData["Namespace"], false);
                callbackType.TypeArguments.Add(invokeOperationType);

                // add callback method parameter
                method.Parameters.Add(new CodeParameterDeclarationExpression(callbackType, "callback"));
                invokeParams.Add(new CodeVariableReferenceExpression("callback"));

                // add the userState parameter to the end
                method.Parameters.Add(new CodeParameterDeclarationExpression(CodeGenUtilities.GetTypeReference(typeof(object), this.ClientProxyGenerator, this._proxyClass), "userState"));
                invokeParams.Add(new CodeVariableReferenceExpression("userState"));
            }
            break;

            case InvokeKind.WithoutCallback:
                invokeParams.Add(new CodePrimitiveExpression(null));
                invokeParams.Add(new CodePrimitiveExpression(null));
                break;

            case InvokeKind.Async:
                var cancellationTokenType     = CodeGenUtilities.GetTypeReference(typeof(CancellationToken), this.ClientProxyGenerator, this._proxyClass);
                var cancellationTokenParmeter = new CodeParameterDeclarationExpression(cancellationTokenType, "cancellationToken");

                // For C# add "  = default(CancellationToken)"
                // For VB add "Optional" ByVal .... = Nothing
                // otherwise fall back to adding [Optional] attribute, this is the same as adding "= default(CancellationToken)"
                if (ClientProxyGenerator.IsCSharp)
                {
                    cancellationTokenParmeter.Name = string.Format("{0} = default({1})", cancellationTokenParmeter.Name, cancellationTokenType.BaseType);
                }
                else if (ClientProxyGenerator.IsVB)     // VB
                {
                    // Set an invalid field direction in order to have VB Code gen from generating
                    cancellationTokenParmeter.Direction = (FieldDirection)0xff;
                    cancellationTokenParmeter.Name      = "Optional ByVal " + cancellationTokenParmeter.Name;
                    cancellationTokenParmeter.Type      = new CodeTypeReference(cancellationTokenType.BaseType + " = Nothing");
                }
                else
                {
                    // Add [Optional] attribute
                    cancellationTokenParmeter.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                                       CodeGenUtilities.GetTypeReference(typeof(OptionalAttribute), this.ClientProxyGenerator, this._proxyClass)));
                }

                method.Parameters.Add(cancellationTokenParmeter);
                invokeParams.Add(new CodeVariableReferenceExpression("cancellationToken"));
                break;
            }

            // this.ValidateMethod("methodName", parameters);
            CodeExpression paramsExpr = new CodePrimitiveExpression(null);

            if (operationParameters.Count > 0)
            {
                paramsExpr = paramsRef;
            }
            CodeExpressionStatement validateMethodCall = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    "ValidateMethod",
                    new CodeExpression[]
            {
                new CodePrimitiveExpression(methodName),
                paramsExpr
            }));

            method.Statements.Add(validateMethodCall);

            var invokeMethod          = (invokeKind == InvokeKind.Async) ? "InvokeOperationAsync" : "InvokeOperation";
            var typeParameters        = (domainOperationEntry.ReturnType == typeof(void)) ? Array.Empty <CodeTypeReference>() : new[] { operationReturnType };
            var invokeMethodReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), invokeMethod, typeParameters);

            CodeExpression invokeCall = new CodeMethodInvokeExpression(invokeMethodReference, invokeParams.ToArray());

            method.Statements.Add(new CodeMethodReturnStatement(invokeCall));
        }