Example #1
0
        private static void AddConstructorWithCopiedParameters(CodeTypeDeclaration codeType, Type implementationType, CodeFieldReferenceExpression omObjectFieldReference, ConstructorInfo constructorInfo)
        {
            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;

            ParameterInfo[]  parameters             = constructorInfo.GetParameters();
            CodeExpression[] codeArgumentReferences = new CodeExpression[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                bool isOmTypeArg = false;

                string paramType = parameters[i].ParameterType.FullName;
                if (OMtoPSClassMappings.ContainsKey(paramType))
                {
                    paramType   = OMtoPSClassMappings[paramType];
                    isOmTypeArg = true;
                }

                string paramName = parameters[i].Name;
                string passedInArg;

                // Create the proper parameter for optional
                if (parameters[i].IsOptional)
                {
                    paramName = paramType.Contains("System")
                        ? string.Format("{0} = null", parameters[i].Name)
                        : string.Format("{0} = default({1})", parameters[i].Name, paramType);
                }

                // Need to do a null check for calling an omObject from a PS wrapper class
                if (isOmTypeArg && parameters[i].IsOptional)
                {
                    CodeVariableDeclarationStatement omObjectDeclaration = new CodeVariableDeclarationStatement(
                        parameters[i].ParameterType,
                        string.Format("{0}{1}", parameters[i].Name, "OmObject"),
                        new CodePrimitiveExpression(null));

                    constructor.Statements.Add(omObjectDeclaration);

                    CodeArgumentReferenceExpression omObjectArgumentReference = new CodeArgumentReferenceExpression(parameters[i].Name);
                    CodeAssignStatement             omObjectAssignStatement   = new CodeAssignStatement(new CodeVariableReferenceExpression(string.Format("{0}{1}", parameters[i].Name, "OmObject")), new CodeVariableReferenceExpression(string.Format("{0}.{1}", parameters[i].Name, OmObject)));
                    CodeBinaryOperatorExpression    nullCheck = new CodeBinaryOperatorExpression(omObjectArgumentReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));

                    // if the parameter is not null, use the omObject of the PS Wrapper class
                    constructor.Statements.Add(new CodeConditionStatement(nullCheck, omObjectAssignStatement));

                    passedInArg = string.Format("{0}{1}", parameters[i].Name, "OmObject");
                }
                else if (isOmTypeArg)
                {
                    passedInArg = string.Format("{0}.{1}", parameters[i].Name, OmObject);
                }
                else
                {
                    passedInArg = parameters[i].Name;
                }

                codeArgumentReferences[i] = new CodeArgumentReferenceExpression(passedInArg);
                constructor.Parameters.Add(new CodeParameterDeclarationExpression(paramType, paramName));
            }

            CodeObjectCreateExpression createExpression = new CodeObjectCreateExpression(implementationType, codeArgumentReferences);

            constructor.Statements.Add(new CodeAssignStatement(omObjectFieldReference, createExpression));
            codeType.Members.Add(constructor);
        }
        protected virtual void GenerateMethods(CodeTypeDeclaration targetClass, Type baseType, IEnumerable <MethodInfo> methods)
        {
            if (methods.Any() == true)
            {
                var finalizeMethod = methods.First().DeclaringType.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance);

                foreach (var method in methods)
                {
                    if (method == finalizeMethod)
                    {
                        continue;
                    }

                    if (method.IsSpecialName == true)
                    {
                        continue;
                    }

                    var m = new CodeMemberMethod();
                    m.Name       = method.Name;
                    m.ReturnType = new CodeTypeReference(method.ReturnType);

                    if (baseType != interfaceProxyType)
                    {
                        m.Attributes = MemberAttributes.Override;
                    }

                    targetClass.Members.Add(m);

                    foreach (var parameter in method.GetParameters())
                    {
                        m.Parameters.Add(new CodeParameterDeclarationExpression(parameter.ParameterType, parameter.Name));
                    }

                    if ((method.Attributes & MethodAttributes.Public) == MethodAttributes.Public)
                    {
                        m.Attributes |= MemberAttributes.Public;
                    }
                    else if ((method.Attributes & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem)
                    {
                        m.Attributes |= MemberAttributes.FamilyOrAssembly;
                    }
                    else if ((method.Attributes & MethodAttributes.Family) == MethodAttributes.Family)
                    {
                        m.Attributes |= MemberAttributes.Family;
                    }
                    else if ((method.Attributes & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem)
                    {
                        m.Attributes |= MemberAttributes.FamilyAndAssembly;
                    }

                    if (baseType == interfaceProxyType)
                    {
                        m.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    }

                    var currentMethod  = new CodeVariableDeclarationStatement(typeof(MethodInfo), "currentMethod", new CodeCastExpression(typeof(MethodInfo), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(MethodBase)), "GetCurrentMethod"))));
                    var getType        = new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance"), "GetType");
                    var getMethod      = new CodeMethodInvokeExpression(getType, "GetMethod", new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentMethod"), "Name"));
                    var originalMethod = new CodeVariableDeclarationStatement(typeof(MethodInfo), "originalMethod", getMethod);

                    m.Statements.Add(currentMethod);
                    m.Statements.Add(originalMethod);

                    var ps = new CodeExpression[] { new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance"), new CodeVariableReferenceExpression("originalMethod") }.Concat(method.GetParameters().Select(x => new CodeVariableReferenceExpression(x.Name))).ToArray();
                    var arg = new CodeVariableDeclarationStatement(typeof(InterceptionArgs), "args", new CodeObjectCreateExpression(typeof(InterceptionArgs), ps));

                    m.Statements.Add(arg);

                    var handler = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "handler"), "Invoke"), new CodeVariableReferenceExpression("args"));
                    m.Statements.Add(handler);

                    var comparison             = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Handled"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(method.ReturnType != typeof(void)));
                    CodeConditionStatement @if = null;

                    if (method.ReturnType != typeof(void))
                    {
                        if (baseType != interfaceProxyType)
                        {
                            @if = new CodeConditionStatement(comparison, new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Result"))));

                            m.Statements.Add(@if);
                            m.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), method.Name, method.GetParameters().Select(x => new CodeArgumentReferenceExpression(x.Name)).ToArray())));
                        }
                        else
                        {
                            @if = new CodeConditionStatement(comparison, new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Result"))));

                            m.Statements.Add(@if);
                            m.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeCastExpression(method.DeclaringType, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance")), m.Name), method.GetParameters().Select(x => new CodeArgumentReferenceExpression(x.Name)).ToArray())));
                        }
                    }
                    else
                    {
                        if (baseType != interfaceProxyType)
                        {
                            @if = new CodeConditionStatement(comparison, new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), method.Name, method.GetParameters().Select(x => new CodeArgumentReferenceExpression(x.Name)).ToArray())));

                            m.Statements.Add(@if);
                        }
                        else
                        {
                            @if = new CodeConditionStatement(comparison, new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Result"))));

                            m.Statements.Add(@if);
                            m.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeCastExpression(method.DeclaringType, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance")), m.Name), method.GetParameters().Select(x => new CodeArgumentReferenceExpression(x.Name)).ToArray())));
                        }
                    }
                }
            }
        }
        public virtual object Serialize(IDesignerSerializationManager manager, object value)
        {
            object obj2 = null;

            if ((manager == null) || (value == null))
            {
                throw new ArgumentNullException((manager == null) ? "manager" : "value");
            }
            using (CodeDomSerializerBase.TraceScope("CodeDomSerializer::Serialize"))
            {
                bool flag2;
                bool flag3;
                if (value is Type)
                {
                    return(new CodeTypeOfExpression((Type)value));
                }
                bool           flag       = false;
                CodeExpression expression = base.SerializeCreationExpression(manager, value, out flag2);
                if (!(value is IComponent))
                {
                    flag = flag2;
                }
                ExpressionContext context = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
                if ((context != null) && object.ReferenceEquals(context.PresetValue, value))
                {
                    flag3 = true;
                }
                else
                {
                    flag3 = false;
                }
                if (expression == null)
                {
                    return(obj2);
                }
                if (flag)
                {
                    return(expression);
                }
                CodeStatementCollection statements = new CodeStatementCollection();
                if (flag3)
                {
                    base.SetExpression(manager, value, expression, true);
                }
                else
                {
                    string uniqueName = base.GetUniqueName(manager, value);
                    CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(TypeDescriptor.GetClassName(value), uniqueName)
                    {
                        InitExpression = expression
                    };
                    statements.Add(statement);
                    CodeExpression expression2 = new CodeVariableReferenceExpression(uniqueName);
                    base.SetExpression(manager, value, expression2);
                }
                base.SerializePropertiesToResources(manager, statements, value, _designTimeFilter);
                base.SerializeProperties(manager, statements, value, _runTimeFilter);
                base.SerializeEvents(manager, statements, value, _runTimeFilter);
                return(statements);
            }
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        //  namespace Namespace1 {
        //      using System;
        //      
        //      
        //      public class Class1 : object {
        //          
        //          public int ReturnMethod(int intInput) {

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

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Class1";
        class1.BaseTypes.Add (new CodeTypeReference (typeof (object)));
        ns.Types.Add (class1);

        AddScenario ("CheckReturnMethod", "Tests varying operators.");
        CodeMemberMethod retMethod = new CodeMemberMethod ();
        retMethod.Name = "ReturnMethod";
        retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
        retMethod.ReturnType = new CodeTypeReference (typeof (int));
        retMethod.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "intInput"));

        // GENERATES (C#):
        //              int x1 = ((18 
        //                          / (6 - 4)) 
        //                          * intInput);
        //
        // in VB (a = a/a) generates an warning if a is integer. Cast the expression just for VB language. 
        CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression (
            new CodeBinaryOperatorExpression (
            new CodePrimitiveExpression (18),
            CodeBinaryOperatorType.Divide,
            new CodeBinaryOperatorExpression (
            new CodePrimitiveExpression (6),
            CodeBinaryOperatorType.Subtract,
            new CodePrimitiveExpression (4))),
            CodeBinaryOperatorType.Multiply,
            new CodeArgumentReferenceExpression ("intInput"));

        CodeVariableDeclarationStatement variableDeclaration = null;
        if (provider is Microsoft.VisualBasic.VBCodeProvider)
            variableDeclaration = new CodeVariableDeclarationStatement (typeof (int), "x1", new CodeCastExpression (typeof (int), cboExpression));
        else
            variableDeclaration = new CodeVariableDeclarationStatement (typeof (int), "x1", cboExpression);

        retMethod.Statements.Add (variableDeclaration);

        // GENERATES (C#):
        //              int x2 = (19 % 8);
        retMethod.Statements.Add (
            new CodeVariableDeclarationStatement (
            typeof (int),
            "x2",
            new CodeBinaryOperatorExpression (
            new CodePrimitiveExpression (19),
            CodeBinaryOperatorType.Modulus,
            new CodePrimitiveExpression (8))));

        // GENERATES (C#):
        //              int x3 = ((15 & 35) 
        //                          | 129);
        retMethod.Statements.Add (
            new CodeVariableDeclarationStatement (
            typeof (int),
            "x3",
            new CodeBinaryOperatorExpression (
            new CodeBinaryOperatorExpression (
            new CodePrimitiveExpression (15),
            CodeBinaryOperatorType.BitwiseAnd,
            new CodePrimitiveExpression (35)),
            CodeBinaryOperatorType.BitwiseOr,
            new CodePrimitiveExpression (129))));

        // GENERATES (C#):
        //              int x4 = 0;
        retMethod.Statements.Add (
            new CodeVariableDeclarationStatement (
            typeof (int),
            "x4",
            new CodePrimitiveExpression (0)));

        // GENERATES (C#):
        //              if (((x2 == 3) 
        //                          || (x3 < 129))) {
        //                  x4 = (x4 + 1);
        //              }
        //              else {
        //                  x4 = (x4 + 2);
        //              }

        retMethod.Statements.Add (
            new CodeConditionStatement (
            new CodeBinaryOperatorExpression (
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x2"),
            CodeBinaryOperatorType.ValueEquality,
            new CodePrimitiveExpression (3)),
            CodeBinaryOperatorType.BooleanOr,
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x3"),
            CodeBinaryOperatorType.LessThan,
            new CodePrimitiveExpression (129))),
            CDHelper.CreateIncrementByStatement ("x4", 1),
            CDHelper.CreateIncrementByStatement ("x4", 2)));

        // GENERATES (C#):
        //              if (((x2 > -1) 
        //                          && (x3 >= 5000))) {
        //                  x4 = (x4 + 4);
        //              }
        //              else {
        //                  x4 = (x4 + 8);
        //              }
        retMethod.Statements.Add (
            new CodeConditionStatement (
            new CodeBinaryOperatorExpression (
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x2"),
            CodeBinaryOperatorType.GreaterThan,
            new CodePrimitiveExpression (-1)),
            CodeBinaryOperatorType.BooleanAnd,
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x3"),
            CodeBinaryOperatorType.GreaterThanOrEqual,
            new CodePrimitiveExpression (5000))),
            CDHelper.CreateIncrementByStatement ("x4", 4),
            CDHelper.CreateIncrementByStatement ("x4", 8)));

        // GENERATES (C#):
        //              if (((x2 <= 3) 
        //                          && (x3 != 1))) {
        //                  x4 = (x4 + 16);
        //              }
        //              else {
        //                  x4 = (x4 + 32);
        //              }
        retMethod.Statements.Add (
            new CodeConditionStatement (
            new CodeBinaryOperatorExpression (
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x2"),
            CodeBinaryOperatorType.LessThanOrEqual,
            new CodePrimitiveExpression (3)),
            CodeBinaryOperatorType.BooleanAnd,
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x3"),
            CodeBinaryOperatorType.IdentityInequality,
            new CodePrimitiveExpression (1))),
            CDHelper.CreateIncrementByStatement ("x4", 16),
            CDHelper.CreateIncrementByStatement ("x4", 32)));


        // GENERATES (C#):
        //              return (x1 
        //                          + (x2 
        //                          + (x3 + x4)));
        //          }
        retMethod.Statements.Add (
            new CodeMethodReturnStatement (
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x1"),
            CodeBinaryOperatorType.Add,
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x2"),
            CodeBinaryOperatorType.Add,
            new CodeBinaryOperatorExpression (
            new CodeVariableReferenceExpression ("x3"),
            CodeBinaryOperatorType.Add,
            new CodeVariableReferenceExpression ("x4"))))));
        class1.Members.Add (retMethod);

        //          
        // GENERATES (C#):
        //          public int SecondReturnMethod(int intInput) {
        //              // To test CodeBinaryOperatorType.IdentityEquality operator
        //              if ((((Object)(intInput)) == ((Object)(5)))) {
        //                  return 5;
        //              }
        //              else {
        //                  return 4;
        //              }
        //          }
        //      }
        AddScenario ("CheckSecondReturnMethod", "Tests identity equality.");
        retMethod = new CodeMemberMethod ();
        retMethod.Name = "SecondReturnMethod";
        retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
        retMethod.ReturnType = new CodeTypeReference (typeof (int));
        retMethod.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "intInput"));

        retMethod.Statements.Add (new CodeCommentStatement ("To test CodeBinaryOperatorType.IdentiEquality operator"));
        retMethod.Statements.Add (
            new CodeConditionStatement (
            new CodeBinaryOperatorExpression (new CodeCastExpression ("Object",
            new CodeArgumentReferenceExpression ("intInput")),
            CodeBinaryOperatorType.IdentityEquality, new CodeCastExpression ("Object",
            new CodePrimitiveExpression (5))),
            new CodeStatement[] {new CodeMethodReturnStatement (new
                CodePrimitiveExpression (5))}, new CodeStatement[] {new
                CodeMethodReturnStatement (new CodePrimitiveExpression (4))}));
        class1.Members.Add (retMethod);

        // GENERATES (C#):
        //      public class Class2 : object {
        //      }
        //  }

        /*class1 = new CodeTypeDeclaration ();
        class1.Name = "Class2";
        class1.BaseTypes.Add (new CodeTypeReference (typeof (object)));
        ns.Types.Add (class1);*/
    }
        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");
        }
 private static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent)
 {
     CodeObjectCreateExpression expression;
     CodeMemberMethod method = new CodeMemberMethod();
     method.Attributes = MemberAttributes.Private;
     method.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations);
     method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state"));
     method.ReturnType = new CodeTypeReference(voidType);
     CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e");
     statement.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName, new CodeArgumentReferenceExpression(method.Parameters[0].Name));
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression(statement.Name);
     if (operationCompletedEventArgsType != null)
     {
         expression = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[0]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) });
     }
     else
     {
         expression = new CodeObjectCreateExpression(asyncCompletedEventArgsType, new CodeExpression[] { new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[1]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[2]), new CodePropertyReferenceExpression(targetObject, EventArgsPropertyNames[3]) });
     }
     CodeEventReferenceExpression expression3 = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name);
     CodeDelegateInvokeExpression expression4 = new CodeDelegateInvokeExpression(expression3, new CodeExpression[] { new CodeThisReferenceExpression(), expression });
     CodeConditionStatement statement2 = new CodeConditionStatement(new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), new CodeStatement[] { statement, new CodeExpressionStatement(expression4) });
     method.Statements.Add(statement2);
     clientType.Members.Add(method);
     return method;
 }
        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) {
                          }
                      }
                  }");
        }
Example #8
0
        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);
        }
Example #9
0
        public static CodePropertyReferenceExpression DefineProperty(this Type fieldType,
                                                                     CodeTypeDeclaration codeTypeDeclaration,
                                                                     CodeFieldReferenceExpression
                                                                     codeFieldReferenceExpression,
                                                                     string propertyName,
                                                                     bool?autoGenerateField  = null,
                                                                     bool?autoGenerateFilter = null,
                                                                     Action <CodeMemberProperty> customization = null)
        {
            //var propertyName = string.Format("{0}{1}", propertyNamePrefix, propertyInfo.Name);
            //var fieldType = propertyInfo.PropertyType.FullName;

            //generate property getter and setter
            var property = new CodeMemberProperty
            {
                Name       = string.Format(propertyName),
                Type       = new CodeTypeReference(fieldType),
                Attributes = MemberAttributes.Public
            };

            //Add [Display] Attribute
            property.DefineDisplayAttribute(autoGenerateField, autoGenerateFilter);

            var codePropertySetValueReferenceExpression = new CodePropertySetValueReferenceExpression();

            #region getter

            property.GetStatements.Add(new CodeMethodReturnStatement(codeFieldReferenceExpression));

            #endregion

            #region setter

            //if (_PropValue == value) return;
            property.SetStatements.Add(
                new CodeConditionStatement(new CodeBinaryOperatorExpression(codeFieldReferenceExpression,
                                                                            CodeBinaryOperatorType.ValueEquality,
                                                                            codePropertySetValueReferenceExpression),
                                           new CodeMethodReturnStatement()));


            var beforeVariableDeclaration = new CodeVariableDeclarationStatement(typeof(object), "before");
            var beforeVariableReference   = new CodeVariableReferenceExpression("before");

            //object before;
            property.SetStatements.Add(beforeVariableDeclaration);

            //before = _PropValue;
            property.SetStatements.Add(new CodeAssignStatement(beforeVariableReference,
                                                               codeFieldReferenceExpression));

            //_PropValue = value;
            property.SetStatements.Add(new CodeAssignStatement(codeFieldReferenceExpression,
                                                               codePropertySetValueReferenceExpression));


            var onPropertyChangedMethodReference =
                new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "OnPropertyChanged");

            //OnPropertyChanged("PropertyName",before,value)
            property.SetStatements.Add(new CodeMethodInvokeExpression(onPropertyChangedMethodReference,
                                                                      new CodePrimitiveExpression(propertyName),
                                                                      beforeVariableReference,
                                                                      codePropertySetValueReferenceExpression));

            #endregion

            //customize definition...
            if (customization != null)
            {
                customization(property);
            }


            var codePropertyReferenceExpression = new CodePropertyReferenceExpression(
                new CodeThisReferenceExpression(), propertyName);

            return(codePropertyReferenceExpression);
        }
        /*
         * Build the default constructor
         */
        protected override void BuildDefaultConstructor()
        {
            base.BuildDefaultConstructor();

            if (CompilParams.IncludeDebugInformation)
            {
                // If in debug mode, set the timeout to some huge value (ASURT 49427)
                //      Server.ScriptTimeout = 30000000;
                CodeAssignStatement setScriptTimeout = new CodeAssignStatement();
                setScriptTimeout.Left = new CodePropertyReferenceExpression(
                    new CodePropertyReferenceExpression(
                        new CodeThisReferenceExpression(), "Server"),
                    "ScriptTimeout");
                setScriptTimeout.Right = new CodePrimitiveExpression(DebugScriptTimeout);
                InitMethod.Statements.Add(setScriptTimeout);
            }

            if (Parser.TransactionMode != 0 /*TransactionOption.Disabled*/)
            {
                InitMethod.Statements.Add(new CodeAssignStatement(
                                              new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "TransactionMode"),
                                              new CodePrimitiveExpression(Parser.TransactionMode)));
            }

            if (Parser.AspCompatMode)
            {
                InitMethod.Statements.Add(new CodeAssignStatement(
                                              new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "AspCompatMode"),
                                              new CodePrimitiveExpression(Parser.AspCompatMode)));
            }

            if (Parser.AsyncMode)
            {
                InitMethod.Statements.Add(new CodeAssignStatement(
                                              new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "AsyncMode"),
                                              new CodePrimitiveExpression(Parser.AsyncMode)));
            }

            if (Parser.OutputCacheParameters != null)
            {
                OutputCacheParameters cacheSettings = Parser.OutputCacheParameters;
                if ((cacheSettings.CacheProfile != null && cacheSettings.CacheProfile.Length != 0) ||
                    cacheSettings.Duration != 0 ||
                    cacheSettings.Location == OutputCacheLocation.None)
                {
                    // Add the following code snippet as a static on the class:
                    //
                    // private static OutputCacheParameters __outputCacheSettings = null;
                    //
                    CodeMemberField outputCacheSettingsField = new CodeMemberField(typeof(OutputCacheParameters), outputCacheSettingsFieldName);
                    outputCacheSettingsField.Attributes    |= MemberAttributes.Static;
                    outputCacheSettingsField.InitExpression = new CodePrimitiveExpression(null);
                    _sourceDataClass.Members.Add(outputCacheSettingsField);

                    // Then, add the following code to the default constructor:
                    //
                    // if (__outputCacheSettings == null)
                    //     __outputCacheSettings = new OutputCacheParameters(.....)
                    //

                    // This is the "if (__outputCacheSettings == null)" part
                    CodeConditionStatement outputCacheSettingsCondition = new CodeConditionStatement();
                    outputCacheSettingsCondition.Condition = new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(
                            _classTypeExpr,
                            outputCacheSettingsFieldName),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePrimitiveExpression(null));

                    // This is the "__outputCacheSettings = new OutputCacheParameters()" part


                    // e.g. declare local variable: OutputCacheParameters outputCacheSettings;
                    CodeVariableDeclarationStatement outputCacheSettingsDeclaration = new CodeVariableDeclarationStatement();
                    outputCacheSettingsDeclaration.Type = new CodeTypeReference(typeof(OutputCacheParameters));
                    outputCacheSettingsDeclaration.Name = outputCacheSettingsLocalName;
                    outputCacheSettingsCondition.TrueStatements.Insert(0, outputCacheSettingsDeclaration);

                    // e.g. outputCacheSettings = new outputCacheParameters;
                    CodeObjectCreateExpression cacheSettingsObject = new CodeObjectCreateExpression();
                    cacheSettingsObject.CreateType = new CodeTypeReference(typeof(OutputCacheParameters));

                    CodeVariableReferenceExpression outputCacheSettings =
                        new CodeVariableReferenceExpression(outputCacheSettingsLocalName);

                    CodeAssignStatement setOutputCacheObject =
                        new CodeAssignStatement(outputCacheSettings, cacheSettingsObject);

                    // Add the statement to the "true" clause
                    outputCacheSettingsCondition.TrueStatements.Add(setOutputCacheObject);

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.CacheProfile))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "CacheProfile"),
                            new CodePrimitiveExpression(cacheSettings.CacheProfile));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.Duration))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "Duration"),
                            new CodePrimitiveExpression(cacheSettings.Duration));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.Enabled))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "Enabled"),
                            new CodePrimitiveExpression(cacheSettings.Enabled));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.Location))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "Location"),
                            new CodeFieldReferenceExpression(
                                new CodeTypeReferenceExpression(typeof(OutputCacheLocation)),
                                cacheSettings.Location.ToString()));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.NoStore))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "NoStore"),
                            new CodePrimitiveExpression(cacheSettings.NoStore));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.SqlDependency))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "SqlDependency"),
                            new CodePrimitiveExpression(cacheSettings.SqlDependency));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByControl))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "VaryByControl"),
                            new CodePrimitiveExpression(cacheSettings.VaryByControl));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByCustom))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "VaryByCustom"),
                            new CodePrimitiveExpression(cacheSettings.VaryByCustom));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByContentEncoding))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "VaryByContentEncoding"),
                            new CodePrimitiveExpression(cacheSettings.VaryByContentEncoding));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }
                    if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByHeader))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "VaryByHeader"),
                            new CodePrimitiveExpression(cacheSettings.VaryByHeader));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByParam))
                    {
                        CodeAssignStatement setPropertyStatement = new CodeAssignStatement(
                            new CodePropertyReferenceExpression(outputCacheSettings, "VaryByParam"),
                            new CodePrimitiveExpression(cacheSettings.VaryByParam));

                        outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement);
                    }

                    // e.g. __outputCacheSettings = outputCacheSettings;
                    CodeFieldReferenceExpression staticOutputCacheSettings =
                        new CodeFieldReferenceExpression(_classTypeExpr, outputCacheSettingsFieldName);
                    CodeAssignStatement assignOutputCacheSettings =
                        new CodeAssignStatement(staticOutputCacheSettings, outputCacheSettings);
                    // Add the statement to the "true" clause
                    outputCacheSettingsCondition.TrueStatements.Add(assignOutputCacheSettings);

                    InitMethod.Statements.Add(outputCacheSettingsCondition);
                }
            }
        }
        /*
         * Build first-time intialization statements
         */
        protected override void BuildInitStatements(CodeStatementCollection trueStatements, CodeStatementCollection topLevelStatements)
        {
            base.BuildInitStatements(trueStatements, topLevelStatements);

            //



            CodeMemberField fileDependencies = new CodeMemberField(typeof(object), fileDependenciesName);

            fileDependencies.Attributes |= MemberAttributes.Static;
            _sourceDataClass.Members.Add(fileDependencies);

            // Note: it may look like this local variable declaration is redundant. However it is necessary
            // to make this init code re-entrant safe. This way, even if two threads enter the contructor
            // at the same time, they will not add multiple dependencies.

            // e.g. string[] dependencies;
            CodeVariableDeclarationStatement dependencies = new CodeVariableDeclarationStatement();

            dependencies.Type = new CodeTypeReference(typeof(string[]));
            dependencies.Name = dependenciesLocalName;
            // Note: it is important to add all local variables at the top level for CodeDom Subset compliance.
            topLevelStatements.Insert(0, dependencies);

            Debug.Assert(Parser.SourceDependencies != null);

            StringSet virtualDependencies = new StringSet();

            virtualDependencies.AddCollection(Parser.SourceDependencies);

            // e.g. dependencies = new string[{{virtualDependencies.Count}}];;
            CodeAssignStatement assignDependencies = new CodeAssignStatement();

            assignDependencies.Left =
                new CodeVariableReferenceExpression(dependenciesLocalName);
            assignDependencies.Right =
                new CodeArrayCreateExpression(typeof(String), virtualDependencies.Count);
            trueStatements.Add(assignDependencies);

            int i = 0;

            foreach (string virtualDependency in virtualDependencies)
            {
                // e.g. dependencies[i] = "~/sub/foo.aspx";
                CodeAssignStatement addFileDep = new CodeAssignStatement();
                addFileDep.Left =
                    new CodeArrayIndexerExpression(
                        new CodeVariableReferenceExpression(dependenciesLocalName),
                        new CodeExpression[] { new CodePrimitiveExpression(i++) });
                string src = UrlPath.MakeVirtualPathAppRelative(virtualDependency);
                addFileDep.Right = new CodePrimitiveExpression(src);
                trueStatements.Add(addFileDep);
            }

            // e.g. __fileDependencies = this.GetWrappedFileDependencies(dependencies);
            CodeAssignStatement initFile = new CodeAssignStatement();

            initFile.Left = new CodeFieldReferenceExpression(_classTypeExpr, fileDependenciesName);
            CodeMethodInvokeExpression createWrap = new CodeMethodInvokeExpression();

            createWrap.Method.TargetObject = new CodeThisReferenceExpression();
            createWrap.Method.MethodName   = "GetWrappedFileDependencies";
            createWrap.Parameters.Add(new CodeVariableReferenceExpression(dependenciesLocalName));
            initFile.Right = createWrap;

#if DBG
            AppendDebugComment(trueStatements);
#endif
            trueStatements.Add(initFile);
        }
Example #12
0
        private static bool DefineResourceFetchingProperty(String propertyName, String resourceName, ResourceData data, CodeTypeDeclaration srClass, bool internalClass, bool useStatic)
        {
            CodeMemberProperty prop = new CodeMemberProperty();

            prop.Name   = propertyName;
            prop.HasGet = true;
            prop.HasSet = false;

            Type type = data.Type;

            if (type == null)
            {
                return(false);
            }

            if (type == typeof(MemoryStream))
            {
                type = typeof(UnmanagedMemoryStream);
            }

            // Ensure type is internalally visible.  This is necessary to ensure
            // users can access classes via a base type.  Imagine a class like
            // Image or Stream as a internalally available base class, then an
            // internal type like MyBitmap or __UnmanagedMemoryStream as an
            // internal implementation for that base class.  For internalally
            // available strongly typed resource classes, we must return the
            // internal type.  For simplicity, we'll do that for internal strongly
            // typed resource classes as well.  Ideally we'd also like to check
            // for interfaces like IList, but I don't know how to do that without
            // special casing collection interfaces & ignoring serialization
            // interfaces or IDisposable.
            while (!type.IsPublic)
            {
                type = type.BaseType;
            }

            CodeTypeReference valueType = new CodeTypeReference(type);

            prop.Type = valueType;
            if (internalClass)
            {
                prop.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                prop.Attributes = MemberAttributes.Public;
            }

            if (useStatic)
            {
                prop.Attributes |= MemberAttributes.Static;
            }

            // For Strings, emit this:
            //    return ResourceManager.GetString("name", _resCulture);
            // For Streams, emit this:
            //    return ResourceManager.GetStream("name", _resCulture);
            // For Objects, emit this:
            //    Object obj = ResourceManager.GetObject("name", _resCulture);
            //    return (MyValueType) obj;
            CodePropertyReferenceExpression resMgr          = new CodePropertyReferenceExpression(null, "ResourceManager");
            CodeFieldReferenceExpression    resCultureField = new CodeFieldReferenceExpression((useStatic) ? null : new CodeThisReferenceExpression(), CultureInfoFieldName);

            bool   isString      = type == typeof(String);
            bool   isStream      = type == typeof(UnmanagedMemoryStream) || type == typeof(MemoryStream);
            String getMethodName = String.Empty;
            String text          = String.Empty;
            String valueAsString = TruncateAndFormatCommentStringForOutput(data.ValueAsString);
            String typeName      = String.Empty;

            if (!isString) // Stream or Object
            {
                typeName = TruncateAndFormatCommentStringForOutput(type.ToString());
            }

            if (isString)
            {
                getMethodName = "GetString";
            }
            else if (isStream)
            {
                getMethodName = "GetStream";
            }
            else
            {
                getMethodName = "GetObject";
            }

            if (isString)
            {
                text = SR.GetString(SR.StringPropertyComment, valueAsString);
            }
            else
            {                                               // Stream or Object
                if (valueAsString == null ||
                    String.Equals(typeName, valueAsString)) // If the type did not override ToString, ToString just returns the type name.
                {
                    text = SR.GetString(SR.NonStringPropertyComment, typeName);
                }
                else
                {
                    text = SR.GetString(SR.NonStringPropertyDetailedComment, typeName, valueAsString);
                }
            }

            prop.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            prop.Comments.Add(new CodeCommentStatement(text, true));
            prop.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));

            CodeExpression            getValue = new CodeMethodInvokeExpression(resMgr, getMethodName, new CodePrimitiveExpression(resourceName), resCultureField);
            CodeMethodReturnStatement ret;

            if (isString || isStream)
            {
                ret = new CodeMethodReturnStatement(getValue);
            }
            else
            {
                CodeVariableDeclarationStatement returnObj = new CodeVariableDeclarationStatement(typeof(Object), "obj", getValue);
                prop.GetStatements.Add(returnObj);

                ret = new CodeMethodReturnStatement(new CodeCastExpression(valueType, new CodeVariableReferenceExpression("obj")));
            }
            prop.GetStatements.Add(ret);

            srClass.Members.Add(prop);
            return(true);
        }
Example #13
0
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch)
        {
            const String tmpVarName = "temp";
            String       resMgrCtorParam;

            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                {
                    resMgrCtorParam = resourcesNamespace + '.' + baseName;
                }
                else
                {
                    resMgrCtorParam = baseName;
                }
            }
            else if ((nameSpace != null) && (nameSpace.Length > 0))
            {
                resMgrCtorParam = nameSpace + '.' + baseName;
            }
            else
            {
                resMgrCtorParam = baseName;
            }

            CodeAttributeDeclaration suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Diagnostics.CodeAnalysis.SuppressMessageAttribute)));

            suppressMessageAttrib.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));

            // Emit a constructor - make it protected even if it is a "static" class to allow subclassing
            CodeConstructor ctor = new CodeConstructor();

            ctor.CustomAttributes.Add(suppressMessageAttrib);
            if (useStatic || internalClass)
            {
                ctor.Attributes = MemberAttributes.FamilyAndAssembly;
            }
            else
            {
                ctor.Attributes = MemberAttributes.Public;
            }
            srClass.Members.Add(ctor);

            // Emit _resMgr field.
            CodeTypeReference ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField   field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName);

            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit _resCulture field, and leave it set to null.
            CodeTypeReference CultureTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);

            field            = new CodeMemberField(CultureTypeReference, CultureInfoFieldName);
            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit ResMgr property
            CodeMemberProperty resMgr = new CodeMemberProperty();

            srClass.Members.Add(resMgr);
            resMgr.Name   = ResMgrPropertyName;
            resMgr.HasGet = true;
            resMgr.HasSet = false;
            resMgr.Type   = ResMgrCodeTypeReference;
            if (internalClass)
            {
                resMgr.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                resMgr.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                resMgr.Attributes |= MemberAttributes.Static;
            }

            // Mark the ResMgr property as advanced
            CodeTypeReference editorBrowsableStateTypeRef = new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState));

            editorBrowsableStateTypeRef.Options = CodeTypeReferenceOptions.GlobalReference;

            CodeAttributeArgument    editorBrowsableStateAdvanced     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced"));
            CodeAttributeDeclaration editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute",
                                                                                                     new CodeAttributeArgument[] { editorBrowsableStateAdvanced });

            editorBrowsableAdvancedAttribute.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            resMgr.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            // Emit the Culture property (read/write)
            CodeMemberProperty culture = new CodeMemberProperty();

            srClass.Members.Add(culture);
            culture.Name   = CultureInfoPropertyName;
            culture.HasGet = true;
            culture.HasSet = true;
            culture.Type   = CultureTypeReference;
            if (internalClass)
            {
                culture.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                culture.Attributes = MemberAttributes.Public;
            }

            if (useStatic)
            {
                culture.Attributes |= MemberAttributes.Static;
            }

            // Mark the Culture property as advanced
            culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute);


            /*
             * // Here's what I'm trying to emit.  Since not all languages support
             * // try/finally, we'll avoid our double lock pattern here.
             * // This will only hurt perf when we get two threads racing through
             * // this method the first time.  Unfortunate, but not a big deal.
             * // Also, the .NET Compact Framework doesn't support
             * // Thread.MemoryBarrier (they only run on processors w/ a strong
             * // memory model, and who knows about IA64...)
             * // Once we have Interlocked.CompareExchange<T>, we should use it here.
             * if (_resMgr == null) {
             *    ResourceManager tmp = new ResourceManager("<resources-name-with-namespace>", typeof("<class-name>").Assembly);
             *    _resMgr = tmp;
             * }
             * return _resMgr;
             */
            CodeFieldReferenceExpression  field_resMgr        = new CodeFieldReferenceExpression(null, ResMgrFieldName);
            CodeMethodReferenceExpression object_equalsMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Object)), "ReferenceEquals");

            CodeMethodInvokeExpression isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, new CodeExpression[] { field_resMgr, new CodePrimitiveExpression(null) });

            // typeof(<class-name>).Assembly
            CodePropertyReferenceExpression getAssembly = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");

            // new ResourceManager(resMgrCtorParam, typeof(<class-name>).Assembly);
            CodeObjectCreateExpression newResMgr = new CodeObjectCreateExpression(ResMgrCodeTypeReference, new CodePrimitiveExpression(resMgrCtorParam), getAssembly);

            CodeStatement[] init = new CodeStatement[2];
            init[0] = new CodeVariableDeclarationStatement(ResMgrCodeTypeReference, tmpVarName, newResMgr);
            init[1] = new CodeAssignStatement(field_resMgr, new CodeVariableReferenceExpression(tmpVarName));

            resMgr.GetStatements.Add(new CodeConditionStatement(isResMgrNull, init));
            resMgr.GetStatements.Add(new CodeMethodReturnStatement(field_resMgr));

            // Add a doc comment to the ResourceManager property
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            resMgr.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ResMgrPropertyComment), true));
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));


            // Emit code for Culture property
            CodeFieldReferenceExpression field_resCulture = new CodeFieldReferenceExpression(null, CultureInfoFieldName);

            culture.GetStatements.Add(new CodeMethodReturnStatement(field_resCulture));

            CodePropertySetValueReferenceExpression newCulture = new CodePropertySetValueReferenceExpression();

            culture.SetStatements.Add(new CodeAssignStatement(field_resCulture, newCulture));

            // Add a doc comment to Culture property
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true));
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
        }
Example #14
0
 public int VisitVariableDeclaration(CodeVariableDeclarationStatement decl)
 {
     return(0);
 }
 private void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
 {
     OutputTypeNamePair(e.Type, e.Name);
     if (e.InitExpression != null)
     {
         Output.Write(" = ");
         GenerateExpression(e.InitExpression);
     }
     if (!generatingForLoop)
     {
         Output.WriteLine(";");
     }
 }
Example #16
0
 protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
 {
 }
    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.Drawing"));
        cu.Namespaces.Add (ns);

        cu.ReferencedAssemblies.Add ("System.Drawing.dll");

        // create a class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Test";
        class1.IsClass = true;
        ns.Types.Add (class1);
        if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {

            // create first struct to test nested structs
            //     GENERATE (C#):
            //	public struct structA {
            //		public structB innerStruct;
            //		public struct structB {
            //    		public int int1;
            //		}
            //	}
            CodeTypeDeclaration structA = new CodeTypeDeclaration ("structA");
            structA.IsStruct = true;

            CodeTypeDeclaration structB = new CodeTypeDeclaration ("structB");
            structB.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);
            class1.Members.Add (structA);

            // create second struct to test tructs of non-primitive types
            //     GENERATE (C#):
            //         public struct structC {
            //              public Point pt1;
            //              public Point pt2;
            //         }
            CodeTypeDeclaration structC = new CodeTypeDeclaration ("structC");
            structC.IsStruct = true;

            CodeMemberField firstPt = new CodeMemberField ("Point", "pt1");
            firstPt.Attributes = MemberAttributes.Public;
            structC.Members.Add (firstPt);

            CodeMemberField secondPt = new CodeMemberField ("Point", "pt2");
            secondPt.Attributes = MemberAttributes.Public;
            structC.Members.Add (secondPt);
            class1.Members.Add (structC);

            // create method to test nested struct
            //     GENERATE (C#):
            //          public static int NestedStructMethod() {
            //               structA varStructA;
            //               varStructA.innerStruct.int1 = 3;
            //               return varStructA.innerStruct.int1;
            //          }
            AddScenario ("CheckNestedStructMethod");
            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")));
            class1.Members.Add (nestedStructMethod);


            // create method to test nested non primitive struct member
            //     GENERATE (C#):
            //          public static System.Drawing.Point NonPrimitiveStructMethod() {
            //               structC varStructC;
            //               varStructC.pt1 = new Point(1, -1);
            //               return varStructC.pt1;
            //          }
            AddScenario ("CheckNonPrimitiveStructMethod");
            CodeMemberMethod nonPrimitiveStructMethod = new CodeMemberMethod ();
            nonPrimitiveStructMethod.Name = "NonPrimitiveStructMethod";
            nonPrimitiveStructMethod.ReturnType = new CodeTypeReference (typeof (Point));
            nonPrimitiveStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeVariableDeclarationStatement varStructC = new CodeVariableDeclarationStatement ("structC", "varStructC");
            nonPrimitiveStructMethod.Statements.Add (varStructC);
            nonPrimitiveStructMethod.Statements.Add (
                new CodeAssignStatement (
                /* Expression1 */ new CodeFieldReferenceExpression (
                new CodeVariableReferenceExpression ("varStructC"),
                "pt1"),
                /* Expression2 */ new CodeObjectCreateExpression ("Point", new CodeExpression[] {new CodePrimitiveExpression (1), new CodePrimitiveExpression (-1)})
                ));
            nonPrimitiveStructMethod.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructC"), "pt1")));
            class1.Members.Add (nonPrimitiveStructMethod);
        }
    }
Example #18
0
        public override string GenerateCode()
        {
            codeNamespace.Comments.Add(
                new CodeCommentStatement("--------------------------------------------------------------------------------------------------"));
            codeNamespace.Comments.Add(new CodeCommentStatement("<auto-generatedInfo>"));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tThis code was generated by ResW File Code Generator MOD (http://bit.ly/reswcodegen)"));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tResW File Code Generator was written by Christian Resma Helle (modified by Tobias Klika)"));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tand is under GNU General Public License version 2 (GPLv2)"));
            codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tThis code contains a helper class exposing property representations"));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tof the string resources defined in the specified .ResW file"));
            codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty));
            codeNamespace.Comments.Add(new CodeCommentStatement("\tGenerated: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)));
            codeNamespace.Comments.Add(new CodeCommentStatement("</auto-generatedInfo>"));
            codeNamespace.Comments.Add(
                new CodeCommentStatement("--------------------------------------------------------------------------------------------------"));

            codeNamespace.Imports.Add(new CodeNamespaceImport("Windows.ApplicationModel.Resources"));

            var targetClass = new CodeTypeDeclaration(className)
            {
                IsClass        = true,
                IsPartial      = true,
                TypeAttributes = (classAccessibility ?? TypeAttributes.Public),
                Attributes     = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final
            };

            const string resourceLoaderType  = "ResourceLoader";
            var          resourceLoaderField = new CodeMemberField(resourceLoaderType, "resourceLoader")
            {
                Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final
            };

            targetClass.Members.Add(resourceLoaderField);

            var constructor = new CodeTypeConstructor();

            var executingAssemblyVar  = new CodeVariableDeclarationStatement(typeof(string), "executingAssemblyName");
            var executingAssemblyInit = new CodeAssignStatement(new CodeVariableReferenceExpression("executingAssemblyName"),
                                                                new CodeSnippetExpression("Windows.UI.Xaml.Application.Current.GetType().AssemblyQualifiedName"));
            var executingAssemblySplit = new CodeVariableDeclarationStatement(typeof(string[]), "executingAssemblySplit");
            var executingAssemblyInit2 = new CodeAssignStatement(new CodeVariableReferenceExpression("executingAssemblySplit"),
                                                                 new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("executingAssemblyName"),
                                                                                                "Split",
                                                                                                new CodePrimitiveExpression(',')));
            var executingAssemblyInit3 = new CodeAssignStatement(new CodeVariableReferenceExpression("executingAssemblyName"),
                                                                 new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("executingAssemblySplit"),
                                                                                                new CodePrimitiveExpression(1)));

            var currentAssemblyVar  = new CodeVariableDeclarationStatement(typeof(string), "currentAssemblyName");
            var currentAssemblyInit = new CodeAssignStatement(new CodeVariableReferenceExpression("currentAssemblyName"),
                                                              new CodePropertyReferenceExpression(new CodeTypeOfExpression(className), "AssemblyQualifiedName"));
            var currentAssemblySplit = new CodeVariableDeclarationStatement(typeof(string[]), "currentAssemblySplit");
            var currentAssemblyInit2 = new CodeAssignStatement(new CodeVariableReferenceExpression("currentAssemblySplit"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("currentAssemblyName"),
                                                                                              "Split",
                                                                                              new CodePrimitiveExpression(',')));
            var currentAssemblyInit3 = new CodeAssignStatement(new CodeVariableReferenceExpression("currentAssemblyName"),
                                                               new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("currentAssemblySplit"),
                                                                                              new CodePrimitiveExpression(1)));

            var createResourceLoader = new CodeConditionStatement(
                new CodeSnippetExpression("executingAssemblyName.Equals(currentAssemblyName)"),
                new CodeStatement[] // true
            {
                visualStudioVersion == VisualStudioVersion.VS2013
                        ? new CodeAssignStatement(new CodeFieldReferenceExpression(null, "resourceLoader"),
                                                  new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("ResourceLoader"),
                                                                                 "GetForCurrentView",
                                                                                 new CodeSnippetExpression("\"" + className + "\"")))
                        : new CodeAssignStatement(new CodeFieldReferenceExpression(null, "resourceLoader"),
                                                  new CodeObjectCreateExpression(new CodeTypeReference("ResourceLoader"),
                                                                                 new CodeSnippetExpression("\"" + className + "\"")))
            },
                new CodeStatement[] // false
            {
                visualStudioVersion == VisualStudioVersion.VS2013
                        ? new CodeAssignStatement(new CodeFieldReferenceExpression(null, "resourceLoader"),
                                                  new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("ResourceLoader"),
                                                                                 "GetForCurrentView",
                                                                                 new CodeSnippetExpression("currentAssemblyName + \"/" + className + "\"")))
                        : new CodeAssignStatement(new CodeFieldReferenceExpression(null, "resourceLoader"),
                                                  new CodeObjectCreateExpression(new CodeTypeReference("ResourceLoader"),
                                                                                 new CodeSnippetExpression("currentAssemblyName + \"/" + className + "\"")))
            });

            constructor.Statements.Add(executingAssemblyVar);
            constructor.Statements.Add(executingAssemblyInit);
            constructor.Statements.Add(executingAssemblySplit);
            constructor.Statements.Add(executingAssemblyInit2);
            constructor.Statements.Add(executingAssemblyInit3);
            constructor.Statements.Add(currentAssemblyVar);
            constructor.Statements.Add(currentAssemblyInit);
            constructor.Statements.Add(currentAssemblySplit);
            constructor.Statements.Add(currentAssemblyInit2);
            constructor.Statements.Add(currentAssemblyInit3);
            constructor.Statements.Add(createResourceLoader);

            targetClass.Members.Add(constructor);

            var resources = ResourceParser.Parse();
            var idx       = 0;

            StringBuilder resourceKeysStringBuilder = new StringBuilder();

            resourceKeysStringBuilder.Append("new string[] { ");

            foreach (var item in resources)
            {
                if (string.IsNullOrEmpty(item.Name))
                {
                    continue;
                }

                string name = item.Name.Trim();
                string key  = item.Name;

                if (name.Contains("."))
                {
                    name = name.Replace(".", "_");
                    key  = key.Replace(".", "/");
                }

                var property = new CodeMemberField
                {
                    Name       = name,
                    Attributes = MemberAttributes.Public,
                    Type       = new CodeTypeReference(typeof(string))
                };

                property.Name += " { get; private set; } //";

                resourceKeysStringBuilder.Append($"\"{name}\"");
                if (idx < resources.Count - 1)
                {
                    resourceKeysStringBuilder.Append(", ");
                }

                targetClass.Members.Add(property);

                idx += 1;
            }

            resourceKeysStringBuilder.Append(" }");

            var keysField = new CodeMemberField()
            {
                Name           = "ResourceKeys",
                Type           = new CodeTypeReference(typeof(string[])),
                Attributes     = MemberAttributes.Private | MemberAttributes.Final,
                InitExpression = new CodeSnippetExpression(resourceKeysStringBuilder.ToString())
            };

            targetClass.Members.Add(keysField);

            codeNamespace.Types.Add(targetClass);
            compileUnit.Namespaces.Add(codeNamespace);

            return(GenerateCodeFromCompileUnit());
        }
Example #19
0
			public void Visit(CodeVariableDeclarationStatement o)
			{
				g.GenerateVariableDeclarationStatement(o);
			}
Example #20
0
        void OutputCacheParamsBlock(CodeMemberMethod method)
        {
            var statements        = new List <CodeStatement> ();
            var localSettingsDecl = new CodeVariableDeclarationStatement(typeof(OutputCacheParameters), "outputCacheSettings");
            var localSettings     = new CodeVariableReferenceExpression("outputCacheSettings");

            statements.Add(localSettingsDecl);
            statements.Add(
                new CodeAssignStatement(
                    localSettings,
                    new CodeObjectCreateExpression(typeof(OutputCacheParameters), new CodeExpression[] {})
                    )
                );

            TemplateParser.OutputCacheParsedParams parsed = pageParser.OutputCacheParsedParameters;
            if ((parsed & TemplateParser.OutputCacheParsedParams.CacheProfile) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "CacheProfile", pageParser.OutputCacheCacheProfile));
            }
            statements.Add(AssignOutputCacheParameter(localSettings, "Duration", pageParser.OutputCacheDuration));
            if ((parsed & TemplateParser.OutputCacheParsedParams.Location) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "Location", pageParser.OutputCacheLocation));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.NoStore) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "NoStore", pageParser.OutputCacheNoStore));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.SqlDependency) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "SqlDependency", pageParser.OutputCacheSqlDependency));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByContentEncodings) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "VaryByContentEncoding", pageParser.OutputCacheVaryByContentEncodings));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByControl) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "VaryByControl", pageParser.OutputCacheVaryByControls));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByCustom) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "VaryByCustom", pageParser.OutputCacheVaryByCustom));
            }
            if ((parsed & TemplateParser.OutputCacheParsedParams.VaryByHeader) != 0)
            {
                statements.Add(AssignOutputCacheParameter(localSettings, "VaryByHeader", pageParser.OutputCacheVaryByHeader));
            }
            statements.Add(AssignOutputCacheParameter(localSettings, "VaryByParam", pageParser.OutputCacheVaryByParam));

            CodeFieldReferenceExpression outputCacheSettings = GetMainClassFieldReferenceExpression("__outputCacheSettings");

            statements.Add(new CodeAssignStatement(outputCacheSettings, localSettings));

            var cond = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    outputCacheSettings,
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(null)
                    ),
                statements.ToArray()
                );

            method.Statements.Add(cond);
        }
Example #21
0
    public CodeMemberMethod GenerateMethod(Smoke* smoke, Smoke.Method* method, string mungedName, CodeTypeReference iface)
    {
        string cppSignature = smoke->GetMethodSignature(method);
        CodeMemberMethod cmm = GenerateBasicMethodDefinition(smoke, method, cppSignature, iface);
        if (cmm == null)
        {
            return null;
        }

        // put the method into the correct type
        CodeTypeDeclaration containingType = type;
        if (cmm.Name.StartsWith("operator") || cmm.Name.StartsWith("explicit "))
        {
            if (!data.CSharpTypeMap.TryGetValue(cmm.Parameters[0].Type.GetStringRepresentation(), out containingType))
            {
                if (cmm.Parameters.Count < 2 ||
                    !data.CSharpTypeMap.TryGetValue(cmm.Parameters[1].Type.GetStringRepresentation(), out containingType))
                {
                    Debug.Print("  |--Can't find containing type for {0} - skipping", cppSignature);
                }
                return null;
            }
        }

        // already implemented?
        if (containingType.HasMethod(cmm))
        {
            if (iface == null || (method->flags & (uint) Smoke.MethodFlags.mf_protected) > 0)
            {
                // protected methods are not available in interfaces
                Debug.Print("  |--Skipping already implemented method {0}", cppSignature);
                return null;
            }
            else
            {
                cmm.PrivateImplementationType = iface;
            }
        }

        if (PreMethodBodyHooks != null)
        {
            PreMethodBodyHooks(smoke, method, cmm, containingType);
        }

        // do we have pass-by-ref parameters?
        bool generateInvokeForRefParams = cmm.Parameters.Cast<CodeParameterDeclarationExpression>().Any(expr => expr.Direction == FieldDirection.Ref);

        // generate the SmokeMethod attribute
        CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeMethod",
                                                                     new CodeAttributeArgument(
                                                                     	new CodePrimitiveExpression(cppSignature)));
        cmm.CustomAttributes.Add(attr);

        // choose the correct 'interceptor'
        CodeMethodInvokeExpression invoke;
        if ((cmm.Attributes & MemberAttributes.Static) == MemberAttributes.Static)
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.staticInterceptor_Invoke);
        }
        else
        {
            invoke = new CodeMethodInvokeExpression(SmokeSupport.interceptor_Invoke);
        }

        // first pass the munged name, then the C++ signature
        invoke.Parameters.Add(new CodePrimitiveExpression(mungedName));
        invoke.Parameters.Add(new CodePrimitiveExpression(cppSignature));

        // retrieve the return type
        CodeTypeReference returnType;
        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) > 0)
        {
            // destructor
            returnType = new CodeTypeReference(typeof(void));
        }
        else if (cmm.Name.StartsWith("explicit operator "))
        {
            // strip 'explicit operator' from the name to get the return type
            returnType = new CodeTypeReference(cmm.Name.Substring(18));
        }
        else
        {
            returnType = cmm.ReturnType;
        }

        // add the return type
        invoke.Parameters.Add(new CodeTypeOfExpression(returnType));
        invoke.Parameters.Add(new CodePrimitiveExpression(generateInvokeForRefParams));
        invoke.Parameters.Add(new CodeVariableReferenceExpression("smokeArgs"));

        ProcessEqualityOperators(cmm);

        CodeArrayCreateExpression argsInitializer = new CodeArrayCreateExpression(typeof(object[]));

        // add the parameters
        foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
        {
            argsInitializer.Initializers.Add(new CodeTypeOfExpression(param.Type));
            string argReference = param.Name;
            int indexOfSpace = argReference.IndexOf(' ');
            if (indexOfSpace > 0)
            {
                argReference = argReference.Substring(0, indexOfSpace);
            }
            argsInitializer.Initializers.Add(new CodeArgumentReferenceExpression(argReference));
        }

        CodeStatement argsStatement = new CodeVariableDeclarationStatement(typeof(object[]), "smokeArgs", argsInitializer);
        cmm.Statements.Add(argsStatement);

        // we have to call "CreateProxy()" in constructors
        if (cmm is CodeConstructor)
        {
            cmm.Statements.Add(
                new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "CreateProxy")));
        }

        // add the method call statement
        CodeStatement statement;

        if (!generateInvokeForRefParams)
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeMethodReturnStatement(new CodeCastExpression(returnType, invoke));
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
            }
            cmm.Statements.Add(statement);
        }
        else
        {
            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                statement = new CodeVariableDeclarationStatement(returnType, "smokeRetval",
                                                                 new CodeCastExpression(returnType, invoke));
                cmm.Statements.Add(statement);
            }
            else
            {
                statement = new CodeExpressionStatement(invoke);
                cmm.Statements.Add(statement);
            }

            int i = 0;
            foreach (CodeParameterDeclarationExpression param in cmm.Parameters)
            {
                ++i;
                if (param.Direction != FieldDirection.Ref)
                {
                    continue;
                }
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(param.Name),
                                                           new CodeCastExpression(param.Type.BaseType,
                                                                                  new CodeArrayIndexerExpression(
                                                                                  	new CodeVariableReferenceExpression("smokeArgs"),
                                                                                  	new CodePrimitiveExpression(i*2 - 1)
                                                                                  	)
                                                           	)
                                   	));
            }

            if (method->ret > 0 && (method->flags & (uint) Smoke.MethodFlags.mf_ctor) == 0)
            {
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("smokeRetval")));
            }
        }
        containingType.Members.Add(cmm);

        if ((method->flags & (uint) Smoke.MethodFlags.mf_dtor) != 0)
        {
            containingType.BaseTypes.Add(new CodeTypeReference(typeof(IDisposable)));
            CodeMemberMethod dispose = new CodeMemberMethod();
            dispose.Name = "Dispose";
            dispose.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final;
            dispose.Statements.AddRange(cmm.Statements);
            dispose.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                               	new CodeTypeReferenceExpression("GC"), "SuppressFinalize",
                                                               	new CodeThisReferenceExpression()
                                                               	)));
            containingType.Members.Add(dispose);
        }
        return cmm;
    }
Example #22
0
        internal static void EmitCodeToAddIntoCustomStdBinding(Type standardBindingType, string generatedElementClassName, string generatedCollectionElementClassName, string srcFile)
        {
            CodeMemberMethod applyCfgMethodForStdBinding = new CodeMemberMethod();

            applyCfgMethodForStdBinding.Name = MethodNameConstants.ApplyConfigurationMethod;

            string paramConfigName = "configurationName";
            CodeVariableReferenceExpression paramVarRef = new CodeVariableReferenceExpression(paramConfigName);

            applyCfgMethodForStdBinding.Parameters.Add(new CodeParameterDeclarationExpression(
                                                           CodeDomHelperObjects.stringTypeRef,
                                                           paramConfigName));

            string bindingsString = "bindings";
            CodeVariableReferenceExpression bindingsVarRef = new CodeVariableReferenceExpression(bindingsString);

            string sectionString = "section";
            CodeVariableReferenceExpression sectionVarRef = new CodeVariableReferenceExpression(sectionString);

            string elementString = "element";
            CodeVariableReferenceExpression elementVarRef = new CodeVariableReferenceExpression(elementString);

            string topLevelSectionNameInConfig = "system.serviceModel/bindings/";
            string subSectionNameInConfig      = Helpers.TurnFirstCharLower(standardBindingType.Name);

            CodeVariableDeclarationStatement bindingsInit = new CodeVariableDeclarationStatement(
                new CodeTypeReference(TypeNameConstants.BindingsSection),
                bindingsString,
                new CodeCastExpression(TypeNameConstants.BindingsSection,
                                       new CodeMethodInvokeExpression(
                                           new CodeTypeReferenceExpression(TypeNameConstants.ConfigurationManager),
                                           MethodNameConstants.GetSectionMethod,
                                           new CodePrimitiveExpression(topLevelSectionNameInConfig))));

            applyCfgMethodForStdBinding.Statements.Add(bindingsInit);

            CodeVariableDeclarationStatement sectionInit = new CodeVariableDeclarationStatement(
                new CodeTypeReference(generatedCollectionElementClassName),
                sectionString,
                new CodeCastExpression(generatedCollectionElementClassName,
                                       new CodeArrayIndexerExpression(
                                           bindingsVarRef,
                                           new CodePrimitiveExpression(subSectionNameInConfig))));

            applyCfgMethodForStdBinding.Statements.Add(sectionInit);

            CodeVariableDeclarationStatement elementInit = new CodeVariableDeclarationStatement(
                new CodeTypeReference(generatedElementClassName),
                elementString,
                new CodeArrayIndexerExpression(
                    new CodeFieldReferenceExpression(
                        sectionVarRef,
                        PropertyNameConstants.BindingsProperty),
                    paramVarRef));

            applyCfgMethodForStdBinding.Statements.Add(elementInit);

            CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression(
                elementVarRef,
                CodeBinaryOperatorType.IdentityEquality,
                CodeDomHelperObjects.NullRef);

            CodeThrowExceptionStatement ctes = new CodeThrowExceptionStatement(
                new CodeObjectCreateExpression(
                    new CodeTypeReference(typeof(ConfigurationErrorsException)),
                    new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(CodeDomHelperObjects.stringTypeRef),
                        MethodNameConstants.FormatMethod,
                        CodeDomHelperObjects.cultureInfoCurrent,
                        new CodePrimitiveExpression("There is no binding named {0} at {1}."),
                        paramVarRef,
                        new CodePropertyReferenceExpression(
                            sectionVarRef, PropertyNameConstants.BindingNameProperty))));
            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(
                elementVarRef,
                MethodNameConstants.ApplyConfigurationMethod,
                CodeDomHelperObjects.ThisRef);

            CodeStatement[]        trueStatements  = { ctes };
            CodeStatement[]        falseStatements = { new CodeExpressionStatement(cmie) };
            CodeConditionStatement ccs             = new CodeConditionStatement(cboe, trueStatements, falseStatements);

            applyCfgMethodForStdBinding.Statements.Add(ccs);

            string          indent   = "    ";
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            using (System.IO.StreamWriter sbSW = new System.IO.StreamWriter(srcFile, false))
            {
                using (IndentedTextWriter sbTW = new IndentedTextWriter(sbSW, indent))
                {
                    provider.GenerateCodeFromMember(
                        applyCfgMethodForStdBinding,
                        sbTW,
                        new CodeGeneratorOptions());
                }
            }
        }
Example #23
0
 protected abstract void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e);
            public override void Transform(IClass scope, IReference reference, CodeMemberProperty property, Transformations.Core.ITransformationContext context)
            {
                var baseTypes = Layering <IClass> .CreateLayers(scope, c => c.BaseTypes).Select(c => c.Single()).ToList();

                if (!baseTypes.Contains((IClass)reference.DeclaringType))
                {
                    throw new InvalidOperationException(string.Format("The reference {0} cannot be refined in the scope of class {1} because {1} does not inherit from its declaring class.", reference.Name, scope.Name));
                }

                var classDeclaration  = context.Trace.ResolveIn(Rule <Type2Type>(), scope);
                var originalReference = context.Trace.ResolveIn(Rule <Reference2Property>(), reference);

                property.Attributes = MemberAttributes.Private;
                property.Name       = originalReference.Name;
                property.PrivateImplementationType = CreateReference(reference.DeclaringType, false, context);
                property.Type = originalReference.Type;

                lock (classDeclaration)
                {
                    classDeclaration.Shadows(true).Add(originalReference);
                    classDeclaration.DependentMembers(true).Add(property);
                }

                var implementations = baseTypes.SelectMany(s => s.References).Where(r => r.Refines == reference).ToList();
                var constraints     = baseTypes.SelectMany(s => s.ReferenceConstraints).Where(rc => rc.Constrains == reference);

                foreach (var declClass in implementations.Select(a => a.DeclaringType).OfType <IClass>().Concat(constraints.Select(c => c.DeclaringType)).Distinct())
                {
                    if (declClass != scope)
                    {
                        var refinedReference = context.Trace.ResolveIn(this, declClass, reference);
                        if (refinedReference != null)
                        {
                            property.Shadows(true).Add(refinedReference);
                        }
                    }
                }

                if (implementations.Count == 0 && !constraints.Any())
                {
                    throw new InvalidOperationException(
                              string.Format("The reference {0} can not be refined in the scope of class {1} because no reference refines it. ", reference, scope)
                              );
                }

                var referenceType = CreateReference(reference.Type, true, context);

                if (reference.UpperBound == 1)
                {
                    var nullRef = new CodePrimitiveExpression(null);
                    if (!constraints.Any())
                    {
                        var castedThisVariable    = new CodeVariableDeclarationStatement(classDeclaration.GetReferenceForType(), "_this", new CodeThisReferenceExpression());
                        var castedThisVariableRef = new CodeVariableReferenceExpression("_this");
                        property.GetStatements.Add(castedThisVariable);
                        property.SetStatements.Add(castedThisVariable);
                        var setRef = new CodePropertySetValueReferenceExpression();
                        var ifNull = new CodeConditionStatement();
                        ifNull.Condition = new CodeBinaryOperatorExpression(setRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                        var foundMatch = false;

                        foreach (var implementation in implementations)
                        {
                            var implementationRef = new CodePropertyReferenceExpression(castedThisVariableRef, context.Trace.ResolveIn(Rule <Reference2Property>(), implementation).Name);

                            if (implementation.Type == reference.Type)
                            {
                                property.GetStatements.Add(new CodeMethodReturnStatement(implementationRef));
                                property.SetStatements.Add(new CodeAssignStatement(implementationRef, setRef));
                                foundMatch = true;
                                break;
                            }
                            else
                            {
                                var getIfStmt = new CodeConditionStatement();
                                getIfStmt.Condition = new CodeBinaryOperatorExpression(implementationRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                                getIfStmt.TrueStatements.Add(new CodeMethodReturnStatement(implementationRef));
                                property.GetStatements.Add(getIfStmt);

                                var implementationType = CreateReference(implementation.Type, true, context);
                                var asRef       = new CodeMethodReferenceExpression(setRef, "As", implementationType);
                                var localVar    = new CodeVariableDeclarationStatement(implementationType, "__" + implementation.Name, new CodeMethodInvokeExpression(asRef));
                                var localVarRef = new CodeVariableReferenceExpression(localVar.Name);
                                var setIfStmt   = new CodeConditionStatement();
                                setIfStmt.Condition = new CodeBinaryOperatorExpression(localVarRef, CodeBinaryOperatorType.IdentityInequality, nullRef);
                                setIfStmt.TrueStatements.Add(new CodeAssignStatement(implementationRef, localVarRef));
                                setIfStmt.TrueStatements.Add(new CodeMethodReturnStatement());
                                ifNull.TrueStatements.Add(localVar);
                                ifNull.TrueStatements.Add(setIfStmt);
                                ifNull.FalseStatements.Add(new CodeAssignStatement(implementationRef, nullRef));
                            }
                        }
                        ifNull.FalseStatements.Add(new CodeMethodReturnStatement());

                        if (ifNull.TrueStatements.Count > 0)
                        {
                            property.SetStatements.Add(ifNull);
                        }

                        if (!foundMatch)
                        {
                            property.GetStatements.Add(new CodeMethodReturnStatement(nullRef));
                            property.SetStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.ArgumentException), new CodePrimitiveExpression("There was no suitable refining reference found for this object"))));
                        }
                    }
                    else
                    {
                        var constraint   = constraints.Last();
                        var ifNotDefault = new CodeConditionStatement();
                        ifNotDefault.TrueStatements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.NotSupportedException))));
                        CodeExpression value;
                        if (constraint.References.Count == 0)
                        {
                            value = nullRef;
                        }
                        else
                        {
                            var refEl = constraint.References[0];
                            var uri   = refEl.AbsoluteUri;
                            if (uri == null)
                            {
                                throw new System.InvalidOperationException();
                            }
                            var metaRepositoryInstance = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(MetaRepository)), "Instance");
                            var refElExpression        = new CodeMethodInvokeExpression(metaRepositoryInstance, "Resolve", new CodePrimitiveExpression(uri.AbsoluteUri));
                            refElExpression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refElExpression, "As", property.Type));
                            var staticField = new CodeMemberField(property.Type, "_" + reference.Name.ToPascalCase());
                            staticField.Attributes     = MemberAttributes.Private | MemberAttributes.Static;
                            staticField.InitExpression = refElExpression;
                            property.DependentMembers(true).Add(staticField);
                            value = new CodeFieldReferenceExpression(null, staticField.Name);
                        }
                        property.GetStatements.Add(new CodeMethodReturnStatement(value));
                        ifNotDefault.Condition = new CodeBinaryOperatorExpression(new CodePropertySetValueReferenceExpression(), CodeBinaryOperatorType.IdentityInequality, value);
                        property.SetStatements.Add(ifNotDefault);
                    }

                    CreateChangeEvent(property, implementations, context, "Changed");
                    CreateChangeEvent(property, implementations, context, "Changing");
                }
                else
                {
                    if (reference.IsUnique)
                    {
                        throw new System.InvalidOperationException("Unique references must not be refined!");
                    }

                    if (implementations.Count > 0 || constraints.Any(c => c.References.Any()))
                    {
                        var collectionType = context.Trace.ResolveIn(Rule <RefinedReferenceCollectionClassGenerator>(), scope, reference);
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(collectionType.GetReferenceForType(), new CodeThisReferenceExpression())));
                        property.DependentTypes(true).Add(collectionType);
                    }
                    else
                    {
                        property.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(EmptyList <>).Name, referenceType)), "Instance")));
                    }
                }
            }
Example #25
0
        private CodeStatement[] ParseFlow(List <CodeLine> lines, int index)
        {
            #region Variables

            var      line  = lines[index];
            string   code  = line.Code.TrimStart(Spaces);
            string[] parts = { string.Empty, string.Empty };

            var delimiters = new char[Spaces.Length + 1];
            delimiters[0] = Multicast;
            Spaces.CopyTo(delimiters, 1);
            int[] d = { code.IndexOfAny(delimiters), code.IndexOfAny(new[] { BlockOpen, ParenOpen }) };

            if (d[0] == -1 && d[1] == -1)
            {
                parts[0] = code;
            }
            else if (d[1] != -1 && (d[1] < d[0] || d[0] == -1))
            {
                parts[0] = code.Substring(0, d[1]);
                parts[1] = code.Substring(d[1], code.Length - d[1]).TrimStart(Spaces);
            }
            else
            {
                parts[0] = code.Substring(0, d[0]);
                parts[1] = code.Substring(d[0] + 1, code.Length - d[0] - 1).TrimStart(Spaces);
            }

            if (parts.Length > 1 && IsEmptyStatement(parts[1]))
            {
                parts = new[] { parts[0] }
            }
            ;

            #endregion Variables

            switch (parts[0].ToLowerInvariant())
            {
                #region If/Else

            case FlowIf:
            {
                if (parts.Length < 1)
                {
                    throw new ParseException("If requires a parameter");
                }

                bool           blockOpen = false;
                CodeExpression condition = ParseFlowParameter(parts[1], true, out blockOpen, false);
                var            ifelse    = new CodeConditionStatement
                {
                    Condition = condition
                };

                var block = new CodeBlock(line, Scope, ifelse.TrueStatements, CodeBlock.BlockKind.IfElse, blocks.Count == 0 ? null : blocks.Peek());
                block.Type = blockOpen ? CodeBlock.BlockType.Within : CodeBlock.BlockType.Expect;
                CloseTopSingleBlock();
                blocks.Push(block);

                elses.Push(ifelse.FalseStatements);
                return(new CodeStatement[] { ifelse });
            }

            case FlowElse:
            {
                if (elses.Count == 0)
                {
                    throw new ParseException("Else with no preceeding if block");
                }

                string next = line.Code.TrimStart(Spaces).Substring(FlowElse.Length).TrimStart(Spaces);

                if (!IsEmptyStatement(next))
                {
                    lines.Insert(index + 1, new CodeLine(lines[index].FileName, lines[index].LineNumber, next));
                }

                var type  = parts.Length > 1 && parts[1][0] == BlockOpen ? CodeBlock.BlockType.Within : CodeBlock.BlockType.Expect;
                var block = new CodeBlock(lines[index], Scope, elses.Pop(), CodeBlock.BlockKind.IfElse, blocks.Count == 0 ? null : blocks.Peek())
                {
                    Type = type
                };
                CloseTopSingleBlock();
                blocks.Push(block);
            }
            break;

                #endregion If/Else

                #region Goto

            case FlowGosub:
            {
                if (parts.Length < 1)
                {
                    throw new ParseException("No label specified");
                }
                return(new CodeStatement[] { new CodeExpressionStatement(LocalLabelInvoke(parts[1])) });
            }

            case FlowGoto:
            {
                if (parts.Length < 1)
                {
                    throw new ParseException("No label specified");
                }
                return(new CodeStatement[] { new CodeExpressionStatement(LocalLabelInvoke(parts[1])), new CodeMethodReturnStatement() });
            }

                #endregion Goto

                #region Loops

            case FlowLoop:
            {
                bool blockOpen = false;
                CodeMethodInvokeExpression iterator;
                bool skip       = true;
                bool checkBrace = true;
                bool byref      = false;

                #region Loop types

                if (parts.Length > 1)
                {
                    string[] sub = parts[1].Split(new[] { Multicast }, 2);
                    sub = new[] { sub[0].Trim(), sub.Length > 1 ? sub[1].Trim() : string.Empty };

                    switch (sub[0].ToUpperInvariant())
                    {
                    case "READ":
                        byref    = true;
                        iterator = (CodeMethodInvokeExpression)InternalMethods.LoopRead;
                        break;

                    case "PARSE":
                        checkBrace = false;
                        byref      = true;
                        iterator   = (CodeMethodInvokeExpression)InternalMethods.LoopParse;
                        break;

                    case "HKEY_LOCAL_MACHINE":
                    case "HKLM":
                    case "HKEY_USERS":
                    case "HKU":
                    case "HKEY_CURRENT_USER":
                    case "HKCU":
                    case "HKEY_CLASSES_ROOT":
                    case "HKCR":
                    case "HKEY_CURRENT_CONFIG":
                    case "HKCC":
                        iterator = (CodeMethodInvokeExpression)InternalMethods.LoopRegistry;
                        break;

                    case "EACH":
                        byref    = true;
                        iterator = (CodeMethodInvokeExpression)InternalMethods.LoopEach;
                        break;

                    default:
                    {
                        var file = false;

                        if (parts[1].IndexOf(Multicast) != -1)
                        {
                            file = true;
                        }

                        // TODO: check file/iteration loop types

                        skip     = false;
                        iterator = (CodeMethodInvokeExpression)(file ? InternalMethods.LoopFile : InternalMethods.Loop);
                    }
                    break;
                    }

                    if (skip)
                    {
                        parts[1] = sub[1];
                    }

                    if (checkBrace)
                    {
                        // TODO: check expression parameters before stripping comments
                        int    x    = parts.Length == 1 ? 0 : 1;
                        string part = StripComment(parts[x]).TrimEnd(Spaces);
                        int    l    = part.Length - 1;
                        if (part.Length > 0 && part[l] == BlockOpen)
                        {
                            blockOpen = true;
                            parts[x]  = part.Substring(0, l);
                        }
                    }

                    if (skip && parts[1].Length == 0)
                    {
                        throw new ParseException("Loop type must have an argument");
                    }

                    foreach (var arg in SplitCommandParameters(parts[1]))
                    {
                        iterator.Parameters.Add(ParseCommandParameter(arg));
                    }

                    if (LegacyLoop && byref)
                    {
                        iterator.Parameters[0] = VarId(iterator.Parameters[0]);
                    }
                }
                else
                {
                    iterator = (CodeMethodInvokeExpression)InternalMethods.Loop;
                    iterator.Parameters.Add(new CodePrimitiveExpression(int.MaxValue));
                }

                #endregion Loop types

                string id = InternalID;

                var init = new CodeVariableDeclarationStatement();
                init.Name           = id;
                init.Type           = new CodeTypeReference(typeof(IEnumerable));
                init.InitExpression = new CodeMethodInvokeExpression(iterator, "GetEnumerator", new CodeExpression[] { });

                var condition = new CodeMethodInvokeExpression();
                condition.Method.TargetObject = new CodeVariableReferenceExpression(id);
                condition.Method.MethodName   = "MoveNext";

                var loop = new CodeIterationStatement();
                loop.InitStatement      = init;
                loop.IncrementStatement = new CodeCommentStatement(string.Empty);                                 // for C# display
                loop.TestExpression     = condition;

                var block = new CodeBlock(line, Scope, loop.Statements, CodeBlock.BlockKind.Loop, blocks.Count == 0 ? null : blocks.Peek(), InternalID, InternalID);
                block.Type = blockOpen ? CodeBlock.BlockType.Within : CodeBlock.BlockType.Expect;
                CloseTopSingleBlock();
                blocks.Push(block);

                return(new CodeStatement[] { loop, new CodeLabeledStatement(block.ExitLabel) });
            }

            case FlowWhile:
            {
                bool           blockOpen = false;
                CodeExpression condition = parts.Length > 1 ? ParseFlowParameter(parts[1], true, out blockOpen, true) : new CodePrimitiveExpression(true);
                var            loop      = new CodeIterationStatement();
                loop.TestExpression = condition;
                loop.InitStatement  = new CodeCommentStatement(string.Empty);

                var block = new CodeBlock(line, Scope, loop.Statements, CodeBlock.BlockKind.Loop, blocks.Count == 0 ? null : blocks.Peek(), InternalID, InternalID);
                block.Type = blockOpen ? CodeBlock.BlockType.Within : CodeBlock.BlockType.Expect;
                CloseTopSingleBlock();
                blocks.Push(block);

                return(new CodeStatement[] { loop, new CodeLabeledStatement(block.ExitLabel) });
            }

            case FlowBreak:
                int b = 1;
                if (parts.Length > 1)
                {
                    parts[1] = StripCommentSingle(parts[1]);
                    if (!int.TryParse(parts[1], out b) || b < 1)
                    {
                        throw new ParseException("Break parameter must be a static integer greater than zero.");
                    }
                }
                string exit = PeekLoopLabel(true, b);
                if (exit == null)
                {
                    throw new ParseException("Cannot break outside a loop");
                }
                return(new CodeStatement[] { new CodeGotoStatement(exit) });

            case FlowContinue:
                int c = 1;
                if (parts.Length > 1)
                {
                    parts[1] = StripCommentSingle(parts[1]);
                    if (!int.TryParse(parts[1], out c) || c < 1)
                    {
                        throw new ParseException("Continue parameter must be a static integer greater than zero.");
                    }
                }
                string cont = PeekLoopLabel(false, c);
                if (cont == null)
                {
                    throw new ParseException("Cannot continue outside a loop");
                }
                return(new CodeStatement[] { new CodeGotoStatement(cont) });

                #endregion Loops

                #region Return

            case FlowReturn:
                if (Scope == mainScope)
                {
                    if (parts.Length > 1)
                    {
                        throw new ParseException("Cannot have return parameter for entry point method");
                    }
                    return(new CodeStatement[] { new CodeMethodReturnStatement() });
                }
                else
                {
                    var result = parts.Length > 1 ? ParseSingleExpression(parts[1]) : new CodePrimitiveExpression(null);
                    return(new CodeStatement[] { new CodeMethodReturnStatement(result) });
                }

                #endregion Return

                #region Function

            case FunctionLocal:
            case FunctionGlobal:
            case FunctionStatic:
                // TODO: function local/global/static scoping modifiers
                break;

                #endregion Function

            default:
                throw new ParseException(ExUnexpected);
            }

            return(null);
        }
Example #26
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);
        }
Example #27
0
        internal protected override void GenerateBuildCode(GeneratorContext ctx, CodeExpression var)
        {
            if (!String.IsNullOrEmpty(UIManagerName))
            {
                // Create an UI manager
                CodeFieldReferenceExpression uixp     = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), UIManagerName);
                CodeAssignStatement          uim_init = new CodeAssignStatement(uixp, new CodeObjectCreateExpression(typeof(Gtk.UIManager).ToGlobalTypeRef()));
                ctx.Statements.Add(uim_init);

                includedActionGroups = new ArrayList();

                // Generate action group creation
                foreach (ActionGroup actionGroup in actionGroups)
                {
                    // Create the action group
                    string grpVar = ctx.NewId();
                    CodeVariableDeclarationStatement uidec = new CodeVariableDeclarationStatement(
                        typeof(Gtk.ActionGroup).ToGlobalTypeRef(),
                        grpVar,
                        actionGroup.GenerateObjectCreation(ctx)
                        );
                    ctx.Statements.Add(uidec);
                    actionGroup.GenerateBuildCode(ctx, new CodeVariableReferenceExpression(grpVar));

                    // Insert the action group in the UIManager
                    CodeMethodInvokeExpression mi = new CodeMethodInvokeExpression(
                        uixp,
                        "InsertActionGroup",
                        new CodeVariableReferenceExpression(grpVar),
                        new CodePrimitiveExpression(includedActionGroups.Count)
                        );
                    ctx.Statements.Add(mi);

                    includedActionGroups.Add(actionGroup);
                }

                // Adds the accel group to the window
                Window w = GetTopLevel() as Window;
                if (w != null)
                {
                    CodeMethodInvokeExpression ami = new CodeMethodInvokeExpression(
                        ctx.WidgetMap.GetWidgetExp(w),
                        "AddAccelGroup",
                        new CodePropertyReferenceExpression(
                            uixp,
                            "AccelGroup"
                            )
                        );
                    ctx.Statements.Add(ami);
                }
                else
                {
                    // There is no top level window, this must be a custom widget.
                    // The only option is to register the accel group when
                    // the widget is realized. This is done by the Bin wrapper.
                }
            }

            if (tooltip != null && tooltip.Length > 0)
            {
                GetTopLevel().GenerateTooltip(ctx, this);
            }

            base.GenerateBuildCode(ctx, var);
        }
 public CodeSimpleForLoopStatement(CodeVariableDeclarationStatement indexVariable, CodeExpression lengthExpression, bool loopBackwards = false)
 {
     LengthExpression = lengthExpression;
     IndexVariable    = indexVariable;
     LoopBackwards    = loopBackwards;
 }
        public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments)
        {
            string name = arguments["name"];
            string type = arguments["type"];

            if (string.IsNullOrEmpty(name))
            {
                throw new DirectiveProcessorException("Parameter directive has no name argument");
            }
            if (string.IsNullOrEmpty(type))
            {
                throw new DirectiveProcessorException("Parameter directive has no type argument");
            }

            string fieldName = "_" + name + "Field";
            var    typeRef   = new CodeTypeReference(type);
            var    thisRef   = new CodeThisReferenceExpression();
            var    fieldRef  = new CodeFieldReferenceExpression(thisRef, fieldName);

            var property = new CodeMemberProperty()
            {
                Name       = name,
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                HasGet     = true,
                HasSet     = false,
                Type       = typeRef
            };

            property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
            members.Add(new CodeMemberField(typeRef, fieldName));
            members.Add(property);

            string acquiredName           = "_" + name + "Acquired";
            var    valRef                 = new CodeVariableReferenceExpression("data");
            var    namePrimitive          = new CodePrimitiveExpression(name);
            var    sessionRef             = new CodePropertyReferenceExpression(thisRef, "Session");
            var    callContextTypeRefExpr = new CodeTypeReferenceExpression("System.Runtime.Remoting.Messaging.CallContext");
            var    nullPrim               = new CodePrimitiveExpression(null);

            var acquiredVariable    = new CodeVariableDeclarationStatement(typeof(bool), acquiredName, new CodePrimitiveExpression(false));
            var acquiredVariableRef = new CodeVariableReferenceExpression(acquiredVariable.Name);

            this.postStatements.Add(acquiredVariable);

            //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true
            var checkCastThenAssignVal = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeOfExpression(typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression(valRef, "GetType")),
                new CodeStatement[] {
                new CodeAssignStatement(fieldRef, new CodeCastExpression(typeRef, valRef)),
                new CodeAssignStatement(acquiredVariableRef, new CodePrimitiveExpression(true)),
            },
                new CodeStatement[] {
                new CodeExpressionStatement(new CodeMethodInvokeExpression(thisRef, "Error",
                                                                           new CodePrimitiveExpression("The type '" + type + "' of the parameter '" + name +
                                                                                                       "' did not match the type passed to the template"))),
            });

            //tries to gets the value from the session
            var checkSession = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(NotNull(sessionRef), CodeBinaryOperatorType.BooleanAnd,
                                                 new CodeMethodInvokeExpression(sessionRef, "ContainsKey", namePrimitive)),
                new CodeVariableDeclarationStatement(typeof(object), "data", new CodeIndexerExpression(sessionRef, namePrimitive)),
                checkCastThenAssignVal);

            this.postStatements.Add(checkSession);

            //if acquiredVariable is false, tries to gets the value from the host
            if (hostSpecific)
            {
                var hostRef   = new CodePropertyReferenceExpression(thisRef, "Host");
                var checkHost = new CodeConditionStatement(
                    BooleanAnd(IsFalse(acquiredVariableRef), NotNull(hostRef)),
                    new CodeVariableDeclarationStatement(typeof(string), "data",
                                                         new CodeMethodInvokeExpression(hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)),
                    new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal));

                this.postStatements.Add(checkHost);
            }

            //if acquiredVariable is false, tries to gets the value from the call context
            var checkCallContext = new CodeConditionStatement(
                IsFalse(acquiredVariableRef),
                new CodeVariableDeclarationStatement(typeof(object), "data",
                                                     new CodeMethodInvokeExpression(callContextTypeRefExpr, "LogicalGetData", namePrimitive)),
                new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal));

            this.postStatements.Add(checkCallContext);
        }
Example #30
0
        /// <summary>
        /// Generates control fields
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="method">The initialize method.</param>
        /// <param name="generateField">if set to <c>true</c> [generate field].</param>
        /// <returns></returns>
        public virtual CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField)
        {
            FrameworkElement element  = source as FrameworkElement;
            string           typeName = element.GetType().Name;

            if (string.IsNullOrEmpty(element.Name))
            {
                element.Name = "e_" + nameUniqueId;
                nameUniqueId++;
            }

            if (generateField)
            {
                CodeMemberField field = new CodeMemberField(typeName, element.Name);
                classType.Members.Add(field);
            }

            CodeComment comment = new CodeComment(element.Name + " element");

            method.Statements.Add(new CodeCommentStatement(comment));

            CodeExpression fieldReference = null;

            if (!generateField)
            {
                fieldReference = new CodeVariableReferenceExpression(element.Name);
                CodeTypeReference variableType = new CodeTypeReference(typeName);
                CodeVariableDeclarationStatement declaration = new CodeVariableDeclarationStatement(variableType, element.Name);
                declaration.InitExpression = new CodeObjectCreateExpression(typeName);
                method.Statements.Add(declaration);
            }
            else
            {
                fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), element.Name);
                method.Statements.Add(new CodeAssignStatement(fieldReference, new CodeObjectCreateExpression(typeName)));
            }

            CodeComHelper.GenerateField <string>(method, fieldReference, source, FrameworkElement.NameProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.HeightProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.MaxHeightProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.MinHeightProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.WidthProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.MaxWidthProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.MinWidthProperty);
            CodeComHelper.GenerateField <object>(method, fieldReference, source, FrameworkElement.TagProperty);
            CodeComHelper.GenerateField <bool>(method, fieldReference, source, FrameworkElement.IsEnabledProperty);
            CodeComHelper.GenerateField <bool>(method, fieldReference, source, FrameworkElement.IsHitTestVisibleProperty);
            CodeComHelper.GenerateField <bool>(method, fieldReference, source, FrameworkElement.SnapsToDevicePixelsProperty);
            CodeComHelper.GenerateField <bool>(method, fieldReference, source, UIElement.FocusableProperty);
            CodeComHelper.GenerateEnumField <Visibility>(method, fieldReference, source, FrameworkElement.VisibilityProperty);
            CodeComHelper.GenerateThicknessField(method, fieldReference, source, FrameworkElement.MarginProperty);
            CodeComHelper.GenerateEnumField <HorizontalAlignment>(method, fieldReference, source, FrameworkElement.HorizontalAlignmentProperty);
            CodeComHelper.GenerateEnumField <VerticalAlignment>(method, fieldReference, source, FrameworkElement.VerticalAlignmentProperty);
            CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, FrameworkElement.StyleProperty);
            CodeComHelper.GenerateToolTipField(classType, method, fieldReference, source, FrameworkElement.ToolTipProperty);
            CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, FrameworkElement.OpacityProperty);

            if (element.Triggers.Count > 0)
            {
                string parentName = element.Name;
                GenerateTriggers(classType, method, element, typeName, fieldReference, parentName);
            }

            if (element.InputBindings.Count > 0)
            {
                GenerateInputBindings(method, element);
            }

            return(fieldReference);
        }
Example #31
0
        private static void GenerateProperties(Type t, CodeTypeDeclaration codeType)
        {
            foreach (PropertyInfo property in t.GetProperties())
            {
                if (OmittedProperties.ContainsKey(t.FullName) && OmittedProperties[t.FullName].Contains(property.Name))
                {
                    continue;
                }

                if (property.CustomAttributes.Any(x => x.AttributeType.FullName.Contains("Obsolete")))
                {
                    continue;
                }

                string propertyType        = GetPropertyType(property.PropertyType);
                bool   isGenericCollection = property.PropertyType.IsGenericType &&
                                             (property.PropertyType.GetGenericTypeDefinition() == typeof(IList <>) || property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                                              property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>));

                CodeFieldReferenceExpression    wrappedObject         = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OmObject);
                CodePropertyReferenceExpression wrappedObjectProperty = new CodePropertyReferenceExpression(wrappedObject, property.Name);
                CodeFieldReferenceExpression    fieldReference        = null;
                if (isGenericCollection || OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    // Add a backing field for the property with the same name but using camel case.
                    string          fieldName    = string.Format("{0}{1}", property.Name.ToLower()[0], property.Name.Substring(1, property.Name.Length - 1));
                    CodeMemberField backingField = new CodeMemberField();
                    backingField.Attributes = MemberAttributes.Private;
                    backingField.Name       = fieldName;
                    backingField.Type       = new CodeTypeReference(propertyType);
                    codeType.Members.Add(backingField);

                    fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
                }

                CodeMemberProperty codeProperty = new CodeMemberProperty();
                codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                codeProperty.Name       = property.Name;
                codeProperty.Type       = new CodeTypeReference(propertyType);

                // For properties with a backing field, the field will not be initialized in the constructor in order to avoid
                // hitting a run time access constraint from the OM. Instead, the field is initialized on the first access of
                // the property.

                if (isGenericCollection)
                {
                    // Collections are not kept in sync with the wrapped OM object. Cmdlets will need to sync them before sending
                    // a request to the server.
                    Type   argType         = property.PropertyType.GetGenericArguments()[0];
                    string wrapperArgType  = argType.FullName.StartsWith("System") ? argType.FullName : OMtoPSClassMappings[argType.FullName];
                    string wrapperListType = string.Format("List<{0}>", wrapperArgType);

                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        // Build a list of wrapper objects
                        const string listVariableName = "list";
                        CodeVariableDeclarationStatement listDeclaration = new CodeVariableDeclarationStatement(wrapperListType, listVariableName);
                        CodeVariableReferenceExpression  listReference   = new CodeVariableReferenceExpression(listVariableName);
                        CodeAssignStatement initializeList = new CodeAssignStatement(listReference, new CodeObjectCreateExpression(wrapperListType));

                        // CodeDom doesn't support foreach loops very well, so instead explicitly get the enumerator and loop on MoveNext() calls
                        const string enumeratorVariableName = "enumerator";
                        CodeVariableDeclarationStatement enumeratorDeclaration = new CodeVariableDeclarationStatement(string.Format("IEnumerator<{0}>", argType.FullName), enumeratorVariableName);
                        CodeVariableReferenceExpression  enumeratorReference   = new CodeVariableReferenceExpression(enumeratorVariableName);
                        CodeAssignStatement    initializeEnumerator            = new CodeAssignStatement(enumeratorReference, new CodeMethodInvokeExpression(wrappedObjectProperty, "GetEnumerator"));
                        CodeIterationStatement loopStatement = new CodeIterationStatement();
                        loopStatement.TestExpression     = new CodeMethodInvokeExpression(enumeratorReference, "MoveNext");
                        loopStatement.IncrementStatement = new CodeSnippetStatement(string.Empty);
                        loopStatement.InitStatement      = new CodeSnippetStatement(string.Empty);
                        CodePropertyReferenceExpression enumeratorCurrent = new CodePropertyReferenceExpression(enumeratorReference, "Current");

                        // Fill the list by individually wrapping each item in the loop
                        if (wrapperArgType.Contains("System"))
                        {
                            CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(listReference, "Add", enumeratorCurrent);
                            loopStatement.Statements.Add(addToList);
                        }
                        else
                        {
                            CodeObjectCreateExpression createListItem = new CodeObjectCreateExpression(wrapperArgType, enumeratorCurrent);
                            CodeMethodInvokeExpression addToList      = new CodeMethodInvokeExpression(listReference, "Add", createListItem);
                            loopStatement.Statements.Add(addToList);
                        }

                        // Initialize the backing field with the built list on first access of the property
                        CodeAssignStatement assignStatement;
                        if (property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>))
                        {
                            CodeMethodInvokeExpression asReadOnlyList = new CodeMethodInvokeExpression(listReference, "AsReadOnly");
                            assignStatement = new CodeAssignStatement(fieldReference, asReadOnlyList);
                        }
                        else
                        {
                            assignStatement = new CodeAssignStatement(fieldReference, listReference);
                        }
                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, listDeclaration, initializeList, enumeratorDeclaration, initializeEnumerator, loopStatement, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        // Call the "set" on the OM object to ensure that constraints are enforced.
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nullAssignment    = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodeObjectCreateExpression(string.Format("List<{0}>", argType.FullName)));
                        CodeConditionStatement ifBlock           = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else if (OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        CodeObjectCreateExpression   createFieldObject        = new CodeObjectCreateExpression(OMtoPSClassMappings[property.PropertyType.FullName], wrappedObjectProperty);
                        CodeAssignStatement          assignStatement          = new CodeAssignStatement(fieldReference, createFieldObject);
                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement             nullAssignment         = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodePropertyReferenceExpression valueProperty          = new CodePropertyReferenceExpression(valueReference, OmObject);
                        CodeAssignStatement             nonNullAssignment      = new CodeAssignStatement(wrappedObjectProperty, valueProperty);
                        CodeConditionStatement          ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else
                {
                    // By default, just pass through to the wrapped OM object's property.
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(wrappedObjectProperty));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        codeProperty.SetStatements.Add(new CodeAssignStatement(wrappedObjectProperty, new CodePropertySetValueReferenceExpression()));
                    }
                }
                codeType.Members.Add(codeProperty);
            }
        }
        /// <summary>
        /// Constructs the CodeDOM method used to transform abstract data into a readable document.
        /// </summary>
        /// <param name="templateNode">Contains the specification for the template.</param>
        public DataTransformTemplateMethod(DataTransform.TemplateNode templateNode)
        {
            // This is a rudimentary test for the start of the document.  The idea is to follow the XSL language where possible
            // but the rigours of an XPATH parser are beyond the scope of this function at the time of this writing.  In the future
            // it should be expanded to follow an XPATH like specification into the data model.
            bool isRootTemplate = templateNode.Match.StartsWith("/");

            // Some top-level information will be needed to construct the template, such as the class name to reference constants.
            DataTransform dataTransform = templateNode.TopLevelNode as DataTransform;

            //		/// <summary>
            //		/// Transforms a row of data into screen instructions.
            //		/// </summary>
            //		/// <param name="viewerTable">The current outline level of the document.</param>
            //		/// <param name="dataRow">The source of the data for this template.</param>
            //		public virtual void SlashTemplate(MarkThree.Forms.ViewerTable viewerTable, System.Data.DataRow dataRow)
            //		{
            this.Comments.Add(new CodeCommentStatement(@"<summary>", true));
            this.Comments.Add(new CodeCommentStatement(@"Transforms a row of data into screen instructions.", true));
            this.Comments.Add(new CodeCommentStatement(@"</summary>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""viewerTable"">The current outline level of the document.</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""dataRow"">The source of the data for this template.</param>", true));
            this.Name       = string.Format("{0}Template", templateNode.Match.Replace("/", "Slash"));
            this.Attributes = MemberAttributes.Public;
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(ViewerTable), "viewerTable"));
            string rowType         = isRootTemplate ? "DataRow" : string.Format(string.Format("{0}Row", templateNode.Match));
            string rowNamespace    = isRootTemplate ? "System.Data" : dataTransform.Source;
            string rowVariableName = CamelCase.Convert(rowType);

            this.Parameters.Add(new CodeParameterDeclarationExpression(string.Format("{0}.{1}", rowNamespace, rowType), rowVariableName));

            // This will create the instructions for generating each row that appears in the template.
            int rowIndex = 0;

            foreach (DataTransform.RowNode rowNode in templateNode.Rows)
            {
                //				// Execution
                //				MarkThree.Forms.ViewerRow viewerRow0 = new MarkThree.Forms.ViewerRow();
                //				viewerRow0.Data = new object[17];
                //				viewerRow0.Tiles = new ViewerTile[17];
                //				viewerRow0.Children = new ViewerTable[2];

                string viewerRowVariableName = string.Format("viewerRow{0}", rowIndex++);
                this.Statements.Add(new CodeCommentStatement(rowNode.RowId));
                this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerRow), viewerRowVariableName, new CodeObjectCreateExpression(typeof(ViewerRow))));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                            new CodeArrayCreateExpression(typeof(object), new CodePrimitiveExpression(dataTransform.Columns.Count))));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Tiles"),
                                                            new CodeArrayCreateExpression(typeof(ViewerTile), new CodePrimitiveExpression(dataTransform.View.Count))));
                int childTableCount = 0;
                foreach (DataTransform.ApplyTemplateNode applyTemplateNode in rowNode.ApplyTemplates)
                {
                    if (applyTemplateNode.RowFilter.ToLower() != bool.FalseString.ToLower())
                    {
                        childTableCount++;
                    }
                }
                if (childTableCount != 0)
                {
                    this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Children"),
                                                                new CodeArrayCreateExpression(typeof(ViewerTable), new CodePrimitiveExpression(childTableCount))));
                }

                // Add in any temporary variables that need to be calculated.
                if (rowNode.ScratchList.Count != 0)
                {
                    // This will add any temporary variables needed to compute the data in a column.
                    this.Statements.Add(new CodeCommentStatement("This will calculate intermediate values used in the row."));
                    foreach (DataTransform.ScratchNode scratchNode in rowNode.ScratchList)
                    {
                        this.Statements.Add(new CodeSnippetExpression(scratchNode.Text.Trim().Trim(';')));
                    }
                }

                // This will create instructions for generating each of the tiles that appear in the row.
                this.Statements.Add(new CodeCommentStatement("Populate the data image of the row."));
                foreach (DataTransform.ColumnNode columnNode in dataTransform.Columns)
                {
                    // The 'View' describes the order of the columns.  Attempt to find the corresponding column in the row
                    // definition.  If it doesn't exist in the row, it will likely screw up the spacing of the document, but it
                    // won't crash with this check.
                    DataTransform.TileNode tileNode;
                    if (!rowNode.Tiles.TryGetValue(columnNode.ColumnId, out tileNode))
                    {
                        continue;
                    }

                    //					viewerRow0.Data[PrototypeViewer.workingStatusImageIndex] = this.variables["WorkingStatusHeaderImage"];
                    CodeExpression dataReferenceExpression = tileNode.Data != string.Empty ? (CodeExpression) new CodeSnippetExpression(tileNode.Data) :
                                                             tileNode.VariableName != string.Empty ? (CodeExpression) new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "documentViewer"), "Variables"), new CodePrimitiveExpression(tileNode.VariableName)) :
                                                             (CodeExpression) new CodePrimitiveExpression(DBNull.Value);
                    this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnNode.ColumnId)))),
                                                                dataReferenceExpression));
                }

                // This is a common value for all tiles in the row.
                CodeFieldReferenceExpression heightExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Height", CamelCase.Convert(rowNode.RowId)));

                // This will create instructions for generating each of the tiles that appear in the row.
                int tileIndex = 0;
                foreach (DataTransform.ColumnReferenceNode columnReferenceNode in dataTransform.View)
                {
                    // The 'View' describes the order of the columns.  Attempt to find the corresponding column in the row
                    // definition.  If it doesn't exist in the row, it will likely screw up the spacing of the document, but it
                    // won't crash with this check.
                    DataTransform.TileNode tileNode;
                    if (!rowNode.Tiles.TryGetValue(columnReferenceNode.ColumnId, out tileNode))
                    {
                        continue;
                    }

                    //					// WorkingStatusImage
                    //					MarkThree.Forms.ViewerTile viewerTile0 = this.documentViewer.GetTile(executionRow, PrototypeView.workingStatusImageIndex);
                    this.Statements.Add(new CodeCommentStatement(columnReferenceNode.ColumnId));
                    string tileVariableName = string.Format("viewerTile{0}", tileIndex);
                    string constantName     = CamelCase.Convert(columnReferenceNode.ColumnId) + "Index";
                    this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerTile), tileVariableName, new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "documentViewer"), "GetTile"), new CodeVariableReferenceExpression(rowVariableName), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), constantName))));

                    //					string viewerStyleId0 = "HeaderImage";
                    //					if (viewerStyleId0 != viewerTile0.ViewerStyleId)
                    //					{
                    //						viewerTile0.ViewerStyleId = viewerStyleId0;
                    //						viewerTile0.IsModified = true;
                    //					}
                    if (tileNode.StyleId != string.Empty)
                    {
                        string styleIdVariableName = string.Format("viewerStyleId{0}", tileIndex);
                        this.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), styleIdVariableName, new CodeSnippetExpression(tileNode.StyleId)));
                        CodeStatement[] trueStatements0 = new CodeStatement[2];
                        trueStatements0[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "ViewerStyleId"), new CodeVariableReferenceExpression(styleIdVariableName));
                        trueStatements0[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                        this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(styleIdVariableName), CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "ViewerStyleId")), trueStatements0));
                    }

                    //					if ((viewerRow0.Data[PrototypeView.workingStatusImageOrdinal].Equals(viewerTile0.Data) != true))
                    //					{
                    //						viewerTile0.Data = viewerRow0.Data[PrototypeView.workingStatusImageOrdinal];
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeStatement[] trueStatements = new CodeStatement[2];
                    trueStatements[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Data"), new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                                                                                                                           new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnReferenceNode.ColumnId)))));
                    trueStatements[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeMethodInvokeExpression(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                                                                                             new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnReferenceNode.ColumnId)))), "Equals",
                                                                                                                                   new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Data")), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true)), trueStatements));

                    //					SizeF sizeF0 = new SizeF(PrototypeView.workingStatusImageWidth, PrototypeView.headerHeight);
                    //					if ((sizeF0 != viewerTile0.RectangleF.Size))
                    //					{
                    //						viewerTile0.RectangleF.Size = sizeF0;
                    //						viewerTile0.IsModified = true;
                    //					}
                    //CodeFieldReferenceExpression widthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(columnReferenceNode.ColumnId)));
                    //string sizeVariableName = string.Format("sizeF{0}", tileIndex);
                    //this.Statements.Add(new CodeVariableDeclarationStatement(typeof(SizeF), sizeVariableName, new CodeObjectCreateExpression(typeof(SizeF), widthExpression, heightExpression)));
                    //CodeStatement[] trueStatements1 = new CodeStatement[2];
                    //trueStatements1[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Size"), new CodeVariableReferenceExpression(sizeVariableName));
                    //trueStatements1[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    //this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(sizeVariableName), CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Size")), trueStatements1));

                    //					if ((PrototypeView.workingStatusImageWidth != viewerTile0.RectangleF.Width))
                    //					{
                    //						viewerTile0.RectangleF.Width = PrototypeView.workingStatusImageWidth;
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeFieldReferenceExpression widthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(columnReferenceNode.ColumnId)));
                    CodeStatement[] trueStatements1 = new CodeStatement[2];
                    trueStatements1[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Width"), widthExpression);
                    trueStatements1[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(widthExpression, CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Width")), trueStatements1));

                    //					if ((PrototypeView.headerHeight != viewerTile0.RectangleF.Height))
                    //					{
                    //						viewerTile0.RectangleF.Height = PrototypeView.headerHeight;
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeStatement[] trueStatements2 = new CodeStatement[2];
                    trueStatements2[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Height"), heightExpression);
                    trueStatements2[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(heightExpression, CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Height")), trueStatements2));

                    //					viewerTile0.Cursor.Width = PrototypeView.workingStatusImageWidth;
                    //					viewerTile0.Cursor.Height = 0;
                    if (tileIndex < dataTransform.View.Count - 1)
                    {
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Width"), widthExpression));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Height"), new CodePrimitiveExpression(0.0f)));
                    }
                    else
                    {
                        CodeExpression columnWidthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(dataTransform.View[tileIndex].Column.ColumnId)));
                        CodeExpression rowWidthExpression    = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(rowNode.RowId)));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Width"), new CodeBinaryOperatorExpression(columnWidthExpression, CodeBinaryOperatorType.Subtract, rowWidthExpression)));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Height"), heightExpression));
                    }

                    //					viewerRow0.Tiles[PrototypeViewer.statusImageOrdinal] = viewerTile0;
                    this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Tiles"),
                                                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Ordinal", CamelCase.Convert(columnReferenceNode.ColumnId)))),
                                                                new CodeVariableReferenceExpression(tileVariableName)));

                    // This indexer will keep the variable names distinct for each column.
                    tileIndex++;
                }

                // Each row can have one or more relationship to child rows that are specified in the 'ApplyTemplate' node.  This
                // specification works very similar to the XSL analog in that it traces through the child nodes seeing if there are
                // any templates that can be applied.
                int childIndex = 0;
                foreach (DataTransform.ApplyTemplateNode applyTemplateNode in rowNode.ApplyTemplates)
                {
                    // It's possible for debugging to include a 'False' row filter, which would remove all the children from the
                    // applied templates.  Unfortunately, an expression that always evaluates to 'False' will result in a warning
                    // about unreachable code.  This will remove the entire reference to the children when the row filter
                    // expression is 'False'.
                    if (applyTemplateNode.RowFilter.ToLower() != bool.FalseString.ToLower())
                    {
                        //						// This will add the child relations for this row to the document.
                        //						MarkThree.Forms.ViewerTable workingOrderTable = new MarkThree.Forms.ViewerTable();
                        //						for (int rowIndex = 0; (rowIndex < SimulatedDatabase.WorkingOrder.Count); rowIndex = (rowIndex + 1))
                        //						{
                        //							SimulatedDatabase.WorkingOrderRow workingOrderRow = SimulatedDatabase.WorkingOrder[rowIndex];
                        //							if (workingOrderRow.StatusCode != 6)
                        //							{
                        //								this.WorkingOrderTemplate(workingOrderTable, workingOrderRow);
                        //							}
                        //						}
                        this.Statements.Add(new CodeCommentStatement("This will add the child relations for this row to the document."));
                        string tableVariableName = string.Format("{0}Table", CamelCase.Convert(applyTemplateNode.Select));
                        this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerTable), tableVariableName, new CodeObjectCreateExpression(typeof(ViewerTable))));
                        CodeExpression childRows = isRootTemplate ?
                                                   (CodeExpression) new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.Source), applyTemplateNode.Select) :
                                                   (CodeExpression) new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(rowVariableName), string.Format("Get{0}Rows", applyTemplateNode.Select)));
                        string                  countingMember          = isRootTemplate ? "Count" : "Length";
                        CodeStatement           initializationStatement = new CodeVariableDeclarationStatement(typeof(int), "rowIndex", new CodePrimitiveExpression(0));
                        CodeExpression          testExpression          = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("rowIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(childRows, countingMember));
                        CodeStatement           incrementStatement      = new CodeAssignStatement(new CodeVariableReferenceExpression("rowIndex"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("rowIndex"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
                        CodeStatementCollection iterationBody           = new CodeStatementCollection();
                        string                  childRowName            = CamelCase.Convert(string.Format("{0}Row", applyTemplateNode.Select));
                        iterationBody.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(string.Format("{0}.{1}Row", dataTransform.Source, applyTemplateNode.Select)), childRowName, new CodeIndexerExpression(childRows, new CodeVariableReferenceExpression("rowIndex"))));
                        if (applyTemplateNode.RowFilter == string.Empty)
                        {
                            iterationBody.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), string.Format("{0}Template", applyTemplateNode.Select), new CodeVariableReferenceExpression(tableVariableName), new CodeVariableReferenceExpression(childRowName))));
                        }
                        else
                        {
                            iterationBody.Add(new CodeConditionStatement(new CodeSnippetExpression(applyTemplateNode.RowFilter), new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), string.Format("{0}Template", applyTemplateNode.Select), new CodeVariableReferenceExpression(tableVariableName), new CodeVariableReferenceExpression(childRowName)))));
                        }
                        CodeStatement[] iterationArray = new CodeStatement[iterationBody.Count];
                        iterationBody.CopyTo(iterationArray, 0);
                        this.Statements.Add(new CodeIterationStatement(initializationStatement, testExpression, incrementStatement, iterationArray));
                        if (applyTemplateNode.Sorts.Count > 0)
                        {
                            this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(tableVariableName), "Sort", new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), string.Format("{0}RowComparer", CamelCase.Convert(applyTemplateNode.Select)))));
                        }

                        //						// The child table is associated to the parent row here.
                        //						viewerRow0.Children[0] = workingOrderTable;
                        this.Statements.Add(new CodeCommentStatement("The child table is associated to the parent row here."));
                        this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Children"), new CodePrimitiveExpression(childIndex)), new CodeVariableReferenceExpression(tableVariableName)));
                    }
                }

                //				// The child rows are added to the parent tables when they've been built.  In this way the hierarchical document is
                //				// built.
                //				viewerTable.Add(viewerRow0);
                this.Statements.Add(new CodeCommentStatement("The child rows are added to the parent tables when they've been built.  In this way the hierarchical document is"));
                this.Statements.Add(new CodeCommentStatement("built."));
                this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("viewerTable"), "Add", new CodeVariableReferenceExpression(viewerRowVariableName)));
            }
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        if (!(provider is JScriptCodeProvider)) {
            // GENERATES (C#):
            //   namespace Foo {
            //       public class Foo {
            //
            //           public int _verifyGlobalGeneration1 = 2147483647;
            //
            //           public int System {
            //              get { return 42; }
            //           }
            //   
            //           public int Property {
            //               get { return 2147483647; }
            //           }
            //
            //           public int GlobalTestProperty1 {
            //               get {
            //                   return _verifyGlobalGeneration1;
            //               }
            //               set {
            //                   _verifyGlobalGeneration1 = value;
            //               }
            //           }
            //         
            //           public global::System.Nullable<int> GlobalTestProperty2 {
            //               get {
            //                   return _verifyGlobalGeneration2;
            //               }
            //               set {
            //                   _verifyGlobalGeneration2 = value;
            //               }
            //           }
            //           
            //   
            //           public int TestMethod02() {
            //               int iReturn;
            //               iReturn = global::Foo.Foo.Property;
            //               return iReturn;
            //           }
            //   
            //           public int TestMethod03() {
            //               int iReturn;
            //               iReturn = global::System.Math.Abs(-1);
            //               return iReturn;
            //           }
            //
            //           public int TestMethod04() {
            //               int iReturn;
            //               iReturn = System;
            //               return iReturn;
            //       }
            //   }

            CodeNamespace ns = new CodeNamespace ("Foo");
            ns.Comments.Add (new CodeCommentStatement ("Foo namespace"));

            cu.Namespaces.Add (ns);

            CodeTypeDeclaration cd = new CodeTypeDeclaration ("Foo");
            ns.Types.Add (cd);

            CodeMemberProperty property = new CodeMemberProperty ();
            property.Name = "System";
            property.Attributes = MemberAttributes.Public;
            property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static;
            property.Type = new CodeTypeReference (typeof (int));
            property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (42)));
            cd.Members.Add (property);

            property = new CodeMemberProperty ();
            property.Name = "Property";
            property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private | MemberAttributes.Static;
            property.Type = new CodeTypeReference (typeof (int));
            property.GetStatements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (Int32.MaxValue)));
            cd.Members.Add (property);

            AddScenario ("CallTestMethod02", "Call Foo.Foo.TestMethod02.");
            CodeMemberMethod method2 = new CodeMemberMethod ();
            method2.Name = "TestMethod02";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.ReturnType = new CodeTypeReference (typeof (int));
            method2.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn"));

            CodePropertyReferenceExpression cpr = new CodePropertyReferenceExpression (
                                              new CodeTypeReferenceExpression (new CodeTypeReference ("Foo.Foo",
                                                      CodeTypeReferenceOptions.GlobalReference)), "Property");

            CodeAssignStatement cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr);
            method2.Statements.Add (cas);
            method2.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn")));
            cd.Members.Add (method2);

            AddScenario ("CallTestMethod03", "Call Foo.Foo.TestMethod02.");
            CodeMemberMethod method3 = new CodeMemberMethod ();
            method3.Name = "TestMethod03";
            method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method3.ReturnType = new CodeTypeReference (typeof (int));
            method3.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn"));
            CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference;
            CodeTypeReference ctr = new CodeTypeReference (typeof (Math), ctro);
            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression (
                                              new CodeMethodReferenceExpression (
                                              new CodeTypeReferenceExpression (ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression (-1) });
            cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cmie);
            method3.Statements.Add (cas);
            method3.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn")));
            cd.Members.Add (method3);

            AddScenario ("CallTestMethod04", "Call Foo.Foo.TestMethod04.");
            CodeMemberMethod method4 = new CodeMemberMethod ();
            method4.Name = "TestMethod04";
            method4.Attributes = (method4.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method4.ReturnType = new CodeTypeReference (typeof (int));
            method4.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "iReturn"));

            cpr = new CodePropertyReferenceExpression (null, "System");

            cas = new CodeAssignStatement (new CodeVariableReferenceExpression ("iReturn"), cpr);
            method4.Statements.Add (cas);
            method4.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("iReturn")));
            cd.Members.Add (method4);

            // Verify that what CodeTypeReferenceOptions are correctly set. 
            // Basically this check gives the code coverage for the get property
            AddScenario ("CTR_GetGlobalRefCheck", "Check that CodeTypeReference.Options gives the proper value.");
            if (ctr.Options == CodeTypeReferenceOptions.GlobalReference)
                VerifyScenario ("CTR_GetGlobalRefCheck");

            // one-off generate statements
            StringWriter sw = new StringWriter ();

            // global shouldn't be generated in this instance
            CodeTypeReference variableType = new CodeTypeReference (typeof (System.String), CodeTypeReferenceOptions.GlobalReference);
            CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement (variableType, "myVariable");
            provider.GenerateCodeFromStatement (variable, sw, null);

            // global should be generated in this instance
            CodeTypeReference variableType2 = new CodeTypeReference (typeof (System.Array), CodeTypeReferenceOptions.GlobalReference);
            CodeVariableDeclarationStatement variable2 = new CodeVariableDeclarationStatement (variableType2, "myVariable2");
            provider.GenerateCodeFromStatement (variable2, sw, null);

            AddScenario ("GlobalKeywordShouldExist", "When an array is referred to, a global qualifier should be generated on it.");
            if (sw.ToString ().IndexOf ("global") != -1 && sw.ToString ().IndexOf ("Global") != -1) {
                LogMessage ("Global keyword does not exist in statement: " + sw.ToString ());
            }
            else
                VerifyScenario ("GlobalKeywordShouldExist");
        }
    }
        public void ComplexExample()
        {
            string          code = @"class A {
	Button closeButton;
	void M() {
		System.Windows.Forms.Panel panel1;
		closeButton = new System.Windows.Forms.Button();
		panel1 = new System.Windows.Forms.Panel();
		panel1.SuspendLayout();
		panel1.Controls.Add(this.closeButton);
		closeButton.BackColor = System.Drawing.Color.FromArgb();
		panel1.BackColor = System.Drawing.SystemColors.Info;
	}
}";
            TypeDeclaration decl = Ast.ParseUtilCSharp.ParseGlobal <TypeDeclaration>(code);
            CompilationUnit cu   = new CompilationUnit();

            cu.AddChild(decl);
            CodeNamespace ns = (CodeNamespace)cu.AcceptVisitor(new CodeDomVisitor(), null);

            Assert.AreEqual("A", ns.Types[0].Name);
            Assert.AreEqual("closeButton", ns.Types[0].Members[0].Name);
            Assert.AreEqual("M", ns.Types[0].Members[1].Name);
            CodeMemberMethod m = (CodeMemberMethod)ns.Types[0].Members[1];

            CodeVariableDeclarationStatement s0 = (CodeVariableDeclarationStatement)m.Statements[0];

            Assert.AreEqual("panel1", s0.Name);
            Assert.AreEqual("System.Windows.Forms.Panel", s0.Type.BaseType);

            CodeAssignStatement cas = (CodeAssignStatement)m.Statements[1];

            Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)cas.Left).FieldName);

            cas = (CodeAssignStatement)m.Statements[2];
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)cas.Left).VariableName);

            CodeExpressionStatement    ces = (CodeExpressionStatement)m.Statements[3];
            CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)ces.Expression;

            Assert.AreEqual("SuspendLayout", mie.Method.MethodName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)mie.Method.TargetObject).VariableName);

            ces = (CodeExpressionStatement)m.Statements[4];
            mie = (CodeMethodInvokeExpression)ces.Expression;
            Assert.AreEqual("Add", mie.Method.MethodName);
            CodePropertyReferenceExpression pre = (CodePropertyReferenceExpression)mie.Method.TargetObject;

            Assert.AreEqual("Controls", pre.PropertyName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);

            cas = (CodeAssignStatement)m.Statements[5];
            pre = (CodePropertyReferenceExpression)cas.Left;
            Assert.AreEqual("BackColor", pre.PropertyName);
            Assert.AreEqual("closeButton", ((CodeFieldReferenceExpression)pre.TargetObject).FieldName);
            mie = (CodeMethodInvokeExpression)cas.Right;
            Assert.AreEqual("FromArgb", mie.Method.MethodName);
            Assert.IsTrue(mie.Method.TargetObject is CodeTypeReferenceExpression);
            Assert.AreEqual("System.Drawing.Color", (mie.Method.TargetObject as CodeTypeReferenceExpression).Type.BaseType);

            cas = (CodeAssignStatement)m.Statements[6];
            pre = (CodePropertyReferenceExpression)cas.Left;
            Assert.AreEqual("BackColor", pre.PropertyName);
            Assert.AreEqual("panel1", ((CodeVariableReferenceExpression)pre.TargetObject).VariableName);
            pre = (CodePropertyReferenceExpression)cas.Right;
            Assert.AreEqual("Info", pre.PropertyName);
            Assert.IsTrue(pre.TargetObject is CodeTypeReferenceExpression);
            Assert.AreEqual("System.Drawing.SystemColors", (pre.TargetObject as CodeTypeReferenceExpression).Type.BaseType);
        }
 private static CodeMemberMethod CreateEndOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod endMethod)
 {
     CodeMemberMethod method = new CodeMemberMethod();
     method.Attributes = MemberAttributes.Private;
     method.ReturnType = new CodeTypeReference(objectArrayType);
     method.Name = NamingHelper.GetUniqueName(GetEndOperationMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations);
     int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), endMethod.Name, new CodeExpression[0]);
     CodeArrayCreateExpression expression2 = new CodeArrayCreateExpression();
     expression2.CreateType = new CodeTypeReference(objectArrayType);
     for (int i = 0; i < endMethod.Parameters.Count; i++)
     {
         if (i == asyncResultParamIndex)
         {
             method.Parameters.Add(new CodeParameterDeclarationExpression(endMethod.Parameters[i].Type, endMethod.Parameters[i].Name));
             expression.Parameters.Add(new CodeVariableReferenceExpression(endMethod.Parameters[i].Name));
         }
         else
         {
             CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement(endMethod.Parameters[i].Type, endMethod.Parameters[i].Name);
             CodeMethodReferenceExpression expression3 = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), getDefaultValueForInitializationMethodName, new CodeTypeReference[] { endMethod.Parameters[i].Type });
             statement.InitExpression = new CodeMethodInvokeExpression(expression3, new CodeExpression[0]);
             method.Statements.Add(statement);
             expression.Parameters.Add(new CodeDirectionExpression(endMethod.Parameters[i].Direction, new CodeVariableReferenceExpression(statement.Name)));
             expression2.Initializers.Add(new CodeVariableReferenceExpression(statement.Name));
         }
     }
     if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
     {
         CodeVariableDeclarationStatement statement2 = new CodeVariableDeclarationStatement();
         statement2.Type = endMethod.ReturnType;
         statement2.Name = NamingHelper.GetUniqueName("retVal", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesParameterNameExist), endMethod);
         statement2.InitExpression = expression;
         expression2.Initializers.Add(new CodeVariableReferenceExpression(statement2.Name));
         method.Statements.Add(statement2);
     }
     else
     {
         method.Statements.Add(expression);
     }
     if (expression2.Initializers.Count > 0)
     {
         method.Statements.Add(new CodeMethodReturnStatement(expression2));
     }
     else
     {
         method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
     }
     clientType.Members.Add(method);
     return method;
 }
Example #36
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            CodeStatementCollection      statements = null;
            PropertyDescriptorCollection props      = TypeDescriptor.GetProperties(value);

            using (TraceScope("ComponentCodeDomSerializer::Serialize"))
            {
                if (manager is null || value is null)
                {
                    throw new ArgumentNullException(manager is null ? "manager" : "value");
                }

                if (IsSerialized(manager, value))
                {
                    Debug.Fail("Serialize is being called twice for the same component");
                    return(GetExpression(manager, value));
                }

                // If the object is being inherited, we will will not emit a variable declaration.  Also, we won't
                // do any serialization at all if the object is privately inherited.
                InheritanceLevel     inheritanceLevel     = InheritanceLevel.NotInherited;
                InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];

                if (inheritanceAttribute != null)
                {
                    inheritanceLevel = inheritanceAttribute.InheritanceLevel;
                }

                // First, skip everything if we're privately inherited.  We cannot write any code that would affect this
                // component.
                TraceIf(inheritanceLevel == InheritanceLevel.InheritedReadOnly, "Skipping read only inherited component");
                if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
                {
                    // Things we need to know:
                    //
                    // 1.  What expression should we use for the left hand side
                    //      a) already given to us via GetExpression?
                    //      b) a local variable?
                    //      c) a member variable?
                    //
                    // 2.  Should we generate an init expression for this
                    //     object?
                    //      a) Inherited or existing expression: no
                    //      b) otherwise, yes.

                    statements = new CodeStatementCollection();
                    CodeTypeDeclaration typeDecl  = manager.Context[typeof(CodeTypeDeclaration)] as CodeTypeDeclaration;
                    RootContext         rootCxt   = manager.Context[typeof(RootContext)] as RootContext;
                    CodeExpression      assignLhs = null;
                    CodeExpression      assignRhs;

                    // Defaults for components
                    bool generateLocal  = false;
                    bool generateField  = true;
                    bool generateObject = true;
                    bool isComplete     = false;

                    assignLhs = GetExpression(manager, value);

                    if (assignLhs != null)
                    {
                        Trace("Existing expression for LHS of value");
                        generateLocal  = false;
                        generateField  = false;
                        generateObject = false;

                        // if we have an existing expression and this is not
                        // a sited component, do not serialize it.  We need this for Everett / 1.0
                        // backwards compat (even though it's wrong).
                        if (value is IComponent comp && comp.Site is null)
                        {
                            // We were in a serialize content
                            // property and would still serialize it.  This code reverses what the
                            // outer if block does for this specific case.  We also need this
                            // for Everett / 1.0 backwards compat.
                            if (!(manager.Context[typeof(ExpressionContext)] is ExpressionContext expCxt) || expCxt.PresetValue != value)
                            {
                                isComplete = true;
                            }
                        }
                    }
                    else
                    {
                        Trace("Creating LHS expression");
                        if (inheritanceLevel == InheritanceLevel.NotInherited)
                        {
                            // See if there is a "GenerateMember" property.  If so,
                            // we might want to generate a local variable.  Otherwise,
                            // we want to generate a field.
                            PropertyDescriptor generateProp = props["GenerateMember"];
                            if (generateProp != null && generateProp.PropertyType == typeof(bool) && !(bool)generateProp.GetValue(value))
                            {
                                Trace("Object GenerateMember property wants a local variable");
                                generateLocal = true;
                                generateField = false;
                            }
                        }
                        else
                        {
                            generateObject = false;
                        }

                        if (rootCxt is null)
                        {
                            generateLocal = true;
                            generateField = false;
                        }
                    }

                    // Push the component being serialized onto the stack.  It may be handy to
                    // be able to discover this.
                    manager.Context.Push(value);
                    manager.Context.Push(statements);

                    try
                    {
                        string name = manager.GetName(value);

                        string typeName = TypeDescriptor.GetClassName(value);

                        // Output variable / field declarations if we need to
                        if ((generateField || generateLocal) && name != null)
                        {
                            if (generateField)
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    // We need to generate the field declaration.  See if there is a modifiers property on
                                    // the object.  If not, look for a DefaultModifies, and finally assume it's private.
                                    CodeMemberField    field        = new CodeMemberField(typeName, name);
                                    PropertyDescriptor modifersProp = props["Modifiers"];
                                    MemberAttributes   fieldAttrs;

                                    if (modifersProp is null)
                                    {
                                        modifersProp = props["DefaultModifiers"];
                                    }

                                    if (modifersProp != null && modifersProp.PropertyType == typeof(MemberAttributes))
                                    {
                                        fieldAttrs = (MemberAttributes)modifersProp.GetValue(value);
                                    }
                                    else
                                    {
                                        TraceWarning("No Modifiers or DefaultModifiers property on component {0}. We must assume private.", name);
                                        fieldAttrs = MemberAttributes.Private;
                                    }

                                    field.Attributes = fieldAttrs;
                                    typeDecl.Members.Add(field);
                                    Trace("Field {0} {1} {2} created.", fieldAttrs, typeName, name);
                                }

                                // Next, create a nice LHS for our pending assign statement, when we hook up the variable.
                                assignLhs = new CodeFieldReferenceExpression(rootCxt.Expression, name);
                            }
                            else
                            {
                                if (inheritanceLevel == InheritanceLevel.NotInherited)
                                {
                                    CodeVariableDeclarationStatement local = new CodeVariableDeclarationStatement(typeName, name);

                                    statements.Add(local);
                                    Trace("Local {0} {1} created.", typeName, name);
                                }

                                assignLhs = new CodeVariableReferenceExpression(name);
                            }
                        }

                        // Now output an object create if we need to.  We always see if there is a
                        // type converter that can provide us guidance

                        if (generateObject)
                        {
                            // Ok, now that we've decided if we have a local or a member variable, its now time to serialize the rest of the code.
                            // The first step is to create an assign statement to "new" the object.  For that, we need to know if
                            // the component wants a special IContainer constructor or not.  For that to be valid we must also know
                            // that we can get to an actual IContainer.
                            IContainer      container = manager.GetService(typeof(IContainer)) as IContainer;
                            ConstructorInfo ctor      = null;
                            if (container != null)
                            {
                                ctor = GetReflectionTypeHelper(manager, value).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, GetContainerConstructor(manager), null);
                            }

                            if (ctor != null)
                            {
                                Trace("Component has IContainer constructor.");
                                assignRhs = new CodeObjectCreateExpression(typeName, new CodeExpression[]
                                {
                                    SerializeToExpression(manager, container)
                                });
                            }
                            else
                            {
                                // For compat reasons we ignore the isCompleteOld value here.
                                assignRhs = SerializeCreationExpression(manager, value, out bool isCompleteOld);
                                Debug.Assert(isCompleteOld == isComplete, "CCDS Differing");
                            }

                            TraceErrorIf(assignRhs is null, "No RHS code assign for object {0}", value);
                            if (assignRhs != null)
                            {
                                if (assignLhs is null)
                                {
                                    // We cannot do much more for this object.  If isComplete is true,
                                    // then the RHS now becomes our LHS.  Otherwise, I'm afraid we have
                                    // just failed to serialize this object.
                                    if (isComplete)
                                    {
                                        assignLhs = assignRhs;
                                    }
                                    else
                                    {
                                        TraceError("Incomplete serialization of object, abandoning serialization.");
                                    }
                                }
                                else
                                {
                                    CodeAssignStatement assign = new CodeAssignStatement(assignLhs, assignRhs);
                                    statements.Add(assign);
                                }
                            }
                        }

                        if (assignLhs != null)
                        {
                            SetExpression(manager, value, assignLhs);
                        }

                        // It should practically be an assert that isComplete is false, but someone may
                        // have an unusual component.
                        if (assignLhs != null && !isComplete)
                        {
                            // .NET CF needs us to verify that the ISupportInitialize interface exists
                            // (they do not support this interface and will modify their DSM to resolve the type to null).

                            bool supportInitialize = (value is ISupportInitialize);
                            if (supportInitialize)
                            {
                                string fullName = typeof(ISupportInitialize).FullName;
                                supportInitialize = manager.GetType(fullName) != null;
                            }
                            Type reflectionType = null;
                            if (supportInitialize)
                            {
                                // Now verify that this control implements ISupportInitialize in the project target framework
                                // Don't use operator "is" but rather use IsAssignableFrom on the reflection types.
                                // We have other places where we use operator "is", for example "is IComponent" to generate
                                // specific CodeDOM objects, however we don't have cases of objects which were not an IComponent
                                // in a downlevel framework and became an IComponent in a newer framework, so I'm not replacing
                                // all instances of operator "is" by IsAssignableFrom.
                                reflectionType    = GetReflectionTypeHelper(manager, value);
                                supportInitialize = GetReflectionTypeFromTypeHelper(manager, typeof(ISupportInitialize)).IsAssignableFrom(reflectionType);
                            }

                            bool persistSettings = (value is IPersistComponentSettings) && ((IPersistComponentSettings)value).SaveSettings;
                            if (persistSettings)
                            {
                                string fullName = typeof(IPersistComponentSettings).FullName;
                                persistSettings = manager.GetType(fullName) != null;
                            }
                            if (persistSettings)
                            {
                                reflectionType  = reflectionType ?? GetReflectionTypeHelper(manager, value);
                                persistSettings = GetReflectionTypeFromTypeHelper(manager, typeof(IPersistComponentSettings)).IsAssignableFrom(reflectionType);
                            }
                            // We implement statement caching only for the main code generation phase.  We don't implement it for other
                            // serialization managers.  How do we tell the difference?  The main serialization manager exists as a service.
                            IDesignerSerializationManager mainManager = manager.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;

                            if (supportInitialize)
                            {
                                Trace("Object implements ISupportInitialize.");
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "BeginInit");
                            }

                            SerializePropertiesToResources(manager, statements, value, _designTimeFilter);

                            // Writing out properties is expensive.  But, we're very smart and we cache the results
                            // in ComponentCache.  See if we have cached results.  If so, use 'em.  If not, generate
                            // code and then see if we can cache the results for later.
                            ComponentCache       cache = manager.GetService(typeof(ComponentCache)) as ComponentCache;
                            ComponentCache.Entry entry = null;
                            if (cache is null)
                            {
                                if (manager.GetService(typeof(IServiceContainer)) is ServiceContainer sc)
                                {
                                    cache = new ComponentCache(manager);
                                    sc.AddService(typeof(ComponentCache), cache);
                                }
                            }
                            else
                            {
                                if (manager == mainManager && cache.Enabled)
                                {
                                    entry = cache[value];
                                }
                            }

                            if (entry is null || entry.Tracking)
                            {
                                // Pushing the entry here allows it to be found by the resource code dom serializer,
                                // which will add data to the ResourceBlob property on the entry.
                                if (entry is null)
                                {
                                    entry = new ComponentCache.Entry(cache);

                                    // We cache components even if they're not valid so dependencies are
                                    // still tracked correctly (see comment below).  The problem is, we will create a
                                    // new entry object even if there is still an existing one that is just invalid, and it
                                    // might have dependencies that will be lost.
                                    // we need to make sure we copy over any dependencies that are also tracked.
                                    ComponentCache.Entry oldEntry = cache?.GetEntryAll(value);
                                    if (oldEntry != null && oldEntry.Dependencies != null && oldEntry.Dependencies.Count > 0)
                                    {
                                        foreach (object dependency in oldEntry.Dependencies)
                                        {
                                            entry.AddDependency(dependency);
                                        }
                                    }
                                }
                                entry.Component = value;
                                // we need to link the cached entry with its corresponding component right away, before it's put in the context
                                // see CodeDomSerializerBase.cs::GetExpression for usage

                                // This entry will only be used if the valid bit is set.
                                // This is useful because we still need to setup depedency relationships
                                // between components even if they are not cached.  See VSWhidbey 263053.
                                bool correctManager = manager == mainManager;
                                entry.Valid = correctManager && CanCacheComponent(manager, value, props);

                                if (correctManager && cache != null && cache.Enabled)
                                {
                                    manager.Context.Push(cache);
                                    manager.Context.Push(entry);
                                }

                                try
                                {
                                    entry.Statements = new CodeStatementCollection();
                                    SerializeProperties(manager, entry.Statements, value, _runTimeFilter);
                                    SerializeEvents(manager, entry.Statements, value, null);

                                    foreach (CodeStatement statement in entry.Statements)
                                    {
                                        if (statement is CodeVariableDeclarationStatement local)
                                        {
                                            entry.Tracking = true;
                                            break;
                                        }
                                    }

                                    if (entry.Statements.Count > 0)
                                    {
                                        // if we added some statements, insert the comments
                                        //
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));
                                        entry.Statements.Insert(0, new CodeCommentStatement(name));
                                        entry.Statements.Insert(0, new CodeCommentStatement(string.Empty));

                                        //
                                        // cache the statements for future usage if possible. We only do this for the main serialization manager, not
                                        // for any other seriallization managers that may be calling us for undo or clipboard functions.
                                        if (correctManager && cache != null && cache.Enabled)
                                        {
                                            cache[value] = entry;
                                        }
                                    }
                                }
                                finally
                                {
                                    if (correctManager && cache != null && cache.Enabled)
                                    {
                                        Debug.Assert(manager.Context.Current == entry, "Context stack corrupted");
                                        manager.Context.Pop();
                                        manager.Context.Pop();
                                    }
                                }
                            }
                            else
                            {
                                // If we got a cache entry, we will need to take all the resources out of
                                // it and apply them too.
                                if ((entry.Resources != null || entry.Metadata != null) && cache != null && cache.Enabled)
                                {
                                    ResourceCodeDomSerializer res = ResourceCodeDomSerializer.Default;
                                    res.ApplyCacheEntry(manager, entry);
                                }
                            }

                            // Regarless, apply statements.  Either we created them or we got them
                            // out of the cache.
                            statements.AddRange(entry.Statements);

                            if (persistSettings)
                            {
                                SerializeLoadComponentSettings(manager, statements, assignLhs, value);
                            }

                            if (supportInitialize)
                            {
                                SerializeSupportInitialize(manager, statements, assignLhs, value, "EndInit");
                            }
                        }
                    }
 private static CodeMemberMethod CreateBeginOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod beginMethod)
 {
     CodeMemberMethod method = new CodeMemberMethod();
     method.Attributes = MemberAttributes.Private;
     method.ReturnType = new CodeTypeReference(asyncResultType);
     method.Name = NamingHelper.GetUniqueName(GetBeginOperationMethodName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations);
     CodeParameterDeclarationExpression expression = new CodeParameterDeclarationExpression();
     expression.Type = new CodeTypeReference(objectArrayType);
     expression.Name = NamingHelper.GetUniqueName("inValues", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesParameterNameExist), beginMethod);
     method.Parameters.Add(expression);
     CodeMethodInvokeExpression expression2 = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), beginMethod.Name, new CodeExpression[0]);
     CodeExpression targetObject = new CodeVariableReferenceExpression(expression.Name);
     for (int i = 0; i < (beginMethod.Parameters.Count - 2); i++)
     {
         CodeVariableDeclarationStatement statement = new CodeVariableDeclarationStatement();
         statement.Type = beginMethod.Parameters[i].Type;
         statement.Name = beginMethod.Parameters[i].Name;
         statement.InitExpression = new CodeCastExpression(statement.Type, new CodeArrayIndexerExpression(targetObject, new CodeExpression[] { new CodePrimitiveExpression(i) }));
         method.Statements.Add(statement);
         expression2.Parameters.Add(new CodeDirectionExpression(beginMethod.Parameters[i].Direction, new CodeVariableReferenceExpression(statement.Name)));
     }
     for (int j = beginMethod.Parameters.Count - 2; j < beginMethod.Parameters.Count; j++)
     {
         method.Parameters.Add(new CodeParameterDeclarationExpression(beginMethod.Parameters[j].Type, beginMethod.Parameters[j].Name));
         expression2.Parameters.Add(new CodeVariableReferenceExpression(beginMethod.Parameters[j].Name));
     }
     method.Statements.Add(new CodeMethodReturnStatement(expression2));
     clientType.Members.Add(method);
     return method;
 }
        public static CodeStatement CreateToSourceAssignmentMethod(
            TranslateAttribute attr,
            CodeVariableDeclarationStatement toSource,
            PropertyInfo toSourceProperty, CodeParameterDeclarationExpression fromTargetParam,
            Func <Type, Type, TranslateAttribute> getTypesTranslateAttributeFn)
        {
            var fromTargetProperty = attr.TargetType.GetProperty(toSourceProperty.Name);
            var cantReadFromTarget = fromTargetProperty.GetGetMethod() == null;

            if (cantReadFromTarget)
            {
                return(new CodeCommentStatement(string.Format("Skipping property 'to.{0}' because 'model.{1}' is write-only",
                                                              toSourceProperty.Name, fromTargetProperty.Name)));
            }
            var cantWriteToSource = toSourceProperty.GetSetMethod() == null;

            if (cantWriteToSource)
            {
                return(new CodeCommentStatement(string.Format("Skipping property 'to.{0}' because 'to.{1}' is read-only",
                                                              toSourceProperty.Name, toSourceProperty.Name)));
            }

            //to[property.Name] = this[property.Name] e.g:
            //	to.Name = from.Name;
            if (fromTargetProperty.PropertyType.IsAssignableFrom(toSourceProperty.PropertyType))
            {
                return(toSource.Assign(
                           toSource.RefProperty(toSourceProperty.Name),
                           fromTargetParam.Name.RefArgument().RefProperty(toSourceProperty.Name)));
            }

            //to[property.Name] = from[property.PropertyType.Name].ToTarget() e.g:
            //to.Address = from.Address.ToTarget();

            var toSourcePropertyType     = toSourceProperty.PropertyType;
            var fromTargetPropertyType   = fromTargetProperty.PropertyType;
            var targetAttr               = getTypesTranslateAttributeFn(toSourcePropertyType, fromTargetPropertyType);
            var useExtensionMethods      = attr is TranslateExtensionAttribute;
            var isTargetTranslatableAlso = targetAttr != null;

            if (isTargetTranslatableAlso)
            {
                var toSourceMethodName = targetAttr.GetConvertToSourceMethodName();
                var method             = useExtensionMethods
                                                                        ? fromTargetParam.RefProperty(toSourceProperty.Name).Call(toSourceMethodName)
                                                                        : toSourcePropertyType.Call(toSourceMethodName, fromTargetParam.RefProperty(toSourceProperty.Name));
                return(toSource.Assign(toSourceProperty.Name, method));
            }

            var fromSourceIsGenericList = toSourcePropertyType.IsGenericType && toSourcePropertyType.GetGenericTypeDefinition() == typeof(List <>);
            var toTargetIsGenericList   = fromTargetPropertyType.IsGenericType && fromTargetPropertyType.GetGenericTypeDefinition() == typeof(List <>);
            var bothAreGenericLists     = fromSourceIsGenericList && toTargetIsGenericList;

            if (bothAreGenericLists)
            {
                //to.PhoneNumbers = from.PhoneNumbers.ToPhoneNumbers();
                var propertyListItemTypeAttr = getTypesTranslateAttributeFn(toSourcePropertyType.GetGenericArguments()[0], fromTargetPropertyType.GetGenericArguments()[0]);
                var sourceIsTranslatable     = propertyListItemTypeAttr != null;
                if (sourceIsTranslatable)
                {
                    var toSourcesMethodName = propertyListItemTypeAttr.GetConvertToSourcesMethodName();
                    var method = useExtensionMethods
                                                                ? fromTargetParam.RefProperty(fromTargetProperty.Name).Call(toSourcesMethodName)
                                                                : propertyListItemTypeAttr.SourceType.Call(toSourcesMethodName, fromTargetParam.RefProperty(fromTargetProperty.Name));

                    return(toSource.RefProperty(toSourceProperty.Name).Assign(method));
                }
            }

            //to[property.Name] = this[property.Name].ToString() e.g:
            //	to.Name = from.Name;
            if (toSourceProperty.PropertyType == typeof(string) &&
                StringConverterUtils.CanCreateFromString(fromTargetProperty.PropertyType))
            {
                var fromTargetPropertyRef = fromTargetParam.Name.RefArgument().RefProperty(toSourceProperty.Name);
                return(fromTargetPropertyRef.IfIsNotNull(
                           toSource.Assign(
                               toSource.RefProperty(toSourceProperty.Name),
                               fromTargetPropertyRef.Call("ToString"))));
            }

            // Converting 'System.Collections.Generic.List`1 PhoneNumbers' to 'System.Collections.Generic.List`1 PhoneNumbers' is unsupported
            return(new CodeCommentStatement(string.Format("Converting '{0}.{1} {2}' to '{3}.{4} {5}' is unsupported"
                                                          , toSourceProperty.PropertyType.Namespace, toSourceProperty.PropertyType.Name, toSourceProperty.Name
                                                          , fromTargetProperty.PropertyType.Namespace, fromTargetProperty.PropertyType.Name, fromTargetProperty.Name)));
        }
        public void ValueTypes()
        {
            // create a namespace
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

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

            // create first struct to test nested structs
            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);
            class1.Members.Add(structA);

            // create second struct to test tructs of non-primative types
            CodeTypeDeclaration structC = new CodeTypeDeclaration("structC");
            structC.IsStruct = true;

            CodeMemberField firstPt = new CodeMemberField("Point", "pt1");
            firstPt.Attributes = MemberAttributes.Public;
            structC.Members.Add(firstPt);

            CodeMemberField secondPt = new CodeMemberField("Point", "pt2");
            secondPt.Attributes = MemberAttributes.Public;
            structC.Members.Add(secondPt);
            class1.Members.Add(structC);

            // create method to test nested struct
            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")));
            class1.Members.Add(nestedStructMethod);

            // create method to test nested non primative struct member
            CodeMemberMethod nonPrimativeStructMethod = new CodeMemberMethod();
            nonPrimativeStructMethod.Name = "NonPrimativeStructMethod";
            nonPrimativeStructMethod.ReturnType = new CodeTypeReference(typeof(DateTime));
            nonPrimativeStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeVariableDeclarationStatement varStructC = new CodeVariableDeclarationStatement("structC", "varStructC");
            nonPrimativeStructMethod.Statements.Add(varStructC);
            nonPrimativeStructMethod.Statements.Add
                (
                new CodeAssignStatement
                (
                /* Expression1 */ new CodeFieldReferenceExpression(
                new CodeVariableReferenceExpression("varStructC"),
                "pt1"),
                /* Expression2 */ new CodeObjectCreateExpression("DateTime", new CodeExpression[] { new CodePrimitiveExpression(1), new CodePrimitiveExpression(-1) })
                )
                );
            nonPrimativeStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructC"), "pt1")));
            class1.Members.Add(nonPrimativeStructMethod);

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

                      public class Test {
                          public static int NestedStructMethod() {
                              structA varStructA;
                              varStructA.innerStruct.int1 = 3;
                              return varStructA.innerStruct.int1;
                          }

                          public static System.DateTime NonPrimativeStructMethod() {
                              structC varStructC;
                              varStructC.pt1 = new DateTime(1, -1);
                              return varStructC.pt1;
                          }

                          public struct structA {

                              public structB innerStruct;

                              public struct structB {

                                  public int int1;
                              }
                          }

                          public struct structC {

                              public Point pt1;

                              public Point pt2;
                          }
                      }
                  }");
        }
Example #40
0
 protected abstract void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e);
        public void BinaryOperators()
        {
            CodeNamespace ns = new CodeNamespace("Namespace1");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Class1";
            class1.BaseTypes.Add(new CodeTypeReference(typeof(object)));
            ns.Types.Add(class1);

            CodeMemberMethod retMethod = new CodeMemberMethod();
            retMethod.Name = "ReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(18),
                CodeBinaryOperatorType.Divide,
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(6),
                CodeBinaryOperatorType.Subtract,
                new CodePrimitiveExpression(4))),
                CodeBinaryOperatorType.Multiply,
                new CodeArgumentReferenceExpression("intInput"));

            CodeVariableDeclarationStatement variableDeclaration = null;
            variableDeclaration = new CodeVariableDeclarationStatement(typeof(int), "x1", cboExpression);

            retMethod.Statements.Add(variableDeclaration);
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x2",
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(19),
                CodeBinaryOperatorType.Modulus,
                new CodePrimitiveExpression(8))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x3",
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(15),
                CodeBinaryOperatorType.BitwiseAnd,
                new CodePrimitiveExpression(35)),
                CodeBinaryOperatorType.BitwiseOr,
                new CodePrimitiveExpression(129))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x4",
                new CodePrimitiveExpression(0)));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanOr,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.LessThan,
                new CodePrimitiveExpression(129))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 1) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 2) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.GreaterThan,
                new CodePrimitiveExpression(-1)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.GreaterThanOrEqual,
                new CodePrimitiveExpression(5000))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 4) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 8) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.LessThanOrEqual,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.IdentityInequality,
                new CodePrimitiveExpression(1))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 16) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 32) }));
            retMethod.Statements.Add(
                new CodeMethodReturnStatement(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x1"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.Add,
                new CodeVariableReferenceExpression("x4"))))));
            class1.Members.Add(retMethod);

            retMethod = new CodeMemberMethod();
            retMethod.Name = "SecondReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            retMethod.Statements.Add(new CodeCommentStatement("To test CodeBinaryOperatorType.IdentiEquality operator"));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(new CodeCastExpression("Object",
                new CodeVariableReferenceExpression("intInput")),
                CodeBinaryOperatorType.IdentityEquality, new CodeCastExpression("Object",
                new CodePrimitiveExpression(5))),
                new CodeStatement[] { new CodeMethodReturnStatement(new
                CodePrimitiveExpression(5)) }, new CodeStatement[] { new
                CodeMethodReturnStatement(new CodePrimitiveExpression(4))}));
            class1.Members.Add(retMethod);

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

                      public class Class1 : object {
                          public int ReturnMethod(int intInput) {
                              int x1 = ((18 / (6 - 4)) * intInput);
                              int x2 = (19 % 8);
                              int x3 = ((15 & 35) | 129);
                              int x4 = 0;
                              if (((x2 == 3) || (x3 < 129))) {
                                  x4 = (x4 + 1);
                              }
                              else {
                                  x4 = (x4 + 2);
                              }
                              if (((x2 > -1) && (x3 >= 5000))) {
                                  x4 = (x4 + 4);
                              }
                              else {
                                  x4 = (x4 + 8);
                              }
                              if (((x2 <= 3) && (x3 != 1))) {
                                  x4 = (x4 + 16);
                              }
                              else {
                                  x4 = (x4 + 32);
                              }
                              return (x1 + (x2 + (x3 + x4)));
                          }

                          public int SecondReturnMethod(int intInput) {
                              // To test CodeBinaryOperatorType.IdentiEquality operator
                              if ((((Object)(intInput)) == ((Object)(5)))) {
                                  return 5;
                              }
                              else {
                                  return 4;
                              }
                          }
                      }
                  }");
        }
Example #42
0
        void AddAsyncMembers(string messageName, CodeMemberMethod method)
        {
            CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
            CodePrimitiveExpression     enull = new CodePrimitiveExpression(null);

            CodeMemberField codeField = new CodeMemberField(typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted");

            codeField.Attributes = MemberAttributes.Private;
            CodeTypeDeclaration.Members.Add(codeField);

            // Event arguments class

            string argsClassName          = classNames.AddUnique(messageName + "CompletedEventArgs", null);
            CodeTypeDeclaration argsClass = new CodeTypeDeclaration(argsClassName);

            argsClass.Attributes |= MemberAttributes.Public;
#if NET_2_0
            argsClass.IsPartial = true;
#endif
            argsClass.BaseTypes.Add(new CodeTypeReference("System.ComponentModel.AsyncCompletedEventArgs"));

            CodeMemberField resultsField = new CodeMemberField(typeof(object[]), "results");
            resultsField.Attributes = MemberAttributes.Private;
            argsClass.Members.Add(resultsField);

            CodeConstructor cc = new CodeConstructor();
            cc.Attributes = MemberAttributes.Assembly;
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "results"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Exception), "exception"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("exception"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("cancelled"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("userState"));
            CodeExpression thisResults = new CodeFieldReferenceExpression(ethis, "results");
            cc.Statements.Add(new CodeAssignStatement(thisResults, new CodeVariableReferenceExpression("results")));
            argsClass.Members.Add(cc);

            int ind = 0;

            if (method.ReturnType.BaseType != "System.Void")
            {
                argsClass.Members.Add(CreateArgsProperty(method.ReturnType, "Result", ind++));
            }

            foreach (CodeParameterDeclarationExpression par in method.Parameters)
            {
                if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref)
                {
                    argsClass.Members.Add(CreateArgsProperty(par.Type, par.Name, ind++));
                }
            }

            bool needsArgsClass = (ind > 0);
            if (needsArgsClass)
            {
                asyncTypes.Add(argsClass);
            }
            else
            {
                argsClassName = "System.ComponentModel.AsyncCompletedEventArgs";
            }

            // Event delegate type

            CodeTypeDelegate delegateType = new CodeTypeDelegate(messageName + "CompletedEventHandler");
            delegateType.Attributes |= MemberAttributes.Public;
            delegateType.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            delegateType.Parameters.Add(new CodeParameterDeclarationExpression(argsClassName, "args"));

            // Event member

            CodeMemberEvent codeEvent = new CodeMemberEvent();
            codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public;
            codeEvent.Name       = messageName + "Completed";
            codeEvent.Type       = new CodeTypeReference(delegateType.Name);
            CodeTypeDeclaration.Members.Add(codeEvent);

            // Async method (without user state param)

            CodeMemberMethod am = new CodeMemberMethod();
            am.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            am.Name       = method.Name + "Async";
            am.ReturnType = new CodeTypeReference(typeof(void));
            CodeMethodInvokeExpression inv;
            inv = new CodeMethodInvokeExpression(ethis, am.Name);
            am.Statements.Add(inv);

            // On...Completed method

            CodeMemberMethod onCompleted = new CodeMemberMethod();
            onCompleted.Name       = "On" + messageName + "Completed";
            onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            onCompleted.ReturnType = new CodeTypeReference(typeof(void));
            onCompleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "arg"));

            CodeConditionStatement anIf = new CodeConditionStatement();

            CodeExpression eventField = new CodeEventReferenceExpression(ethis, codeEvent.Name);
            anIf.Condition = new CodeBinaryOperatorExpression(eventField, CodeBinaryOperatorType.IdentityInequality, enull);
            CodeExpression castedArg  = new CodeCastExpression(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression("arg"));
            CodeStatement  invokeArgs = new CodeVariableDeclarationStatement(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg);
            anIf.TrueStatements.Add(invokeArgs);

            CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression();
            delegateInvoke.TargetObject = eventField;
            delegateInvoke.Parameters.Add(ethis);
            CodeObjectCreateExpression argsInstance  = new CodeObjectCreateExpression(argsClassName);
            CodeExpression             invokeArgsVar = new CodeVariableReferenceExpression("invokeArgs");
            if (needsArgsClass)
            {
                argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Results"));
            }
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Error"));
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Cancelled"));
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "UserState"));
            delegateInvoke.Parameters.Add(argsInstance);
            anIf.TrueStatements.Add(delegateInvoke);

            onCompleted.Statements.Add(anIf);

            // Async method

            CodeMemberMethod asyncMethod = new CodeMemberMethod();
            asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            asyncMethod.Name       = method.Name + "Async";
            asyncMethod.ReturnType = new CodeTypeReference(typeof(void));

            CodeExpression delegateField = new CodeFieldReferenceExpression(ethis, codeField.Name);
            anIf           = new CodeConditionStatement();
            anIf.Condition = new CodeBinaryOperatorExpression(delegateField, CodeBinaryOperatorType.IdentityEquality, enull);;
            CodeExpression      delegateRef = new CodeMethodReferenceExpression(ethis, onCompleted.Name);
            CodeExpression      newDelegate = new CodeObjectCreateExpression(typeof(System.Threading.SendOrPostCallback), delegateRef);
            CodeAssignStatement cas         = new CodeAssignStatement(delegateField, newDelegate);
            anIf.TrueStatements.Add(cas);
            asyncMethod.Statements.Add(anIf);

            CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression(typeof(object));

            // Assign parameters

            CodeIdentifiers paramsIds = new CodeIdentifiers();

            foreach (CodeParameterDeclarationExpression par in method.Parameters)
            {
                paramsIds.Add(par.Name, null);
                if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref)
                {
                    CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression(par.Type, par.Name);
                    am.Parameters.Add(inpar);
                    asyncMethod.Parameters.Add(inpar);
                    inv.Parameters.Add(new CodeVariableReferenceExpression(par.Name));
                    paramsArray.Initializers.Add(new CodeVariableReferenceExpression(par.Name));
                }
            }


            inv.Parameters.Add(enull);

            string userStateName = paramsIds.AddUnique("userState", null);
            asyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userStateName));

            CodeExpression userStateVar = new CodeVariableReferenceExpression(userStateName);
            asyncMethod.Statements.Add(BuildInvokeAsync(messageName, paramsArray, delegateField, userStateVar));

            CodeTypeDeclaration.Members.Add(am);
            CodeTypeDeclaration.Members.Add(asyncMethod);
            CodeTypeDeclaration.Members.Add(onCompleted);

            asyncTypes.Add(delegateType);
        }
	protected override void GenerateVariableDeclarationStatement
				(CodeVariableDeclarationStatement e)
			{
				OutputTypeNamePair(e.Type, e.Name);
				if(e.InitExpression != null)
				{
					Output.Write(" = ");
					GenerateExpression(e.InitExpression);
				}
				if(!outputForInit)
				{
					Output.WriteLine(";");
				}
			}
 protected override void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
 {
     Output.WriteLine("[CodeVariableDeclarationStatement: {0}]", e.ToString());
 }
 void CreateTestFile(String[] values)
   {
   StreamWriter sw = new StreamWriter("test.cs");
   CSharpCodeProvider cdp = new CSharpCodeProvider();
   ICodeGenerator cg = cdp.CreateGenerator();
   CodeNamespace cnspace = new CodeNamespace("N");
   cnspace.Imports.Add(new CodeNamespaceImport("System"));
   CodeTypeDeclaration co = new CodeTypeDeclaration ("C");
   co.IsClass = true;
   cnspace.Types.Add (co);
   co.TypeAttributes  = TypeAttributes.Public;
   CodeMemberMethod cmm = new CodeMemberMethod();
   cmm.Name = "Main";
   cmm.ReturnType = null;
   cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
   CodeVariableDeclarationStatement cvar = new CodeVariableDeclarationStatement(typeof(String[]), "args", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Environment"), "GetCommandLineArgs"));
   cmm.Statements.Add(cvar);  
   cvar = new CodeVariableDeclarationStatement(typeof(Int32), "exitCode", new CodeSnippetExpression("0"));
   cmm.Statements.Add(cvar);
   String strArgLength = (values.Length + 1).ToString();
   CodeConditionStatement ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args.Length"), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression(strArgLength)), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   ccs1 = new CodeConditionStatement(new CodeSnippetExpression("!args[0].ToLower().EndsWith(\"test.exe\")"), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   for(int i=0; i<values.Length; i++){
   ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args[" + (i+1).ToString() + "]"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(values[i])), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   }
   cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("Environment.ExitCode"), new CodeVariableReferenceExpression("exitCode")));
   co.Members.Add(cmm);
   cg.GenerateCodeFromNamespace(cnspace, sw, null);
   sw.Flush();
   sw.Close();		
   }
Example #46
0
 private void ValidateVariableDeclarationStatement(CodeVariableDeclarationStatement e)
 {
     ValidateTypeReference(e.Type);
     ValidateIdentifier(e, nameof(e.Name), e.Name);
     if (e.InitExpression != null)
     {
         ValidateExpression(e.InitExpression);
     }
 }
        public void ValueTypes()
        {
            // create a namespace
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

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

            // create first struct to test nested structs
            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);
            class1.Members.Add(structA);

            // create second struct to test tructs of non-primative types
            CodeTypeDeclaration structC = new CodeTypeDeclaration("structC");
            structC.IsStruct = true;

            CodeMemberField firstPt = new CodeMemberField("Point", "pt1");
            firstPt.Attributes = MemberAttributes.Public;
            structC.Members.Add(firstPt);

            CodeMemberField secondPt = new CodeMemberField("Point", "pt2");
            secondPt.Attributes = MemberAttributes.Public;
            structC.Members.Add(secondPt);
            class1.Members.Add(structC);

            // create method to test nested struct
            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")));
            class1.Members.Add(nestedStructMethod);

            // create method to test nested non primative struct member
            CodeMemberMethod nonPrimativeStructMethod = new CodeMemberMethod();
            nonPrimativeStructMethod.Name = "NonPrimativeStructMethod";
            nonPrimativeStructMethod.ReturnType = new CodeTypeReference(typeof(DateTime));
            nonPrimativeStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeVariableDeclarationStatement varStructC = new CodeVariableDeclarationStatement("structC", "varStructC");
            nonPrimativeStructMethod.Statements.Add(varStructC);
            nonPrimativeStructMethod.Statements.Add
                (
                new CodeAssignStatement
                (
                /* Expression1 */ new CodeFieldReferenceExpression(
                new CodeVariableReferenceExpression("varStructC"),
                "pt1"),
                /* Expression2 */ new CodeObjectCreateExpression("DateTime", new CodeExpression[] { new CodePrimitiveExpression(1), new CodePrimitiveExpression(-1) })
                )
                );
            nonPrimativeStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructC"), "pt1")));
            class1.Members.Add(nonPrimativeStructMethod);

            AssertEqual(ns,
                @"Imports System
                  Namespace NS
                      Public Class Test
                          Public Shared Function NestedStructMethod() As Integer
                              Dim varStructA As structA
                              varStructA.innerStruct.int1 = 3
                              Return varStructA.innerStruct.int1
                          End Function
                          Public Shared Function NonPrimativeStructMethod() As Date
                              Dim varStructC As structC
                              varStructC.pt1 = New DateTime(1, -1)
                              Return varStructC.pt1
                          End Function
                          Public Structure structA
                              Public innerStruct As structB
                              Public Structure structB
                                  Public int1 As Integer
                              End Structure
                          End Structure
                          Public Structure structC
                              Public pt1 As Point
                              Public pt2 As Point
                          End Structure
                      End Class
                  End Namespace");
        }
        protected virtual void GenerateProperties(CodeTypeDeclaration targetClass, Type baseType, IEnumerable <PropertyInfo> properties)
        {
            var interceptorProperty = new CodeMemberProperty();

            interceptorProperty.Name        = "Interceptor";
            interceptorProperty.Type        = interceptorTypeReference;
            interceptorProperty.Attributes |= MemberAttributes.Private;
            interceptorProperty.PrivateImplementationType = proxyTypeReference;
            interceptorProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "interceptor")));
            targetClass.Members.Add(interceptorProperty);

            foreach (var property in properties)
            {
                var p = new CodeMemberProperty();
                p.Name = property.Name;
                p.Type = new CodeTypeReference(property.PropertyType);

                if (baseType != interfaceProxyType)
                {
                    p.Attributes = MemberAttributes.Override;
                }

                targetClass.Members.Add(p);

                if (property.CanRead == true)
                {
                    p.HasGet = true;

                    if ((property.GetMethod.Attributes & MethodAttributes.Public) == MethodAttributes.Public)
                    {
                        p.Attributes |= MemberAttributes.Public;
                    }
                    else if ((property.GetMethod.Attributes & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem)
                    {
                        p.Attributes |= MemberAttributes.FamilyOrAssembly;
                    }
                    else if ((property.GetMethod.Attributes & MethodAttributes.Family) == MethodAttributes.Family)
                    {
                        p.Attributes |= MemberAttributes.Family;
                    }
                    else if ((property.GetMethod.Attributes & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem)
                    {
                        p.Attributes |= MemberAttributes.FamilyAndAssembly;
                    }

                    if (baseType == interfaceProxyType)
                    {
                        p.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    }

                    var currentMethod  = new CodeVariableDeclarationStatement(typeof(MethodInfo), "currentMethod", new CodeCastExpression(typeof(MethodInfo), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(MethodBase)), "GetCurrentMethod"))));
                    var getType        = new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance"), "GetType");
                    var getMethod      = new CodeMethodInvokeExpression(getType, "GetMethod", new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentMethod"), "Name"));
                    var originalMethod = new CodeVariableDeclarationStatement(typeof(MethodInfo), "originalMethod", getMethod);

                    p.GetStatements.Add(currentMethod);
                    p.GetStatements.Add(originalMethod);

                    var ps  = new CodeExpression[] { new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance"), new CodeVariableReferenceExpression("originalMethod") };
                    var arg = new CodeVariableDeclarationStatement(typeof(InterceptionArgs), "args", new CodeObjectCreateExpression(typeof(InterceptionArgs), ps));

                    p.GetStatements.Add(arg);

                    var handler = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "handler"), "Invoke"), new CodeVariableReferenceExpression("args"));
                    p.GetStatements.Add(handler);

                    var comparison = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Handled"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true));
                    var @if        = new CodeConditionStatement(comparison, new CodeMethodReturnStatement(new CodeCastExpression(property.PropertyType, new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Result"))));

                    p.GetStatements.Add(@if);

                    if (baseType != interfaceProxyType)
                    {
                        p.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), property.Name)));
                    }
                    else
                    {
                        p.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeCastExpression(property.DeclaringType, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance")), property.Name)));
                    }
                }

                if (property.CanWrite == true)
                {
                    p.HasSet = true;

                    var ps = new CodeExpression[]
                    {
                        new CodeThisReferenceExpression(),
                        new CodeCastExpression(typeof(MethodInfo), new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(MethodBase)), "GetCurrentMethod"))),
                        new CodeVariableReferenceExpression("value")
                    };

                    var arg = new CodeVariableDeclarationStatement(typeof(InterceptionArgs), "args", new CodeObjectCreateExpression(typeof(InterceptionArgs), ps));

                    p.SetStatements.Add(arg);

                    var handler = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "handler"), "Invoke"), new CodeVariableReferenceExpression("args"));
                    p.SetStatements.Add(handler);

                    var comparison = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("args"), "Handled"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true));
                    var @if        = new CodeConditionStatement(comparison, new CodeMethodReturnStatement());

                    p.SetStatements.Add(@if);

                    if (baseType != interfaceProxyType)
                    {
                        p.SetStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), property.Name), new CodeVariableReferenceExpression("value")));
                    }
                    else
                    {
                        p.SetStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeCastExpression(property.DeclaringType, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "instance")), property.Name), new CodeVariableReferenceExpression("value")));
                    }
                }
            }
        }
        public void BinaryOperators()
        {
            CodeNamespace ns = new CodeNamespace("Namespace1");
            ns.Imports.Add(new CodeNamespaceImport("System"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "Class1";
            class1.BaseTypes.Add(new CodeTypeReference(typeof(object)));
            ns.Types.Add(class1);

            CodeMemberMethod retMethod = new CodeMemberMethod();
            retMethod.Name = "ReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(18),
                CodeBinaryOperatorType.Divide,
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(6),
                CodeBinaryOperatorType.Subtract,
                new CodePrimitiveExpression(4))),
                CodeBinaryOperatorType.Multiply,
                new CodeArgumentReferenceExpression("intInput"));

            CodeVariableDeclarationStatement variableDeclaration = null;
            variableDeclaration = new CodeVariableDeclarationStatement(typeof(int), "x1", cboExpression);

            retMethod.Statements.Add(variableDeclaration);
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x2",
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(19),
                CodeBinaryOperatorType.Modulus,
                new CodePrimitiveExpression(8))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x3",
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodePrimitiveExpression(15),
                CodeBinaryOperatorType.BitwiseAnd,
                new CodePrimitiveExpression(35)),
                CodeBinaryOperatorType.BitwiseOr,
                new CodePrimitiveExpression(129))));
            retMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                typeof(int),
                "x4",
                new CodePrimitiveExpression(0)));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanOr,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.LessThan,
                new CodePrimitiveExpression(129))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 1) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 2) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.GreaterThan,
                new CodePrimitiveExpression(-1)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.GreaterThanOrEqual,
                new CodePrimitiveExpression(5000))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 4) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 8) }));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.LessThanOrEqual,
                new CodePrimitiveExpression(3)),
                CodeBinaryOperatorType.BooleanAnd,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.IdentityInequality,
                new CodePrimitiveExpression(1))),
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 16) },
                new CodeStatement[] { CreateVariableIncrementExpression("x4", 32) }));
            retMethod.Statements.Add(
                new CodeMethodReturnStatement(
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x1"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x2"),
                CodeBinaryOperatorType.Add,
                new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression("x3"),
                CodeBinaryOperatorType.Add,
                new CodeVariableReferenceExpression("x4"))))));
            class1.Members.Add(retMethod);

            retMethod = new CodeMemberMethod();
            retMethod.Name = "SecondReturnMethod";
            retMethod.Attributes = (retMethod.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            retMethod.ReturnType = new CodeTypeReference(typeof(int));
            retMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "intInput"));

            retMethod.Statements.Add(new CodeCommentStatement("To test CodeBinaryOperatorType.IdentiEquality operator"));
            retMethod.Statements.Add(
                new CodeConditionStatement(
                new CodeBinaryOperatorExpression(new CodeCastExpression("Object",
                new CodeVariableReferenceExpression("intInput")),
                CodeBinaryOperatorType.IdentityEquality, new CodeCastExpression("Object",
                new CodePrimitiveExpression(5))),
                new CodeStatement[] { new CodeMethodReturnStatement(new
                CodePrimitiveExpression(5)) }, new CodeStatement[] { new
                CodeMethodReturnStatement(new CodePrimitiveExpression(4))}));
            class1.Members.Add(retMethod);

            AssertEqual(ns,
                @"Imports System

                  Namespace Namespace1

                      Public Class Class1
                          Inherits Object

                          Public Function ReturnMethod(ByVal intInput As Integer) As Integer
                              Dim x1 As Integer = ((18  _
                                          / (6 - 4))  _
                                          * intInput)
                              Dim x2 As Integer = (19 Mod 8)
                              Dim x3 As Integer = ((15 And 35)  _
                                          Or 129)
                              Dim x4 As Integer = 0
                              If ((x2 = 3)  _
                                          OrElse (x3 < 129)) Then
                                  x4 = (x4 + 1)
                              Else
                                  x4 = (x4 + 2)
                              End If
                              If ((x2 > -1)  _
                                          AndAlso (x3 >= 5000)) Then
                                  x4 = (x4 + 4)
                              Else
                                  x4 = (x4 + 8)
                              End If
                              If ((x2 <= 3)  _
                                          AndAlso (x3 <> 1)) Then
                                  x4 = (x4 + 16)
                              Else
                                  x4 = (x4 + 32)
                              End If
                              Return (x1  _
                                          + (x2  _
                                          + (x3 + x4)))
                          End Function

                          Public Function SecondReturnMethod(ByVal intInput As Integer) As Integer
                              'To test CodeBinaryOperatorType.IdentiEquality operator
                              If (CType(intInput,[Object]) Is CType(5,[Object])) Then
                                  Return 5
                              Else
                                  Return 4
                              End If
                          End Function
                      End Class
                  End Namespace");
        }
    public override void Initialize(CodeFileGenerator fileGenerator)
    {
        base.Initialize(fileGenerator);

        //Throw in NUnit
        base.Namespace.Imports.Add(new CodeNamespaceImport("NUnit.Framework"));

        //Declare test suite class
        var testSuitDeclaration = new CodeTypeDeclaration
        {
            Name = _testSuiteData.Name + "TestSuite",
            IsClass = true,
        };

        //Adding text fixture attribute
        testSuitDeclaration.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("TestFixture")));

        foreach (var scenario in _testSuiteData.Scenarios)
        {
            var isMultiinstance = _elementData.IsMultiInstance;
            var useParameter = !String.IsNullOrEmpty(scenario.CommandData.RelatedTypeName);
            const string controllerVariableName = "controller";
            const string argumentVariableName = "argument";
            const string senderVariableName = "sender";

            //Setup scenario method
            var testMethod = new CodeMemberMethod
            {
                Name = scenario.Name.Replace(" ", "_"),
                Attributes = MemberAttributes.Public,
            };
            testMethod.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("Test")));

            //Create controller instance + comment
            var controllerDeclaractionComment = new CodeCommentStatement("GIVEN: setup your environment here");
            var contollerDeclaractionStatement = new CodeVariableDeclarationStatement(
                new CodeTypeReference(_elementData.NameAsController),
                controllerVariableName,
                new CodeObjectCreateExpression(_elementData.NameAsController));

            testMethod.Statements.Add(new CodeSnippetStatement(""));
            testMethod.Statements.Add(controllerDeclaractionComment);
            testMethod.Statements.Add(contollerDeclaractionStatement);

            //Create viewmodel if multiinstance
            if (isMultiinstance)
            {
                var viewModelDeclaration = new CodeVariableDeclarationStatement(
                    new CodeTypeReference(_elementData.NameAsViewModel),
                    senderVariableName,
                    new CodeObjectCreateExpression(
                        new CodeTypeReference(_elementData.NameAsViewModel),
                        new CodeSnippetExpression(controllerVariableName)));

                testMethod.Statements.Add(viewModelDeclaration);
            }

            //Create parameter if needed
            if (useParameter)
            {
                CodeVariableDeclarationStatement argumentDeclaration = null;
                var viewModel = _elementData.OwnerData.GetViewModel(scenario.CommandData.RelatedTypeName);

                if (viewModel == null)
                    argumentDeclaration = new CodeVariableDeclarationStatement(
                        new CodeTypeReference(scenario.CommandData.RelatedTypeName),
                        argumentVariableName,
                        new CodeDefaultValueExpression(new CodeTypeReference(scenario.CommandData.RelatedTypeName))
                        );
                else
                    argumentDeclaration = new CodeVariableDeclarationStatement(
                        new CodeTypeReference(viewModel.NameAsViewModel), argumentVariableName, new CodeDefaultValueExpression(new CodeTypeReference(viewModel.NameAsViewModel)));
                testMethod.Statements.Add(argumentDeclaration);
            }

            //Create invocation to the controller + comment
            var commandInvocationComment = new CodeCommentStatement("WHEN: call to the command");
            var commandInvocation = new CodeMethodInvokeExpression(
                new CodeSnippetExpression(controllerVariableName),
                scenario.CommandData.Name);

            if(isMultiinstance)
            commandInvocation.Parameters.Add(new CodeSnippetExpression(senderVariableName));
            if(useParameter)
            commandInvocation.Parameters.Add(new CodeSnippetExpression(argumentVariableName));

            testMethod.Statements.Add(new CodeSnippetStatement(""));
            testMethod.Statements.Add(commandInvocationComment);
            testMethod.Statements.Add(commandInvocation);

            //Create template assertion + comment
            var assertionComment = new CodeCommentStatement("THEN: Assert anything here");
            var assertionInvocation = new CodeSnippetExpression("Assert.That(true)");

            testMethod.Statements.Add(new CodeSnippetStatement(""));
            testMethod.Statements.Add(assertionComment);
            testMethod.Statements.Add(assertionInvocation);

            testSuitDeclaration.Members.Add(testMethod);
        }
        base.Namespace.Types.Add(testSuitDeclaration);
    }