Beispiel #1
0
    /*
     * Generates an Enum member, creating the Enum if necessary.
     */
    public void DefineMember(Smoke.Method* meth)
    {
        if ((meth->flags & (uint) Smoke.MethodFlags.mf_enum) == 0)
            return;

        string typeName = ByteArrayManager.GetString(data.Smoke->types[meth->ret].name);
        if (typeName == "long") // unnamed enum
            return;

        CodeTypeDeclaration enumType;
        if (!data.EnumTypeMap.TryGetValue(typeName, out enumType))
        {
            enumType = DefineEnum(typeName);
        }
        CodeMemberField member = new CodeMemberField();
        member.Name = ByteArrayManager.GetString(data.Smoke->methodNames[meth->name]);
        long value = GetEnumValue(data.Smoke, meth);

        if (value > int.MaxValue && enumType.BaseTypes.Count == 0)
        {
            // make the enum derive from 'long' if necessary
            enumType.BaseTypes.Add(new CodeTypeReference(typeof(long)));
        }

        member.InitExpression = new CodePrimitiveExpression(value);
        if (PostEnumMemberHook != null)
        {
            PostEnumMemberHook(data.Smoke, meth, member, enumType);
        }
        enumType.Members.Add(member);
    }
 private static CodeMemberField CreateBeginOperationDelegate(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName)
 {
     CodeMemberField field = new CodeMemberField();
     field.Attributes = MemberAttributes.Private;
     field.Type = new CodeTypeReference(beginOperationDelegateTypeName);
     field.Name = NamingHelper.GetUniqueName(GetBeginOperationDelegateName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations);
     clientType.Members.Add(field);
     return field;
 }
Beispiel #3
0
 /// <summary>
 /// 字段
 /// <para>eg. public Dictionary<string,string> TestDic = new Dictionary<string,string>();</para>
 /// </summary>
 /// <param name="inLeft">字段类型</param>
 /// <param name="inFieldName"></param>
 /// <param name="inRight"></param>
 public ItemField(string inLeft, string inFieldName, string inRight = "", MemberAttributes inAtt = MemberAttributes.Private)
 {
     field = new CodeMemberField(inLeft, inFieldName);
     if (inRight != "")
     {
         CodeVariableReferenceExpression right = new CodeVariableReferenceExpression(inRight);
         field.InitExpression = right;
     }
     field.Attributes = inAtt;
 }
        public void AccessingFields()
        {
            var cd = new CodeTypeDeclaration("ClassWithFields") { IsClass = true };

            var field = new CodeMemberField("System.String", "Microsoft");
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.InitExpression = new CodePrimitiveExpression("hi");
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "StaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(5);
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "NonStaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(6);
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "PrivateField";
            field.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(7);
            cd.Members.Add(field);

            var cmm = new CodeMemberMethod();
            cmm.Name = "UsePrivateField";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"), new CodeVariableReferenceExpression("i")));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField")));
            cd.Members.Add(cmm);

            AssertEqual(cd,
                @"Public Class ClassWithFields
                      Public Shared Microsoft As String = ""hi""
                      Public Shared StaticPublicField As Integer = 5
                      Public NonStaticPublicField As Integer = 6
                      Private PrivateField As Integer = 7
                      Public Function UsePrivateField(ByVal i As Integer) As Integer
                          Me.PrivateField = i
                          Return Me.PrivateField
                      End Function
                  End Class");
        }
        public void AccessingFields()
        {
            var cd = new CodeTypeDeclaration("ClassWithFields") { IsClass = true };

            var field = new CodeMemberField("System.String", "Microsoft");
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.InitExpression = new CodePrimitiveExpression("hi");
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "StaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(5);
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "NonStaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(6);
            cd.Members.Add(field);

            field = new CodeMemberField();
            field.Name = "PrivateField";
            field.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int));
            field.InitExpression = new CodePrimitiveExpression(7);
            cd.Members.Add(field);

            var cmm = new CodeMemberMethod();
            cmm.Name = "UsePrivateField";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField"), new CodeVariableReferenceExpression("i")));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PrivateField")));
            cd.Members.Add(cmm);

            AssertEqual(cd,
                @"public class ClassWithFields {
                      public static string Microsoft = ""hi"";
                      public static int StaticPublicField = 5;
                      public int NonStaticPublicField = 6;
                      private int PrivateField = 7;
                      public int UsePrivateField(int i) {
                          this.PrivateField = i;
                          return this.PrivateField;
                      }
                  }");
        }
        public void Indexers()
        {
            CodeNamespace nspace = new CodeNamespace("NSPC");

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

            CodeMemberField field = new CodeMemberField();
            field.Name = "PublicField";
            field.InitExpression = new CodeArrayCreateExpression(new CodeTypeReference(typeof(int)), new CodeExpression[]{
                new CodePrimitiveExpression(0), new CodePrimitiveExpression(0),new CodePrimitiveExpression(0),new CodePrimitiveExpression(0),
                new CodePrimitiveExpression(0),new CodePrimitiveExpression(0), new CodePrimitiveExpression(0)});
            field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            field.Type = new CodeTypeReference(typeof(int[]));
            cd.Members.Add(field);

            // nonarray indexers
            CodeMemberProperty indexerProperty = new CodeMemberProperty();
            indexerProperty.Name = "Item";
            indexerProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            indexerProperty.Type = new CodeTypeReference(typeof(int));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            // uses array indexer
            indexerProperty.SetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                , "PublicField"), new CodeExpression[] { new CodeVariableReferenceExpression("i") }),
                new CodeVariableReferenceExpression("value")));
            indexerProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PublicField"),
                new CodeVariableReferenceExpression("i"))));
            cd.Members.Add(indexerProperty);

            // nonarray indexers
            indexerProperty = new CodeMemberProperty();
            indexerProperty.Name = "Item";
            indexerProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            indexerProperty.Type = new CodeTypeReference(typeof(int));
            indexerProperty.SetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                , "PublicField"), new CodeExpression[] { new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                                                            new CodeVariableReferenceExpression("b"))}),
                new CodeVariableReferenceExpression("value")));
            indexerProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "PublicField"),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b")))));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "a"));
            indexerProperty.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "b"));
            // uses array indexer

            cd.Members.Add(indexerProperty);

            cd = new CodeTypeDeclaration("UseTEST");
            cd.IsClass = true;
            nspace.Types.Add(cd);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "TestMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("TEST"),
                "temp", new CodeObjectCreateExpression("TEST")));
            cmm.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(
                new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(1) }),
                new CodeVariableReferenceExpression("i")));
            cmm.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(
                new CodeVariableReferenceExpression("temp"), new CodeExpression[]{new CodePrimitiveExpression(2),
                new CodePrimitiveExpression(4)}),
                new CodePrimitiveExpression(83)));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                new CodeIndexerExpression(new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(1) }),
                CodeBinaryOperatorType.Add,
                new CodeIndexerExpression(new CodeVariableReferenceExpression("temp"), new CodeExpression[] { new CodePrimitiveExpression(2), new CodePrimitiveExpression(4) }))));

            cd.Members.Add(cmm);

            AssertEqual(nspace,
                @"Namespace NSPC
                  Public Class TEST
                      Public PublicField() As Integer = New Integer() {0, 0, 0, 0, 0, 0, 0}
                      Public Overloads Default Property Item(ByVal i As Integer) As Integer
                          Get
                              Return Me.PublicField(i)
                          End Get
                          Set
                              Me.PublicField(i) = value
                          End Set
                      End Property
                      Public Overloads Default Property Item(ByVal a As Integer, ByVal b As Integer) As Integer
                          Get
                              Return Me.PublicField((a + b))
                          End Get
                          Set
                              Me.PublicField((a + b)) = value
                          End Set
                      End Property
                  End Class
                  Public Class UseTEST

                      Public Function TestMethod(ByVal i As Integer) As Integer
                          Dim temp As TEST = New TEST()
                          temp(1) = i
                          temp(2, 4) = 83
                          Return (temp(1) + temp(2, 4))
                      End Function
                  End Class
              End Namespace");
        }
        public void TypeOf()
        {
            var nspace = new CodeNamespace("System.Something");
            var class1 = new CodeTypeDeclaration("ClassToTest") { IsClass = true };
            nspace.Types.Add(class1);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "Primitives";
            cmm.ReturnType = new CodeTypeReference(typeof(string));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(int)), "ToString")));
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfPrimitives";
            cmm.ReturnType = new CodeTypeReference(typeof(string));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(int[])), "ToString")));
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "NonPrimitives";
            cmm.ReturnType = new CodeTypeReference(typeof(string));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(System.ICloneable)), "ToString")));
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfNonPrimitives";
            cmm.ReturnType = new CodeTypeReference(typeof(string));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(System.ICloneable[])), "ToString")));
            class1.Members.Add(cmm);

            cmm = new CodeMemberMethod();
            cmm.Name = "Enumerations";
            cmm.ReturnType = new CodeTypeReference(typeof(string));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression("DecimalEnum"), "ToString")));
            class1.Members.Add(cmm);

            var ce = new CodeTypeDeclaration("DecimalEnum") { IsEnum = true };
            ce.IsEnum = true;
            nspace.Types.Add(ce);
            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);
            }

            AssertEqual(nspace,
                @"Namespace System.Something
                      Public Class ClassToTest
                          Public Shared Function Primitives() As String
                              Return GetType(Integer).ToString
                          End Function
                          Public Shared Function ArraysOfPrimitives() As String
                              Return GetType(Integer()).ToString
                          End Function
                          Public Shared Function NonPrimitives() As String
                              Return GetType(System.ICloneable).ToString
                          End Function
                          Public Shared Function ArraysOfNonPrimitives() As String
                              Return GetType(System.ICloneable()).ToString
                          End Function
                          Public Shared Function Enumerations() As String
                              Return GetType(DecimalEnum).ToString
                          End Function
                      End Class
                      Public Enum DecimalEnum
                          Num0 = 0
                          Num1 = 1
                          Num2 = 2
                          Num3 = 3
                          Num4 = 4
                      End Enum
                  End Namespace");
        }
Beispiel #8
0
    public CodeTypeDeclaration GenerateClass(Generator g, CodeTypeDeclaration libDecl, string libFieldName)
    {
        var decl = new CodeTypeDeclaration (Name);
        decl.IsPartial = true;
        if (BaseClasses.Count > 0)
            decl.BaseTypes.Add (new CodeTypeReference (BaseClasses [0].Name));
        else
            decl.BaseTypes.Add (new CodeTypeReference ("ICppObject"));

        bool hasBase = BaseClasses.Count > 0;

        var layout = new CodeTypeDeclaration ("_" + Name);
        layout.IsStruct = true;
        layout.TypeAttributes = TypeAttributes.NotPublic;
        decl.Members.Add (layout);

        foreach (var f in Fields) {
            CodeMemberField field = new CodeMemberField { Name = f.Name, Type = g.CppTypeToCodeDomType (f.Type) };
            layout.Members.Add (field);
        }

        var iface = new CodeTypeDeclaration ("I" + Name);
        iface.IsInterface = true;
        layout.TypeAttributes = TypeAttributes.NotPublic;
        iface.BaseTypes.Add (new CodeTypeReference ("ICppClassOverridable", new CodeTypeReference [] { new CodeTypeReference (decl.Name) }));
        decl.Members.Add (iface);

        var layoutField = new CodeMemberField (new CodeTypeReference (typeof (Type)), "native_layout");
        layoutField.Attributes = MemberAttributes.Private|MemberAttributes.Static;
        layoutField.InitExpression = new CodeTypeOfExpression (layout.Name);
        decl.Members.Add (layoutField);

        var implField = new CodeMemberField (new CodeTypeReference (iface.Name), "impl");
        implField.Attributes = MemberAttributes.Private|MemberAttributes.Static;
        var getclass = new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (libDecl.Name), libFieldName), "GetClass", new CodeTypeReference [] { new CodeTypeReference (iface.Name), new CodeTypeReference (layout.Name), new CodeTypeReference (decl.Name) });
        implField.InitExpression = new CodeMethodInvokeExpression (getclass, new CodeExpression [] { new CodePrimitiveExpression (Name) });
        decl.Members.Add (implField);
        //private static IClass impl = global::CppTests.Libs.Test.GetClass <IClass, _Class, Class>("Class");

        if (!hasBase) {
            var ptrField = new CodeMemberField (new CodeTypeReference ("CppInstancePtr"), "native_ptr");
            ptrField.Attributes = MemberAttributes.Family;
            decl.Members.Add (ptrField);
        }

        var allocCtor = new CodeConstructor () {
            };
        allocCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppLibrary"), "dummy"));
        allocCtor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "native_ptr"), new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Alloc"), new CodeExpression [] { new CodeThisReferenceExpression () })));
        if (hasBase) {
            var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo");
            allocCtor.BaseConstructorArgs.Add (implTypeInfo);
        }
        decl.Members.Add (allocCtor);

        var subclassCtor = new CodeConstructor () {
                Attributes = MemberAttributes.Family
            };
        subclassCtor.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("CppTypeInfo"), "subClass"));
        subclassCtor.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeArgumentReferenceExpression ("subClass"), "AddBase"), new CodeExpression [] { new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "TypeInfo") })));
        if (hasBase) {
            var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo");
            subclassCtor.BaseConstructorArgs.Add (implTypeInfo);
        }
        decl.Members.Add (subclassCtor);

        if (!hasBase) {
            var nativeProperty = new CodeMemberProperty () {
                    Name = "Native",
                        Type = new CodeTypeReference ("CppInstancePtr"),
                        Attributes = MemberAttributes.Public|MemberAttributes.Final
                        };
            nativeProperty.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "native_ptr")));
            decl.Members.Add (nativeProperty);
        }

        var disposeMethod = new CodeMemberMethod () {
                Name = "Dispose",
                Attributes = MemberAttributes.Public
        };
        if (Methods.Any (m => m.IsDestructor))
            disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "impl"), "Destruct"), new CodeExpression [] { new CodeFieldReferenceExpression (null, "Native") })));
        disposeMethod.Statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (new CodeFieldReferenceExpression (null, "Native"), "Dispose"))));
        decl.Members.Add (disposeMethod);

        foreach (Method m in Methods) {
            iface.Members.Add (m.GenerateIFaceMethod (g));

            if (m.GenWrapperMethod) {
                var cm = m.GenerateWrapperMethod (g);
                if (m.IsConstructor && hasBase) {
                    var implTypeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo");
                    (cm as CodeConstructor).BaseConstructorArgs.Add (implTypeInfo);
                }
                decl.Members.Add (cm);
            }
        }

        foreach (Property p in Properties) {
            decl.Members.Add (p.GenerateProperty (g));
        }

        return decl;
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        // [assembly: System.Reflection.AssemblyTitle("MyAssembly")]
        // [assembly: System.Reflection.AssemblyVersion("1.0.6.2")]
        // [assembly: System.CLSCompliantAttribute(false)]
        // 
        // namespace MyNamespace {
        //     using System;
        //     using System.Drawing;
        //     using System.Windows.Forms;
        //     using System.ComponentModel;
        //
        CodeNamespace ns = new CodeNamespace ();
        ns.Name = "MyNamespace";
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
        cu.Namespaces.Add (ns);

        cu.ReferencedAssemblies.Add ("System.Xml.dll");
        cu.ReferencedAssemblies.Add ("System.Drawing.dll");
        cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");

        // Assembly Attributes
        if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
            AddScenario ("CheckAssemblyAttributes", "Check that assembly attributes get generated properly.");
            CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new
                CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly"))));
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new
                CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2"))));
            attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new
                CodeAttributeArgument (new CodePrimitiveExpression (false))));
        }

        // GENERATES (C#):
        //     [System.Serializable()]
        //     [System.Obsolete("Don\'t use this Class")]
        //     [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")]
        //     public class MyClass {
        //

#if !WHIDBEY
        if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider))
            AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#else
        AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#endif
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "MyClass";
        class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable"));
        class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Class"))));
        class1.CustomAttributes.Add (new
            CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName,
            new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID"))));
        ns.Types.Add (class1);

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Method")]
        //         [System.ComponentModel.Editor("This", "That")]
        //         public void MyMethod(string blah, int[] arrayit) {
        //         }
        AddScenario ("CheckMyMethodAttributes", "Check that attributes are generated properly on MyMethod().");
        CodeMemberMethod method1 = new CodeMemberMethod ();
        method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
        method1.Name = "MyMethod";
        method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Method"))));
        method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.ComponentModel.Editor", new
            CodeAttributeArgument (new CodePrimitiveExpression ("This")), new CodeAttributeArgument (new
            CodePrimitiveExpression ("That"))));
        CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah");

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

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

        // GENERATES (C#):
        //         [System.Xml.Serialization.XmlElementAttribute()]
        //         private string myField = "hi!";
        //
        AddScenario ("CheckMyFieldAttributes", "Check that attributes are generated properly on MyField.");
        CodeMemberField field1 = new CodeMemberField ();
        field1.Name = "myField";
        field1.Attributes = MemberAttributes.Public;
        field1.Type = new CodeTypeReference (typeof (string));
        field1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlElementAttribute"));
        field1.InitExpression = new CodePrimitiveExpression ("hi!");
        class1.Members.Add (field1);


        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Property")]
        //         public string MyProperty {
        //             get {
        //                 return this.myField;
        //             }
        //         }
        AddScenario ("CheckMyPropertyAttributes", "Check that attributes are generated properly on MyProperty.");
        CodeMemberProperty prop1 = new CodeMemberProperty ();
        prop1.Attributes = MemberAttributes.Public;
        prop1.Name = "MyProperty";
        prop1.Type = new CodeTypeReference (typeof (string));
        prop1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Property"))));
        prop1.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "myField")));
        class1.Members.Add (prop1);

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Constructor")]
        //         public MyClass() {
        //         }
        //     }

        if (!(provider is JScriptCodeProvider))
            AddScenario ("CheckConstructorAttributes", "Check that attributes are generated properly on the constructor.");
        CodeConstructor const1 = new CodeConstructor ();
        const1.Attributes = MemberAttributes.Public;
        const1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor"))));
        class1.Members.Add (const1);

        if (Supports (provider, GeneratorSupport.DeclareEvents)) {
            // GENERATES (C#):
            //     public class Test : Form {
            //         
            //         private Button b = new Button();
            //
            // 
            AddScenario ("CheckEventAttributes", "test attributes on an event");
            class1 = new CodeTypeDeclaration ("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add (new CodeTypeReference ("Form"));
            ns.Types.Add (class1);
            CodeMemberField mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button"));
            class1.Members.Add (mfield);

            // GENERATES (C#):
            //         public Test() {
            //             this.Size = new Size(600, 600);
            //             b.Text = "Test";
            //             b.TabIndex = 0;
            //             b.Location = new Point(400, 525);
            //             this.MyEvent += new EventHandler(this.b_Click);
            //         }
            //
            CodeConstructor ctor = new CodeConstructor ();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
                "Size"), new CodeObjectCreateExpression (new CodeTypeReference ("Size"),
                new CodePrimitiveExpression (600), new CodePrimitiveExpression (600))));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "Text"), new CodePrimitiveExpression ("Test")));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "TabIndex"), new CodePrimitiveExpression (0)));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "Location"), new CodeObjectCreateExpression (new CodeTypeReference ("Point"),
                new CodePrimitiveExpression (400), new CodePrimitiveExpression (525))));
            ctor.Statements.Add (new CodeAttachEventStatement (new CodeEventReferenceExpression (new
                CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler")
                , new CodeThisReferenceExpression (), "b_Click")));
            class1.Members.Add (ctor);

            // GENERATES (C#):
            //         [System.CLSCompliantAttribute(false)]
            //         public event System.EventHandler MyEvent;
            CodeMemberEvent evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false))));
            class1.Members.Add (evt);

            // GENERATES (C#):
            //         private void b_Click(object sender, System.EventArgs e) {
            //         }
            //     }
            // }
            //
            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "b_Click";
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
            class1.Members.Add (cmm);
        }

    }
    public override void Interpret(InternalDSL.Operator op, FunctionBlock block)
    {
        if (ops == null)
        {
            ctxs      = Engine.GetPlugin <ContextSwitchesPlugin> ();
            ops       = Engine.GetPlugin <EventFunctionOperators> ();
            exprInter = Engine.GetPlugin <ExpressionInterpreter> ();
        }
        if (op.Args.Count > 0)
        {
            var varName = ((op.Args [0].Operands [0] as ExprAtom).Content as Scope).Parts [0] as string;
            if (op.Context is Expression)
            {
                //cache(some_name) = expression
//				var varDecl = block.FindStatement<DeclareVariableStatement> (v => v.Name == varName);
//				varDecl.IsArg = true;

                var exprValue = exprInter.InterpretExpression(op.Context as Expression, block);
                Debug.Log(exprValue.ExprString);
                var field = new CodeMemberField(exprValue.Type, varName);
                field.UserData.Add("type", exprValue.Type);
                block.Type.Members.Add(field);
                block.Statements.Add(String.Format("{0} = {1};", varName, exprValue.ExprString));
                block.Statements.Add(new DeclareVariableStatement()
                {
                    Name = varName, IsArg = true, Type = exprValue.Type
                });
                //var varDecl = block.FindStatement<DeclareVariableStatement> (v => v.Name == varName);
            }
            else
            {
                //cache(some_name, scope) = { ... }
                var exprValue = exprInter.InterpretExpression(op.Args [1], block);
                var field     = new CodeMemberField(exprValue.Type, varName);
                field.UserData.Add("type", exprValue.Type);
                block.Type.Members.Add(field);
                DeclareVariableStatement cachedVar = new DeclareVariableStatement();
                cachedVar.Name      = varName;
                cachedVar.IsContext = true;
                cachedVar.Type      = exprValue.Type;
                cachedVar.IsArg     = true;
                block.Statements.Add(cachedVar);
                block.Statements.Add(String.Format("{0} = {1};", varName, exprValue.ExprString));
                block.Statements.Add(new DeclareVariableStatement()
                {
                    Name = varName, IsArg = true, Type = exprValue.Type
                });
                var inter = ctxs.GetInterByType(exprValue.Type);
                inter.Interpret(op, block);
            }
        }
        else
        {
            //cache = some_name

            var varName = (((op.Context as Expression).Operands [0] as ExprAtom).Content as Scope).Parts [0] as string;
            var varDecl = block.FindStatement <DeclareVariableStatement> (v => v.Name == varName);
            //varDecl.IsArg = true;
            varDecl.IsDeclaration = false;

            var field = new CodeMemberField(varDecl.Type, varDecl.Name);
            field.UserData.Add("type", varDecl.Type);
            block.Type.Members.Add(field);
            //block.Statements.Add (String.Format ("this.{0} = {0};", varName));
        }

        //new CodeMemberField()
        //block.Type.Members.Add ();
    }
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, string nameSpace, string baseName, string resourcesNamespace, bool internalClass, bool useStatic, bool supportsTryCatch)
        {
            string str;

            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                {
                    str = resourcesNamespace + '.' + baseName;
                }
                else
                {
                    str = baseName;
                }
            }
            else if ((nameSpace != null) && (nameSpace.Length > 0))
            {
                str = nameSpace + '.' + baseName;
            }
            else
            {
                str = baseName;
            }
            CodeCommentStatement statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments1"));

            srClass.Comments.Add(statement);
            statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments2"));
            srClass.Comments.Add(statement);
            statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments3"));
            srClass.Comments.Add(statement);
            statement = new CodeCommentStatement(System.Design.SR.GetString("ClassComments4"));
            srClass.Comments.Add(statement);
            CodeAttributeDeclaration declaration = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)))
            {
                AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference }
            };

            declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            declaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));
            CodeConstructor constructor = new CodeConstructor();

            constructor.CustomAttributes.Add(declaration);
            if (useStatic || internalClass)
            {
                constructor.Attributes = MemberAttributes.FamilyAndAssembly;
            }
            else
            {
                constructor.Attributes = MemberAttributes.Public;
            }
            srClass.Members.Add(constructor);
            CodeTypeReference type  = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            CodeMemberField   field = new CodeMemberField(type, "resourceMan")
            {
                Attributes = MemberAttributes.Private
            };

            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);
            CodeTypeReference reference2 = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);

            field = new CodeMemberField(reference2, "resourceCulture")
            {
                Attributes = MemberAttributes.Private
            };
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);
            CodeMemberProperty property = new CodeMemberProperty();

            srClass.Members.Add(property);
            property.Name   = "ResourceManager";
            property.HasGet = true;
            property.HasSet = false;
            property.Type   = type;
            if (internalClass)
            {
                property.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                property.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                property.Attributes |= MemberAttributes.Static;
            }
            CodeTypeReference reference3 = new CodeTypeReference(typeof(EditorBrowsableState))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };
            CodeAttributeArgument    argument     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(reference3), "Advanced"));
            CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", new CodeAttributeArgument[] { argument })
            {
                AttributeType = { Options = CodeTypeReferenceOptions.GlobalReference }
            };

            property.CustomAttributes.Add(declaration2);
            CodeMemberProperty property2 = new CodeMemberProperty();

            srClass.Members.Add(property2);
            property2.Name   = "Culture";
            property2.HasGet = true;
            property2.HasSet = true;
            property2.Type   = reference2;
            if (internalClass)
            {
                property2.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                property2.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                property2.Attributes |= MemberAttributes.Static;
            }
            property2.CustomAttributes.Add(declaration2);
            CodeFieldReferenceExpression    left           = new CodeFieldReferenceExpression(null, "resourceMan");
            CodeMethodReferenceExpression   method         = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(object)), "ReferenceEquals");
            CodeMethodInvokeExpression      condition      = new CodeMethodInvokeExpression(method, new CodeExpression[] { left, new CodePrimitiveExpression(null) });
            CodePropertyReferenceExpression expression4    = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");
            CodeObjectCreateExpression      initExpression = new CodeObjectCreateExpression(type, new CodeExpression[] { new CodePrimitiveExpression(str), expression4 });

            CodeStatement[] trueStatements = new CodeStatement[] { new CodeVariableDeclarationStatement(type, "temp", initExpression), new CodeAssignStatement(left, new CodeVariableReferenceExpression("temp")) };
            property.GetStatements.Add(new CodeConditionStatement(condition, trueStatements));
            property.GetStatements.Add(new CodeMethodReturnStatement(left));
            property.Comments.Add(new CodeCommentStatement("<summary>", true));
            property.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("ResMgrPropertyComment"), true));
            property.Comments.Add(new CodeCommentStatement("</summary>", true));
            CodeFieldReferenceExpression expression = new CodeFieldReferenceExpression(null, "resourceCulture");

            property2.GetStatements.Add(new CodeMethodReturnStatement(expression));
            CodePropertySetValueReferenceExpression right = new CodePropertySetValueReferenceExpression();

            property2.SetStatements.Add(new CodeAssignStatement(expression, right));
            property2.Comments.Add(new CodeCommentStatement("<summary>", true));
            property2.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("CulturePropertyComment1"), true));
            property2.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("CulturePropertyComment2"), true));
            property2.Comments.Add(new CodeCommentStatement("</summary>", true));
        }
Beispiel #12
0
        /// <summary>
        /// Create a new Alpaca client executable using the supplied parameters
        /// </summary>
        /// <param name="DeviceType">The ASCOM device type to create</param>
        /// <param name="DeviceNumber">The number of this device type to create</param>
        /// <param name="OutputDirectory">The directory in which to place the compiled assembly</param>
        /// <remarks>
        /// This subroutine creates compiler source line definitions (not source code as such) and stores them in memory
        /// When complete, the compiler is called and the resultant assembly is stored in the specified output directory.
        /// The code created has no function as such it is just a shell with all of the heavy lifting undertaken by an inherited base class that is supplied pre-compiled
        /// The resultant assembly for Camera device 1 has this form:
        ///
        /// using System;
        /// using System.Runtime.InteropServices;
        /// namespace ASCOM.DynamicRemoteClients
        /// {
        ///     [Guid("70495DF9-C01E-4987-AE49-E12967202C7F")]             <====> The GUID is dynamically created on the user's machine so that it is unique for every driver
        ///     [ProgId(DRIVER_PROGID)]
        ///     [ServedClassName(DRIVER_DISPLAY_NAME)]
        ///     [ClassInterface(ClassInterfaceType.None)]
        ///     public class Camera : CameraBaseClass                      <====> Created from supplied parameters - all executable code is in the base class
        ///     {
        ///         private const string DRIVER_NUMBER = "1";              <====> Created from supplied parameters
        ///         private const string DEVICE_TYPE = "Camera";           <====> Created from supplied parameters
        ///         private const string DRIVER_DISPLAY_NAME = SharedConstants.DRIVER_DISPLAY_NAME + " " + DRIVER_NUMBER;
        ///         private const string DRIVER_PROGID = SharedConstants.DRIVER_PROGID_BASE + DRIVER_NUMBER + "." + DEVICE_TYPE;
        ///         public Camera() : base(DRIVER_NUMBER, DRIVER_DISPLAY_NAME, DRIVER_PROGID)
        ///         {
        ///         }
        ///     }
        /// }
        /// </remarks>
        internal static void CreateAlpacaClient(string DeviceType, int DeviceNumber, string ProgId, string DisplayName, string localServerPath)
        {
            TL.LogMessage("CreateAlpacaClient", $"Creating new ProgID: for {DeviceType} device {DeviceNumber} with ProgID: {ProgId} and display name: {DisplayName}");

            try
            {
                // Generate the container unit
                CodeCompileUnit program = new CodeCompileUnit();

                // Generate the namespace
                CodeNamespace ns = new CodeNamespace("ASCOM.DynamicRemoteClients");

                // Add required imports
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.Runtime.InteropServices"));

                // Declare the device class
                CodeTypeDeclaration deviceClass = new CodeTypeDeclaration()
                {
                    Name    = DeviceType,
                    IsClass = true
                };

                // Add the class base type
                deviceClass.BaseTypes.Add(new CodeTypeReference {
                    BaseType = DeviceType + BASE_CLASS_POSTFIX
                });
                TL.LogMessage("CreateAlpacaClient", "Created base type");

                // Create custom attributes to decorate the class
                CodeAttributeDeclaration           guidAttribute            = new CodeAttributeDeclaration("Guid", new CodeAttributeArgument(new CodePrimitiveExpression(Guid.NewGuid().ToString())));
                CodeAttributeDeclaration           progIdAttribute          = new CodeAttributeDeclaration("ProgId", new CodeAttributeArgument(new CodeArgumentReferenceExpression("DRIVER_PROGID")));
                CodeAttributeDeclaration           servedClassNameAttribute = new CodeAttributeDeclaration("ServedClassName", new CodeAttributeArgument(new CodeArgumentReferenceExpression("DRIVER_DISPLAY_NAME")));
                CodeAttributeDeclaration           classInterfaceAttribute  = new CodeAttributeDeclaration("ClassInterface", new CodeAttributeArgument(new CodeArgumentReferenceExpression("ClassInterfaceType.None")));
                CodeAttributeDeclarationCollection customAttributes         = new CodeAttributeDeclarationCollection()
                {
                    guidAttribute, progIdAttribute, servedClassNameAttribute, classInterfaceAttribute
                };
                TL.LogMessage("CreateAlpacaClient", "Created custom attributes");

                // Add the custom attributes to the class
                deviceClass.CustomAttributes = customAttributes;

                // Create some class level private constants
                CodeMemberField driverNumberConst = new CodeMemberField(typeof(string), "DRIVER_NUMBER");
                driverNumberConst.Attributes     = MemberAttributes.Private | MemberAttributes.Const;
                driverNumberConst.InitExpression = new CodePrimitiveExpression(DeviceNumber.ToString());

                CodeMemberField deviceTypeConst = new CodeMemberField(typeof(string), "DEVICE_TYPE");
                deviceTypeConst.Attributes     = MemberAttributes.Private | MemberAttributes.Const;
                deviceTypeConst.InitExpression = new CodePrimitiveExpression(DeviceType);

                CodeMemberField driverDisplayNameConst = new CodeMemberField(typeof(string), "DRIVER_DISPLAY_NAME");
                driverDisplayNameConst.Attributes     = (MemberAttributes.Private | MemberAttributes.Const);
                driverDisplayNameConst.InitExpression = new CodePrimitiveExpression(DisplayName);

                CodeMemberField driverProgIDConst = new CodeMemberField(typeof(string), "DRIVER_PROGID");
                driverProgIDConst.Attributes     = MemberAttributes.Private | MemberAttributes.Const;
                driverProgIDConst.InitExpression = new CodePrimitiveExpression(ProgId);

                // Add the constants to the class
                deviceClass.Members.AddRange(new CodeMemberField[] { driverNumberConst, deviceTypeConst, driverDisplayNameConst, driverProgIDConst });
                TL.LogMessage("CreateAlpacaClient", "Added constants to class");

                // Declare the class constructor
                CodeConstructor constructor = new CodeConstructor();
                constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;

                // Add a call to the base class with required parameters
                constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_NUMBER"));
                constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_DISPLAY_NAME"));
                constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_PROGID"));
                deviceClass.Members.Add(constructor);
                TL.LogMessage("CreateAlpacaClient", "Added base constructor");

                // Add the class to the namespace
                ns.Types.Add(deviceClass);
                TL.LogMessage("CreateAlpacaClient", "Added class to name space");

                // Add the namespace to the program, which is now complete
                program.Namespaces.Add(ns);
                TL.LogMessage("CreateAlpacaClient", "Added name space to program");

                // Construct the path to the output DLL
                String dllName = $"{localServerPath.TrimEnd('\\')}\\{SharedConstants.DRIVER_PROGID_BASE}{DeviceNumber}.{DeviceType}.dll";
                TL.LogMessage("CreateAlpacaClient", string.Format("Output file name: {0}", dllName));

                // Create relevant compiler options to shape the compilation
                CompilerParameters cp = new CompilerParameters()
                {
                    GenerateExecutable      = false,   // Specify output of a DLL
                    OutputAssembly          = dllName, // Specify the assembly file name to generate
                    GenerateInMemory        = false,   // Save the assembly as a physical file.
                    TreatWarningsAsErrors   = false,   // Don't treat warnings as errors.
                    IncludeDebugInformation = true     // Include debug information
                };
                TL.LogMessage("CreateAlpacaClient", "Created compiler parameters");

                // Add required assembly references to make sure the compilation succeeds
                cp.ReferencedAssemblies.Add(@"ASCOM.Attributes.dll");                    // Must be present in the current directory because the compiler doesn't use the GAC
                cp.ReferencedAssemblies.Add(@"ASCOM.DeviceInterfaces.dll");              // Must be present in the current directory because the compiler doesn't use the GAC
                cp.ReferencedAssemblies.Add(@"ASCOM.Newtonsoft.Json.dll");               // Must be present in the current directory because the compiler doesn't use the GAC
                cp.ReferencedAssemblies.Add(@"RestSharp.dll");                           // Must be present in the current directory
                cp.ReferencedAssemblies.Add(@"ASCOM.AlpacaClientDeviceBaseClasses.dll"); // Must be present in the current directory
                cp.ReferencedAssemblies.Add(SharedConstants.ALPACA_CLIENT_LOCAL_SERVER); // Must be present in the current directory

                Assembly executingAssembly = Assembly.GetExecutingAssembly();
                cp.ReferencedAssemblies.Add(executingAssembly.Location);

                foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies())
                {
                    cp.ReferencedAssemblies.Add(Assembly.Load(assemblyName).Location);
                }

                TL.LogMessage("CreateAlpacaClient", "Added assembly references");

                // Create formatting options for the generated code that will be logged into the trace logger
                CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions()
                {
                    BracingStyle             = "C",
                    IndentString             = "    ",
                    VerbatimOrder            = true,
                    BlankLinesBetweenMembers = false
                };

                // Get a code provider so that we can compile the program
                CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
                TL.LogMessage("CreateAlpacaClient", "Created CSharp provider");

                // Write the generated code to the trace logger
                using (MemoryStream outputStream = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(outputStream))
                    {
                        provider.GenerateCodeFromNamespace(ns, writer, codeGeneratorOptions);
                    }

                    MemoryStream actualStream = new MemoryStream(outputStream.ToArray());
                    using (StreamReader reader = new StreamReader(actualStream))
                    {
                        do
                        {
                            TL.LogMessage("GeneratedCode", reader.ReadLine());
                        } while (!reader.EndOfStream);
                    }
                }
                provider.Dispose();

                // Compile the source contained in the "program" variable
                CompilerResults cr = provider.CompileAssemblyFromDom(cp, program);
                TL.LogMessage("CreateAlpacaClient", string.Format("Compiled assembly - {0} errors", cr.Errors.Count));

                // Report success or errors
                if (cr.Errors.Count > 0)
                {
                    // Display compilation errors.
                    foreach (CompilerError ce in cr.Errors)
                    {
                        TL.LogMessage("CreateAlpacaClient", string.Format("Compiler error: {0}", ce.ToString()));
                    }
                }
                else
                {
                    // Display a successful compilation message.
                    TL.LogMessage("CreateAlpacaClient", "Assembly compiled OK!");
                }

                TL.BlankLine();
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("CreateAlpacaClient", ex.ToString());
            }
        }
        /// <summary>
        /// Creates a class declaration
        /// </summary>
        /// <param name="schema">record schema</param>
        /// <param name="ns">namespace</param>
        /// <returns></returns>
        protected virtual CodeTypeDeclaration processRecord(Schema schema)
        {
            RecordSchema recordSchema = schema as RecordSchema;

            if (null == recordSchema)
            {
                throw new CodeGenException("Unable to cast schema into a record");
            }

            // declare the class
            var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));

            //@todo implments
            if (DoJava)
            {
                ctd.BaseTypes.Add(SystemObjectStr);
                ctd.BaseTypes.Add("SpecificRecord");
            }
            else
            {
                ctd.BaseTypes.Add("ISpecificRecord");
            }
            var interf = processRecordInterface(schema);

            ctd.BaseTypes.Add(interf.Name);
            ctd.Attributes = MemberAttributes.Public;
            ctd.IsClass    = true;
            ctd.IsPartial  = true;

            createSchemaField(schema, ctd, false, false);

            // declare Get() to be used by the Writer classes
            var cmmGet = new CodeMemberMethod();

            cmmGet.Name       = ToLangCase("Get", !DoJava);
            cmmGet.Attributes = MemberAttributes.Public;
            cmmGet.ReturnType = new CodeTypeReference(SystemObjectStr);
            cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");

            // declare Put() to be used by the Reader classes
            var cmmPut = new CodeMemberMethod();

            cmmPut.Name       = ToLangCase("Put", !DoJava);
            cmmPut.Attributes = MemberAttributes.Public;
            cmmPut.ReturnType = new CodeTypeReference(typeof(void));
            cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
            cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(SystemObjectStr, "fieldValue"));
            var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
            HashSet <CodeTypeReference> feildRefs = new HashSet <CodeTypeReference>();

            foreach (Field field in recordSchema.Fields)
            {
                // Determine type of field
                bool   nullibleEnum = false;
                string baseType     = getType(field.Schema, false, ref nullibleEnum, false);
                var    ctrfield     = new CodeTypeReference(baseType);

                // Create field
                string privFieldName = string.Concat("_", field.Name);
                if (DoJava)
                {
                    privFieldName = "m" + privFieldName;
                }
                var codeField = new CodeMemberField(ctrfield, privFieldName);
                codeField.Attributes = MemberAttributes.Private;

                // Process field documentation if it exist and add to the field
                CodeCommentStatement propertyComment = null;
                if (!string.IsNullOrEmpty(field.Documentation))
                {
                    propertyComment = createDocComment(field.Documentation);
                    if (null != propertyComment)
                    {
                        codeField.Comments.Add(propertyComment);
                    }
                }

                // Add field to class
                ctd.Members.Add(codeField);

                // Create reference to the field - this.fieldname
                var fieldRef    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
                var mangledName = CodeGenUtil.Instance.Mangle(field.Name);

                // Create field property with get and set methods
                AddProperty(ctd, ctrfield, propertyComment, mangledName, fieldRef, false);

                string getsetName = mangledName;
                if (DoJava)
                {
                    getsetName = privFieldName;
                }

                // add to Get()
                getFieldStmt.Append("\t\t\tcase ");
                getFieldStmt.Append(field.Pos);
                getFieldStmt.Append(": return this.");
                getFieldStmt.Append(getsetName);
                getFieldStmt.Append(";\n");

                // add to Put()
                putFieldStmt.Append("\t\t\tcase ");
                putFieldStmt.Append(field.Pos);
                putFieldStmt.Append(": this.");
                putFieldStmt.Append(getsetName);

                feildRefs.Add(ctrfield);
                if (baseType.EndsWith("long"))
                {
                }
                var castType = baseType;
                if (DoJava)
                {
                    castType = getType(field.Schema, true, ref nullibleEnum, false);
                }
                if (nullibleEnum)
                {
                    putFieldStmt.Append(" = fieldValue == null ? (");
                    putFieldStmt.Append(baseType);
                    putFieldStmt.Append(")null : (");

                    string type = baseType.Remove(0, 16); // remove System.Nullable<
                    type = type.Remove(type.Length - 1);  // remove >

                    putFieldStmt.Append(type);
                    putFieldStmt.Append(")fieldValue; break;\n");
                }
                else
                {
                    putFieldStmt.Append(" = (");
                    putFieldStmt.Append(castType);
                    putFieldStmt.Append(")fieldValue; break;\n");
                }
            }

            // end switch block for Get()
            getFieldStmt.Append(
                "\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
            var    cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
            string cs     = cseGet.Value;

            cmmGet.Statements.Add(cseGet);
            ctd.Members.Add(cmmGet);

            // end switch block for Put()
            putFieldStmt.Append(
                "\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
            var csePut = new CodeSnippetExpression(putFieldStmt.ToString());

            cmmPut.Statements.Add(csePut);
            ctd.Members.Add(cmmPut);

            string nspace = recordSchema.Namespace;

            if (string.IsNullOrEmpty(nspace))
            {
                throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
            }
            CodeNamespace codens = addNamespace(nspace);

            codens.Types.Add(ctd);
            foreach (CodeTypeReference reference in feildRefs)
            {
                //codens.Types.Add(reference);
            }

            return(ctd);
        }
        private void GenerateServiceProxyCode(AssemblyBuilder assemblyBuilder, Type serviceType)
        {
            IResourceNameGenerator nameGenerator = assemblyBuilder.CodeDomProvider as IResourceNameGenerator;

            if (nameGenerator != null)
            {
                this.ResourceFullName = nameGenerator.GenerateResourceName(base.VirtualPath);
            }
            else
            {
                this.ResourceFullName = ResourceBuildProvider.GenerateTypeNameFromPath(base.VirtualPath);
            }

            // TODO: consolidate app relative path conversion
            // calculate the service end-point path
            string proxyPath = ResourceHandler.EnsureAppRelative(base.VirtualPath).TrimStart('~');

            // build proxy from main service type
            JsonServiceDescription    desc  = new JsonServiceDescription(serviceType, proxyPath);
            JsonServiceProxyGenerator proxy = new JsonServiceProxyGenerator(desc);

            string proxyOutput = proxy.OutputProxy(false);

            proxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, proxyOutput, true);

            string debugProxyOutput = proxy.OutputProxy(true);

            debugProxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, debugProxyOutput, false);

            byte[] gzippedBytes, deflatedBytes;
            ResourceBuildProvider.Compress(proxyOutput, out gzippedBytes, out deflatedBytes);
            string hash = ResourceBuildProvider.ComputeHash(proxyOutput);

            // generate a service factory
            CodeCompileUnit generatedUnit = new CodeCompileUnit();

            #region namespace ResourceNamespace

            CodeNamespace ns = new CodeNamespace(this.ResourceNamespace);
            generatedUnit.Namespaces.Add(ns);

            #endregion namespace ResourceNamespace

            #region public sealed class ResourceTypeName : JsonServiceInfo

            CodeTypeDeclaration resourceType = new CodeTypeDeclaration();
            resourceType.IsClass    = true;
            resourceType.Name       = this.ResourceTypeName;
            resourceType.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            resourceType.BaseTypes.Add(typeof(IJsonServiceInfo));
            resourceType.BaseTypes.Add(typeof(IOptimizedResult));
            ns.Types.Add(resourceType);

            #endregion public sealed class ResourceTypeName : CompiledBuildResult

            #region [BuildPath(virtualPath)]

            string virtualPath = base.VirtualPath;
            if (HttpRuntime.AppDomainAppVirtualPath.Length > 1)
            {
                virtualPath = virtualPath.Substring(HttpRuntime.AppDomainAppVirtualPath.Length);
            }
            virtualPath = "~" + virtualPath;

            CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(
                new CodeTypeReference(typeof(BuildPathAttribute)),
                new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath)));
            resourceType.CustomAttributes.Add(attribute);

            #endregion [BuildPath(virtualPath)]

            #region private static readonly byte[] GzippedBytes

            CodeMemberField field = new CodeMemberField();
            field.Name       = "GzippedBytes";
            field.Type       = new CodeTypeReference(typeof(byte[]));
            field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;

            CodeArrayCreateExpression arrayInit = new CodeArrayCreateExpression(field.Type, gzippedBytes.Length);
            foreach (byte b in gzippedBytes)
            {
                arrayInit.Initializers.Add(new CodePrimitiveExpression(b));
            }
            field.InitExpression = arrayInit;

            resourceType.Members.Add(field);

            #endregion private static static readonly byte[] GzippedBytes

            #region private static readonly byte[] DeflatedBytes

            field            = new CodeMemberField();
            field.Name       = "DeflatedBytes";
            field.Type       = new CodeTypeReference(typeof(byte[]));
            field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;

            arrayInit = new CodeArrayCreateExpression(field.Type, deflatedBytes.Length);
            foreach (byte b in deflatedBytes)
            {
                arrayInit.Initializers.Add(new CodePrimitiveExpression(b));
            }
            field.InitExpression = arrayInit;

            resourceType.Members.Add(field);

            #endregion private static readonly byte[] DeflatedBytes

            #region string IOptimizedResult.Source { get; }

            // add a readonly property with the original resource source
            CodeMemberProperty property = new CodeMemberProperty();
            property.Name = "Source";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult));
            property.HasGet = true;

            // get { return debugProxyOutput; }
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(debugProxyOutput)));
            resourceType.Members.Add(property);

            #endregion string IOptimizedResult.Source { get; }

            #region string IOptimizedResult.PrettyPrinted { get; }

            // add a readonly property with the debug proxy code string
            property      = new CodeMemberProperty();
            property.Name = "PrettyPrinted";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult));
            property.HasGet = true;

            // get { return ((IOptimizedResult)this).Source; }
            CodeExpression thisRef = new CodeCastExpression(typeof(IOptimizedResult), new CodeThisReferenceExpression());
            CodePropertyReferenceExpression sourceProperty = new CodePropertyReferenceExpression(thisRef, "Source");
            property.GetStatements.Add(new CodeMethodReturnStatement(sourceProperty));
            resourceType.Members.Add(property);

            #endregion string IOptimizedResult.PrettyPrinted { get; }

            #region string IOptimizedResult.Compacted { get; }

            // add a readonly property with the proxy code string
            property      = new CodeMemberProperty();
            property.Name = "Compacted";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult));
            property.HasGet = true;
            // get { return proxyOutput; }
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(proxyOutput)));
            resourceType.Members.Add(property);

            #endregion string IOptimizedResult.Compacted { get; }

            #region byte[] IOptimizedResult.Gzipped { get; }

            // add a readonly property with the gzipped proxy code
            property      = new CodeMemberProperty();
            property.Name = "Gzipped";
            property.Type = new CodeTypeReference(typeof(byte[]));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult));
            property.HasGet = true;
            // get { return GzippedBytes; }
            property.GetStatements.Add(new CodeMethodReturnStatement(
                                           new CodeFieldReferenceExpression(
                                               new CodeTypeReferenceExpression(this.ResourceTypeName),
                                               "GzippedBytes")));
            resourceType.Members.Add(property);

            #endregion byte[] IOptimizedResult.Gzipped { get; }

            #region byte[] IOptimizedResult.Deflated { get; }

            // add a readonly property with the deflated proxy code
            property      = new CodeMemberProperty();
            property.Name = "Deflated";
            property.Type = new CodeTypeReference(typeof(byte[]));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult));
            property.HasGet = true;
            // get { return DeflatedBytes; }
            property.GetStatements.Add(new CodeMethodReturnStatement(
                                           new CodeFieldReferenceExpression(
                                               new CodeTypeReferenceExpression(this.ResourceTypeName),
                                               "DeflatedBytes")));
            resourceType.Members.Add(property);

            #endregion byte[] IOptimizedResult.Deflated { get; }

            #region string IBuildResultMeta.Hash { get; }

            // add a readonly property with the hash of the resource data
            property      = new CodeMemberProperty();
            property.Name = "Hash";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult));
            property.HasGet = true;
            // get { return hash; }

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(hash)));
            resourceType.Members.Add(property);

            #endregion string IBuildResultMeta.Hash { get; }

            #region string IBuildResultMeta.ContentType { get; }

            // add a readonly property with the MIME of the resource data
            property      = new CodeMemberProperty();
            property.Name = "ContentType";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult));
            property.HasGet = true;
            // get { return ScriptResourceCodeProvider.MimeType; }

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.MimeType)));
            resourceType.Members.Add(property);

            #endregion string IBuildResultMeta.ContentType { get; }

            #region string IBuildResultMeta.FileExtension { get; }

            // add a readonly property with the extension of the resource data
            property      = new CodeMemberProperty();
            property.Name = "FileExtension";
            property.Type = new CodeTypeReference(typeof(String));
            property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult));
            property.HasGet = true;
            // get { return ScriptResourceCodeProvider.FileExt; }

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.FileExt)));
            resourceType.Members.Add(property);

            #endregion string IBuildResultMeta.FileExtension { get; }

            #region public Type IJrpcServiceInfo.ServiceType { get; }

            // add a static field with the service type
            property            = new CodeMemberProperty();
            property.Name       = "ServiceType";
            property.Type       = new CodeTypeReference(typeof(Type));
            property.Attributes = MemberAttributes.Public;
            property.ImplementationTypes.Add(new CodeTypeReference(typeof(IJsonServiceInfo)));
            property.HasGet = true;
            // get { return typeof(serviceType); }
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeOfExpression(serviceType.FullName)));
            resourceType.Members.Add(property);

            #endregion public Type IJrpcServiceInfo.ServiceType { get; }

            #region object IJrpcServiceInfo.CreateService();

            CodeMemberMethod codeMethod = new CodeMemberMethod();
            codeMethod.Name = "CreateService";
            codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo));
            codeMethod.ReturnType = new CodeTypeReference(typeof(Object));
            // return new serviceType();
            codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(serviceType)));
            resourceType.Members.Add(codeMethod);

            #endregion object IJrpcServiceInfo.CreateService();

            #region MethodInfo IJrpcServiceInfo.ResolveMethodName(string name);

            codeMethod      = new CodeMemberMethod();
            codeMethod.Name = "ResolveMethodName";
            codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo));
            codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name"));
            codeMethod.ReturnType = new CodeTypeReference(typeof(MethodInfo));
            CodeVariableReferenceExpression nameParam = new CodeVariableReferenceExpression("name");

            // if (String.IsNullOrEmpty(name)) { return null; }
            CodeConditionStatement nullCheck = new CodeConditionStatement();
            nullCheck.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam);
            nullCheck.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
            codeMethod.Statements.Add(nullCheck);

            Dictionary <string, MethodInfo> methodMap = JsonServiceBuildProvider.CreateMethodMap(serviceType);
            foreach (string name in methodMap.Keys)
            {
                CodeConditionStatement nameTest = new CodeConditionStatement();
                // if (String.Equals(name, methodName)) { ... }
                nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam, new CodePrimitiveExpression(name));

                // this.ServiceType
                CodePropertyReferenceExpression serviceTypeRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ServiceType");

                // method name
                CodePrimitiveExpression methodNameRef = new CodePrimitiveExpression(methodMap[name].Name);

                // this.ServiceType.GetMethod(methodNameRef)
                CodeMethodInvokeExpression methodInfoRef = new CodeMethodInvokeExpression(serviceTypeRef, "GetMethod", methodNameRef);

                // return MethodInfo;
                nameTest.TrueStatements.Add(new CodeMethodReturnStatement(methodInfoRef));
                codeMethod.Statements.Add(nameTest);
            }

            codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
            resourceType.Members.Add(codeMethod);

            #endregion MethodInfo IJrpcServiceInfo.ResolveMethodName(string name);

            #region string[] IJrpcServiceInfo.GetMethodParams(string name);

            codeMethod      = new CodeMemberMethod();
            codeMethod.Name = "GetMethodParams";
            codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo));
            codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name"));
            codeMethod.ReturnType = new CodeTypeReference(typeof(String[]));
            CodeVariableReferenceExpression nameParam2 = new CodeVariableReferenceExpression("name");

            // if (String.IsNullOrEmpty(name)) { return new string[0]; }
            CodeConditionStatement nullCheck2 = new CodeConditionStatement();
            nullCheck2.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam);
            nullCheck2.TrueStatements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0)));
            codeMethod.Statements.Add(nullCheck2);

            foreach (MethodInfo method in methodMap.Values)
            {
                string[] paramMap = JsonServiceBuildProvider.CreateParamMap(method);

                if (paramMap.Length < 1)
                {
                    continue;
                }

                CodeConditionStatement nameTest = new CodeConditionStatement();
                // if (String.Equals(name, method.Name)) { ... }
                nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam2, new CodePrimitiveExpression(method.Name));

                // = {...}
                CodePrimitiveExpression[] paramList = new CodePrimitiveExpression[paramMap.Length];
                for (int i = 0; i < paramMap.Length; i++)
                {
                    paramList[i] = new CodePrimitiveExpression(paramMap[i]);
                }

                // new string[] = {...}
                CodeArrayCreateExpression paramArray = new CodeArrayCreateExpression(typeof(String[]), paramList);

                // return string[];
                nameTest.TrueStatements.Add(new CodeMethodReturnStatement(paramArray));
                codeMethod.Statements.Add(nameTest);
            }

            codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0)));
            resourceType.Members.Add(codeMethod);

            #endregion string[] IJrpcServiceInfo.GetMethodParams(string name);

            if (this.VirtualPathDependencies.Count > 0)
            {
                resourceType.BaseTypes.Add(typeof(IDependentResult));

                #region private static readonly string[] Dependencies

                field            = new CodeMemberField();
                field.Name       = "Dependencies";
                field.Type       = new CodeTypeReference(typeof(string[]));
                field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;

                arrayInit = new CodeArrayCreateExpression(field.Type, this.VirtualPathDependencies.Count);
                foreach (string key in this.VirtualPathDependencies)
                {
                    arrayInit.Initializers.Add(new CodePrimitiveExpression(key));
                }
                field.InitExpression = arrayInit;

                resourceType.Members.Add(field);

                #endregion private static readonly string[] Dependencies

                #region IEnumerable<string> IDependentResult.VirtualPathDependencies { get; }

                // add a readonly property returning the static data
                property      = new CodeMemberProperty();
                property.Name = "VirtualPathDependencies";
                property.Type = new CodeTypeReference(typeof(IEnumerable <string>));
                property.PrivateImplementationType = new CodeTypeReference(typeof(IDependentResult));
                property.HasGet = true;
                // get { return Dependencies; }
                property.GetStatements.Add(new CodeMethodReturnStatement(
                                               new CodeFieldReferenceExpression(
                                                   new CodeTypeReferenceExpression(resourceType.Name),
                                                   "Dependencies")));
                resourceType.Members.Add(property);

                #endregion IEnumerable<string> IDependentResult.VirtualPathDependencies { get; }
            }

            // Generate _ASP FastObjectFactory
            assemblyBuilder.GenerateTypeFactory(this.ResourceFullName);

            assemblyBuilder.AddCodeCompileUnit(this, generatedUnit);
        }
Beispiel #15
0
 protected override void GenerateSpecifierMember(CodeMemberField codeField)
 {
     AddCustomAttribute(codeField, "System.Xml.Serialization.XmlIgnore");
 }
Beispiel #16
0
 private void PostEnumMemberHook(Smoke* smoke, Smoke.Method* smokeMethod, CodeMemberField cmm, CodeTypeDeclaration type)
 {
     CodeTypeDeclaration parentType = this.memberDocumentation.Keys.FirstOrDefault(t => t.Name == (string) type.UserData["parent"]);
     if (parentType != null)
     {
         IList<string> docs = this.memberDocumentation[parentType];
         string typeName = Regex.Escape(parentType.Name) + "::" + Regex.Escape(type.Name);
         if (type.Comments.Count == 0)
         {
             for (int i = 0; i < docs.Count; i++)
             {
                 const string enumDoc = @"enum {0}(\s*flags {1}::\w+\s+)?(?<docsStart>.*?)(\n){{3}}";
                 Match matchEnum = Regex.Match(docs[i], string.Format(enumDoc, typeName, parentType.Name), RegexOptions.Singleline);
                 if (matchEnum.Success)
                 {
                     string doc = (matchEnum.Groups["docsStart"].Value + matchEnum.Groups["docsEnd1"].Value).Trim();
                     doc = Regex.Replace(doc,
                                         @"(The \S+ type is a typedef for QFlags<\S+>\. It stores an OR combination of \S+ values\.)",
                                         string.Empty);
                     doc = Regex.Replace(doc,
                                         @"ConstantValue(Description)?.*?(((\n){2})|$)",
                                         string.Empty, RegexOptions.Singleline).Trim();
                     if (!string.IsNullOrEmpty(doc))
                     {
                         Util.FormatComment(doc, type, i > 0);
                         break;
                     }
                 }
             }
         }
         string memberName = Regex.Escape(parentType.Name) + "::" +
                             Regex.Escape(ByteArrayManager.GetString(smoke->methodNames[smokeMethod->name]));
         const string memberDoc = @"enum {0}.*{1}\t[^\t\n]+\t(?<docs>.*?)(&\w+;)?(\n)";
         for (int i = 0; i < docs.Count; i++)
         {
             Match match = Regex.Match(docs[i], string.Format(memberDoc, typeName, memberName), RegexOptions.Singleline);
             if (match.Success)
             {
                 string doc = match.Groups["docs"].Value.Trim();
                 if (!string.IsNullOrEmpty(doc))
                 {
                     Util.FormatComment(char.ToUpper(doc[0]) + doc.Substring(1), cmm, i > 0);
                     break;
                 }
             }
         }
     }
 }
        public CodeCompileUnit CreateCodeCompileUnit(CompositeClass compositeClass)
        {
            CodeCompileUnit unit = new CodeCompileUnit();
            CodeNamespace   ns   = new CodeNamespace(GetNamespace(compositeClass.RootNamespace));

            foreach (string newNamespace in compositeClass.Namespaces)
            {
                CodeNamespaceImport import = new CodeNamespaceImport(newNamespace);
                ns.Imports.Add(import);
            }
            unit.Namespaces.Add(ns);

            CodeTypeDeclaration generatedClass = new CodeTypeDeclaration(GetClassName());

            generatedClass.IsClass        = true;
            generatedClass.IsPartial      = true;
            generatedClass.TypeAttributes = TypeAttributes.Public;
            ns.Types.Add(generatedClass);

            // add private fields
            foreach (CompositeType compositeType in compositeClass.Types)
            {
                CodeMemberField privateVariable = new CodeMemberField(compositeType.ClassName, compositeType.GetFieldName());
                privateVariable.Attributes = MemberAttributes.Private;
                generatedClass.Members.Add(privateVariable);
            }

            // add constructor
            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public;

            // add the parameters and field assignments
            foreach (CompositeType compositeType in compositeClass.Types)
            {
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(
                    compositeType.ClassName, compositeType.GetParameterName());
                ctor.Parameters.Add(param);

                // add field assignment
                CodeFieldReferenceExpression leftRef;
                leftRef = new CodeFieldReferenceExpression();
                //leftRef.TargetObject = new CodeThisReferenceExpression();
                leftRef.FieldName = compositeType.GetFieldName();

                CodeFieldReferenceExpression rightRef;
                rightRef = new CodeFieldReferenceExpression();
                //rightRef.TargetObject = new CodeThisReferenceExpression();
                rightRef.FieldName = compositeType.GetParameterName();

                CodeAssignStatement assign = new CodeAssignStatement();
                assign.Left  = leftRef;
                assign.Right = rightRef;

                ctor.Statements.Add(assign);
            }
            generatedClass.Members.Add(ctor);

            // add properties
            foreach (CompositeType compositeType in compositeClass.Types)
            {
                foreach (CompositeProperty property in compositeType.Properties)
                {
                    AttachProperty(generatedClass, compositeType, property);
                }
            }

            return(unit);
        }
Beispiel #18
0
        private static void ProvideNestedClassProperty(CodeTypeMemberCollection members, CodeTypeReference nestRef, CodeMemberField toStringHelperField)
        {
            CodeMemberProperty property = new CodeMemberProperty {
                Type       = nestRef,
                Name       = "ToStringHelper",
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), toStringHelperField.Name)));
            property.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "ToString Helpers"));
            members.Add(property);
        }
 private CodeMemberField CreateFieldMember (String strFieldName, long strFieldValue){
     CodeMemberField field = new CodeMemberField (typeof (UInt64), strFieldName);
     field.InitExpression = new CodePrimitiveExpression (strFieldValue);
     return field;
 }
Beispiel #20
0
        private void ImproveCodeDom(CodeNamespace codeNamespace, XmlSchema schema)
        {
            var nonElementAttributes = new HashSet <string>(new[]
            {
                "System.Xml.Serialization.XmlAttributeAttribute",
                "System.Xml.Serialization.XmlIgnoreAttribute",
                "System.Xml.Serialization.XmlTextAttribute",
            });

            var nullValue = new CodePrimitiveExpression();

            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            if (Options.UsingNamespaces != null)
            {
                foreach (var ns in Options.UsingNamespaces)
                {
                    codeNamespace.Imports.Add(new CodeNamespaceImport(ns));
                }
            }

            var neverBrowsableAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsable",
                                                                       new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.ComponentModel.EditorBrowsableState"), "Never")));

            var removedTypes = new List <CodeTypeDeclaration>();

            var changedTypeNames = new Dictionary <string, string>();
            var newTypeNames     = new HashSet <string>();

            if (Options.UseXLinq)
            {
                changedTypeNames.Add("System.Xml.XmlNode", "System.Xml.Linq.XNode");
                changedTypeNames.Add("System.Xml.XmlElement", "System.Xml.Linq.XElement");
                changedTypeNames.Add("System.Xml.XmlAttribute", "System.Xml.Linq.XAttribute");
            }

            foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
            {
                if (Options.ExcludeImportedTypes && Options.Imports != null && Options.Imports.Count > 0)
                {
                    if (!ContainsTypeName(schema, codeType))
                    {
                        removedTypes.Add(codeType);
                        continue;
                    }
                }

                var attributesToRemove = new HashSet <CodeAttributeDeclaration>();
                foreach (CodeAttributeDeclaration att in codeType.CustomAttributes)
                {
                    if (Options.AttributesToRemove.Contains(att.Name))
                    {
                        attributesToRemove.Add(att);
                    }
                    else
                    {
                        switch (att.Name)
                        {
                        case "System.Xml.Serialization.XmlRootAttribute":
                            var nullableArgument = att.Arguments.Cast <CodeAttributeArgument>().FirstOrDefault(x => x.Name == "IsNullable");
                            if (nullableArgument != null && (bool)((CodePrimitiveExpression)nullableArgument.Value).Value)
                            {
                                // Remove nullable root attribute
                                attributesToRemove.Add(att);
                            }
                            break;
                        }
                    }
                }

                foreach (var att in attributesToRemove)
                {
                    codeType.CustomAttributes.Remove(att);
                }

                if (Options.TypeNameCapitalizer != null)
                {
                    var newName = Options.TypeNameCapitalizer.Capitalize(codeNamespace, codeType);
                    if (newName != codeType.Name)
                    {
                        SetAttributeOriginalName(codeType, codeType.GetOriginalName(), "System.Xml.Serialization.XmlTypeAttribute");
                        var newNameToAdd = newName;
                        var index        = 0;
                        while (!newTypeNames.Add(newNameToAdd))
                        {
                            index       += 1;
                            newNameToAdd = string.Format("{0}{1}", newName, index);
                        }
                        changedTypeNames.Add(codeType.Name, newNameToAdd);
                        codeType.Name = newNameToAdd;
                    }
                }

                var members = new Dictionary <string, CodeTypeMember>();
                foreach (CodeTypeMember member in codeType.Members)
                {
                    members[member.Name] = member;
                }

                if (Options.EnableDataBinding && codeType.IsClass && codeType.BaseTypes.Count == 0)
                {
                    codeType.BaseTypes.Add(typeof(object));
                    codeType.BaseTypes.Add(typeof(INotifyPropertyChanged));

                    codeType.Members.Add(new CodeMemberEvent()
                    {
                        Name = "PropertyChanged",
                        ImplementationTypes = { typeof(INotifyPropertyChanged) },
                        Attributes          = MemberAttributes.Public,
                        Type = new CodeTypeReference(typeof(PropertyChangedEventHandler))
                    });

                    codeType.Members.Add(new CodeMemberMethod()
                    {
                        Name       = "RaisePropertyChanged",
                        Attributes = MemberAttributes.Family | MemberAttributes.Final,
                        Parameters =
                        {
                            new CodeParameterDeclarationExpression(typeof(string), "propertyName")
                        },
                        Statements =
                        {
                            new CodeVariableDeclarationStatement(typeof(PropertyChangedEventHandler),                                                                                "propertyChanged",
                                                                 new CodeEventReferenceExpression(new CodeThisReferenceExpression(),                                                 "PropertyChanged")),
                            new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("propertyChanged"),                                      CodeBinaryOperatorType.IdentityInequality,nullValue),
                                                       new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeVariableReferenceExpression("propertyChanged"),
                                                                                                                    new CodeThisReferenceExpression(),
                                                                                                                    new CodeObjectCreateExpression(typeof(PropertyChangedEventArgs), new CodeArgumentReferenceExpression("propertyName")))))
                        }
                    });
                }

                bool mixedContentDetected = Options.MixedContent && members.ContainsKey("textField") && members.ContainsKey("itemsField");

                var orderIndex = 0;
                foreach (CodeTypeMember member in members.Values)
                {
                    if (member is CodeMemberField)
                    {
                        CodeMemberField field = (CodeMemberField)member;

                        if (mixedContentDetected)
                        {
                            switch (field.Name)
                            {
                            case "textField":
                                codeType.Members.Remove(member);
                                continue;

                            case "itemsField":
                                field.Type = new CodeTypeReference(typeof(object[]));
                                break;
                            }
                        }

                        if (Options.UseLists && field.Type.ArrayRank > 0)
                        {
                            CodeTypeReference type = new CodeTypeReference(typeof(List <>))
                            {
                                TypeArguments =
                                {
                                    field.Type.ArrayElementType
                                }
                            };

                            field.Type = type;
                        }

                        if (codeType.IsEnum && Options.EnumValueCapitalizer != null)
                        {
                            var newName = Options.EnumValueCapitalizer.Capitalize(codeNamespace, member);
                            if (newName != member.Name)
                            {
                                SetAttributeOriginalName(member, member.GetOriginalName(), "System.Xml.Serialization.XmlEnumAttribute");
                                member.Name = newName;
                            }
                        }
                    }

                    if (member is CodeMemberProperty)
                    {
                        CodeMemberProperty property = (CodeMemberProperty)member;

                        // Is this "*Specified" property part of a "propertyName" and "propertyNameSpecified" combination?
                        var isSpecifiedProperty = property.Name.EndsWith("Specified") && members.ContainsKey(property.Name.Substring(0, property.Name.Length - 9));

                        if (mixedContentDetected)
                        {
                            switch (property.Name)
                            {
                            case "Text":
                                codeType.Members.Remove(member);
                                continue;

                            case "Items":
                                property.Type = new CodeTypeReference(typeof(object[]));
                                property.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlTextAttribute", new CodeAttributeArgument {
                                    Name = "", Value = new CodeTypeOfExpression(new CodeTypeReference(typeof(string)))
                                }));
                                break;
                            }
                        }

                        if (Options.UseLists && property.Type.ArrayRank > 0)
                        {
                            CodeTypeReference type = new CodeTypeReference(typeof(List <>))
                            {
                                TypeArguments =
                                {
                                    property.Type.ArrayElementType
                                }
                            };

                            property.Type = type;
                        }

                        bool capitalizeProperty;
                        if (!isSpecifiedProperty)
                        {
                            if (Options.UseNullableTypes)
                            {
                                var            fieldName = GetFieldName(property.Name, "Field");
                                CodeTypeMember specified;
                                if (members.TryGetValue(property.Name + "Specified", out specified))
                                {
                                    var nullableProperty = new CodeMemberProperty
                                    {
                                        Name = property.Name,
                                        Type = new CodeTypeReference(typeof(Nullable <>))
                                        {
                                            TypeArguments = { property.Type.BaseType }
                                        },
                                        HasGet     = true,
                                        HasSet     = true,
                                        Attributes = MemberAttributes.Public | MemberAttributes.Final
                                    };

                                    nullableProperty.GetStatements.Add(
                                        new CodeConditionStatement(new CodeVariableReferenceExpression(fieldName + "Specified"),
                                                                   new CodeStatement[] { new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName)) },
                                                                   new CodeStatement[] { new CodeMethodReturnStatement(new CodePrimitiveExpression()) }
                                                                   ));

                                    nullableProperty.SetStatements.Add(
                                        new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodePropertySetValueReferenceExpression(), CodeBinaryOperatorType.IdentityInequality, nullValue),
                                                                   new CodeStatement[]
                                    {
                                        new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName + "Specified"),
                                                                new CodePrimitiveExpression(true)),
                                        new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName),
                                                                new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(), "Value")),
                                    },
                                                                   new CodeStatement[]
                                    {
                                        new CodeAssignStatement(
                                            new CodeVariableReferenceExpression(fieldName + "Specified"),
                                            new CodePrimitiveExpression(false)),
                                    }
                                                                   ));

                                    nullableProperty.CustomAttributes.Add(new CodeAttributeDeclaration
                                    {
                                        Name = "System.Xml.Serialization.XmlIgnoreAttribute"
                                    });

                                    codeType.Members.Add(nullableProperty);

                                    foreach (CodeAttributeDeclaration attribute in property.CustomAttributes)
                                    {
                                        if (attribute.Name == "System.Xml.Serialization.XmlAttributeAttribute")
                                        {
                                            attribute.Arguments.Add(new CodeAttributeArgument
                                            {
                                                Name  = "AttributeName",
                                                Value = new CodePrimitiveExpression(property.Name)
                                            });
                                        }
                                    }

                                    property.Name  = "_" + property.Name;
                                    specified.Name = "_" + specified.Name;

                                    if (Options.HideUnderlyingNullableProperties)
                                    {
                                        property.CustomAttributes.Add(neverBrowsableAttribute);
                                        specified.CustomAttributes.Add(neverBrowsableAttribute);
                                    }

                                    property = nullableProperty;
                                }
                            }

                            if (Options.PreserveOrder)
                            {
                                if (!property.CustomAttributes.Cast <CodeAttributeDeclaration>().Any(x => nonElementAttributes.Contains(x.Name)))
                                {
                                    var elementAttributes = property
                                                            .CustomAttributes.Cast <CodeAttributeDeclaration>()
                                                            .Where(x => x.Name == "System.Xml.Serialization.XmlElementAttribute")
                                                            .ToList();
                                    if (elementAttributes.Count == 0)
                                    {
                                        var elementAttribute = new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute");
                                        property.CustomAttributes.Add(elementAttribute);
                                        elementAttributes.Add(elementAttribute);
                                    }

                                    foreach (var elementAttribute in elementAttributes)
                                    {
                                        elementAttribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(orderIndex)));
                                    }

                                    orderIndex += 1;
                                }
                            }

                            if (Options.EnableDataBinding)
                            {
                                property.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "RaisePropertyChanged", new CodePrimitiveExpression(property.Name)));
                            }

                            capitalizeProperty = Options.PropertyNameCapitalizer != null;
                        }
                        else if (!Options.UseNullableTypes)
                        {
                            if (Options.EnableDataBinding)
                            {
                                property.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "RaisePropertyChanged", new CodePrimitiveExpression(property.Name)));
                            }

                            capitalizeProperty = Options.PropertyNameCapitalizer != null;
                        }
                        else
                        {
                            capitalizeProperty = false;
                        }

                        if (capitalizeProperty)
                        {
                            var newName = Options.PropertyNameCapitalizer.Capitalize(codeNamespace, property);
                            if (newName != property.Name)
                            {
                                SetAttributeOriginalName(property, property.GetOriginalName(), "System.Xml.Serialization.XmlElementAttribute");
                                property.Name = newName;
                            }
                        }
                    }
                }
            }

            // Remove types
            foreach (var rt in removedTypes)
            {
                codeNamespace.Types.Remove(rt);
            }

            // Fixup changed type names
            if (changedTypeNames.Count != 0)
            {
                foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
                {
                    if (codeType.IsEnum)
                    {
                        continue;
                    }

                    FixAttributeTypeReference(changedTypeNames, codeType);

                    foreach (CodeTypeMember member in codeType.Members)
                    {
                        var memberField = member as CodeMemberField;
                        if (memberField != null)
                        {
                            FixTypeReference(changedTypeNames, memberField.Type);
                            FixAttributeTypeReference(changedTypeNames, memberField);
                        }

                        var memberProperty = member as CodeMemberProperty;
                        if (memberProperty != null)
                        {
                            FixTypeReference(changedTypeNames, memberProperty.Type);
                            FixAttributeTypeReference(changedTypeNames, memberProperty);
                        }
                    }
                }
            }
        }
Beispiel #21
0
 internal CodeMemberField Field(string fieldName, CodeExpression initializer)
 {
     var field = new CodeMemberField(typeof(object), fieldName)
     {
         Attributes = MemberAttributes.Public,
         InitExpression = initializer,
     };
     CurrentType.Members.Add(field);
     return field;
 }
Beispiel #22
0
        public void Generate()
        {
            if (this.visitor.NativeMethods == null)
            {
                return;
            }

            // Create the I{Name}Api interface
            CodeTypeDeclaration nativeInterface = new CodeTypeDeclaration();

            nativeInterface.Name        = $"I{this.generator.Name}Api";
            nativeInterface.IsInterface = true;
            nativeInterface.IsPartial   = true;
            nativeInterface.Attributes |= MemberAttributes.Public;

            // Create the {Name}Api class
            CodeTypeDeclaration nativeClass = new CodeTypeDeclaration();

            nativeClass.Name = $"{this.generator.Name}Api";
            nativeClass.BaseTypes.Add(nativeInterface.Name);
            nativeClass.IsPartial   = true;
            nativeClass.Attributes |= MemberAttributes.Public;

            // Create the "Parent" property for the API & the interface,
            CodeMemberProperty parentInterfaceProperty = new CodeMemberProperty();

            parentInterfaceProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            parentInterfaceProperty.Comments.Add(new CodeCommentStatement($"Gets or sets the <see cref=\"ILibiMobileDeviceApi\"/> which owns this <see cref=\"{this.generator.Name}\"/>.", true));
            parentInterfaceProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            parentInterfaceProperty.Name       = "Parent";
            parentInterfaceProperty.Type       = new CodeTypeReference("ILibiMobileDevice");
            parentInterfaceProperty.HasGet     = true;
            parentInterfaceProperty.Attributes = MemberAttributes.Final;

            nativeInterface.Members.Add(parentInterfaceProperty);

            CodeMemberField parentField = new CodeMemberField();

            parentField.Comments.Add(new CodeCommentStatement("<summary>", true));
            parentField.Comments.Add(new CodeCommentStatement("Backing field for the <see cref=\"Parent\"/> property", true));
            parentField.Comments.Add(new CodeCommentStatement("</summary>", true));
            parentField.Name        = "parent";
            parentField.Type        = new CodeTypeReference("ILibiMobileDevice");
            parentField.Attributes |= MemberAttributes.Private | MemberAttributes.Final;
            nativeClass.Members.Add(parentField);

            CodeMemberProperty parentProperty = new CodeMemberProperty();

            parentProperty.Comments.Add(new CodeCommentStatement("<inheritdoc/>", true));
            parentProperty.Name = "Parent";
            parentProperty.Type = new CodeTypeReference("ILibiMobileDevice");
            parentProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "parent")));
            parentProperty.Attributes |= MemberAttributes.Public;
            nativeClass.Members.Add(parentProperty);

            CodeConstructor constructor = new CodeConstructor();

            constructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            constructor.Comments.Add(new CodeCommentStatement($"Initializes a new instance of the <see cref=\"{nativeClass.Name}\"/> class", true));
            constructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            constructor.Comments.Add(new CodeCommentStatement("<param name=\"parent\">", true));
            constructor.Comments.Add(new CodeCommentStatement($"The <see cref=\"ILibiMobileDeviceApi\"/> which owns this <see cref=\"{this.generator.Name}\"/>.", true));
            constructor.Comments.Add(new CodeCommentStatement("</param>", true));
            constructor.Attributes = MemberAttributes.Public;
            constructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference("ILibiMobileDevice"),
                    "parent"));
            constructor.Statements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "parent"),
                    new CodeArgumentReferenceExpression("parent")));
            nativeClass.Members.Add(constructor);

            foreach (var method in this.visitor.NativeMethods.Members.OfType <CodeMemberMethod>())
            {
                if (method is CodeTypeConstructor || method is CodeTypeConstructor)
                {
                    continue;
                }

                var interfaceMethod = new CodeMemberMethod();
                interfaceMethod.Name       = method.Name;
                interfaceMethod.ReturnType = method.ReturnType;
                interfaceMethod.Comments.AddRange(method.Comments);

                var classMethod = new CodeMemberMethod();
                classMethod.Name       = method.Name;
                classMethod.ReturnType = method.ReturnType;
                classMethod.Comments.AddRange(method.Comments);
                classMethod.Attributes = MemberAttributes.Public;

                var nativeInvocation = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(this.visitor.NativeMethods.Name),
                        method.Name));

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

                foreach (var parameter in method.Parameters.OfType <CodeParameterDeclarationExpression>())
                {
                    var interfaceParameter = new CodeParameterDeclarationExpression();
                    interfaceParameter.Name      = parameter.Name;
                    interfaceParameter.Direction = parameter.Direction;
                    interfaceParameter.Type      = parameter.Type;

                    interfaceMethod.Parameters.Add(interfaceParameter);

                    var classParameter = new CodeParameterDeclarationExpression();
                    classParameter.Name      = parameter.Name;
                    classParameter.Direction = parameter.Direction;
                    classParameter.Type      = parameter.Type;

                    classMethod.Parameters.Add(classParameter);

                    var argumentRef = new CodeArgumentReferenceExpression(parameter.Name);
                    nativeInvocation.Parameters.Add(new CodeDirectionExpression(parameter.Direction, argumentRef));
                }

                if ((method.ReturnType == null || method.ReturnType.BaseType == "System.Void") &&
                    method.Name.StartsWith("plist") &&
                    (method.Name.EndsWith("set_item") || method.Name.EndsWith("insert_item")) &&
                    method.Parameters.OfType <CodeParameterDeclarationExpression>().Any(a => a.Name == "item"))
                {
                    // The plist API has set_item and insert_item methods such as plist_dict_insert_item
                    // When these methods are called, the parent dictionary takes ownership of the handles and releases them.
                    // The safe handles no longer need to free the memory (either it has been freed by the dict and the memory
                    // is invalid, or it is still in use by the dict and we can't free it yet); so call .SetHandleAsInvalid on those handles
                    classMethod.Statements.Add(nativeInvocation);

                    // Add item.SetHandleAsInvalid();
                    classMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("item"), "SetHandleAsInvalid"));
                }
                else
                {
                    // If there are return values or "out" parameters which are safe handles, we should special case.
                    // Otherwise, just call the method and return the result
                    if (!method.Parameters.OfType <CodeParameterDeclarationExpression>().Any(
                            p => p.Direction == FieldDirection.Out &&
                            p.Type.BaseType.EndsWith("Handle")) &&
                        !method.ReturnType.BaseType.EndsWith("Handle"))
                    {
                        if (hasReturnValue)
                        {
                            classMethod.Statements.Add(
                                new CodeMethodReturnStatement(
                                    nativeInvocation));
                        }
                        else
                        {
                            classMethod.Statements.Add(nativeInvocation);
                        }
                    }
                    else
                    {
                        if (hasReturnValue)
                        {
                            // Store the result in a variable and perform the invoke
                            classMethod.Statements.Add(
                                new CodeVariableDeclarationStatement(
                                    method.ReturnType,
                                    "returnValue"));

                            classMethod.Statements.Add(
                                new CodeAssignStatement(
                                    new CodeVariableReferenceExpression("returnValue"),
                                    nativeInvocation));
                        }
                        else
                        {
                            classMethod.Statements.Add(nativeInvocation);
                        }

                        // For all "out" parameters which are safehandles, update the .Api property pointing
                        // to this instance of the API - making sure the same API which created the safe handle
                        // will also release it. Useful when mocking multiple APIs in parallel (e.g. Xunit).
                        foreach (var parameter in method.Parameters.OfType <CodeParameterDeclarationExpression>())
                        {
                            if (parameter.Direction == FieldDirection.Out && parameter.Type.BaseType.EndsWith("Handle"))
                            {
                                classMethod.Statements.Add(
                                    new CodeAssignStatement(
                                        new CodePropertyReferenceExpression(
                                            new CodeVariableReferenceExpression(parameter.Name),
                                            "Api"),
                                        new CodePropertyReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "Parent")));
                            }
                        }

                        // The same also applies to the return value - if it is a safe handle, update the. Api property
                        if (hasReturnValue)
                        {
                            if (method.ReturnType.BaseType.EndsWith("Handle"))
                            {
                                classMethod.Statements.Add(
                                    new CodeAssignStatement(
                                        new CodePropertyReferenceExpression(
                                            new CodeVariableReferenceExpression("returnValue"),
                                            "Api"),
                                        new CodePropertyReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "Parent")));
                            }

                            classMethod.Statements.Add(
                                new CodeMethodReturnStatement(
                                    new CodeVariableReferenceExpression("returnValue")));
                        }
                    }
                }

                nativeInterface.Members.Add(interfaceMethod);
                nativeClass.Members.Add(classMethod);
            }

            this.generator.AddType(nativeInterface.Name, new CodeDomGeneratedType(nativeInterface));
            this.generator.AddType(nativeClass.Name, new CodeDomGeneratedType(nativeClass));
        }
Beispiel #23
0
    string FindProxyTypeAndAugmentCodeDom(CodeNamespace codeNamespace) {
        // add new type containing Type properties for each type
        // in the web service proxy assembly (kind of a namespace)
        string nsName = string.Format("ws_namespace_{0:x}", Guid.NewGuid().GetHashCode());
        CodeTypeDeclaration nsType = new CodeTypeDeclaration(nsName);

        CodeTypeDeclaration wsType = null; // the web service type (only one)

        foreach (CodeTypeDeclaration t in codeNamespace.Types) {
            string name = t.Name;

            // find the one derived from SoapHttpClientProtocol
            foreach (CodeTypeReference baseType in t.BaseTypes) {
                if (baseType.BaseType == typeof(SoapHttpClientProtocol).FullName) {
                    if (wsType != null) {
                        throw new InvalidDataException("Found more than one web service proxy type.");
                    }

                    wsType = t;
                }
            }

            // add the corresponding property to the namespace type
            CodeMemberProperty p = new CodeMemberProperty();
            p.Attributes &= ~MemberAttributes.AccessMask;
            p.Attributes |= MemberAttributes.Public;
            p.Name = name; // same as type name
            p.Type = new CodeTypeReference(typeof(DynamicType));
            p.GetStatements.Add(new CodeMethodReturnStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(Ops)),
                        "GetDynamicTypeFromType"),
                    new CodeTypeOfExpression(name))));
            nsType.Members.Add(p);
        }

        if (wsType == null) {
            // must have exactly one ws proxy
            throw new InvalidDataException("Web service proxy type not found.");
        }

        codeNamespace.Types.Add(nsType);

        // add ServiceNamespace property of the above type to the proxy type
        CodeMemberField nsField = new CodeMemberField(nsName, "_serviceNamespace");
        nsField.Attributes &= ~MemberAttributes.AccessMask;
        nsField.Attributes |= MemberAttributes.Private;
        nsField.InitExpression = new CodeObjectCreateExpression(nsName);
        wsType.Members.Add(nsField);

        CodeMemberProperty nsProp = new CodeMemberProperty();
        nsProp.Attributes &= ~MemberAttributes.AccessMask;
        nsProp.Attributes |= MemberAttributes.Public;
        nsProp.Name = "ServiceNamespace";
        nsProp.Type = new CodeTypeReference(nsName);
        nsProp.GetStatements.Add(new CodeMethodReturnStatement(
            new CodePropertyReferenceExpression(
                new CodeThisReferenceExpression(),
                "_serviceNamespace")));
        wsType.Members.Add(nsProp);

        // return the proxy type name
        return wsType.Name;
    }
Beispiel #24
0
        public static void GenerateBackingField(
            this CodeMemberProperty property,
            CodeTypeDeclaration containingType,
            Object defaultValue
            )
        {
            if (containingType == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(containingType));
            }

            if (String.IsNullOrEmpty(property.Name))
            {
                throw Logger.Fatal.Argument(
                          nameof(property),
                          SR.CodeDomExtensions_PropertyNameNotSet
                          );
            }

            if (property.GetStatements.Any())
            {
                throw Logger.Fatal.Argument(
                          nameof(property),
                          SR.CodeDomExtensions_PropertyGetterNotEmpty
                          );
            }

            if (property.SetStatements.Any())
            {
                throw Logger.Fatal.Argument(
                          nameof(property),
                          SR.CodeDomExtensions_PropertySetterNotEmpty
                          );
            }

            var fieldName = "_" + ToCamelCase(property.Name);

            if (containingType.Members
                .Cast <CodeTypeMember>()
                .Any(member => member.Name == fieldName)
                )
            {
                throw Logger.Fatal.InvalidOperation(SR.CodeDomExtensions_FieldExists);
            }

            var isStatic = (property.Attributes & MemberAttributes.Static) == MemberAttributes.Static;

            var codeField = new CodeMemberField()
            {
                Name       = fieldName,
                Type       = property.Type,
                Attributes = MemberAttributes.Private | (isStatic ? MemberAttributes.Static : 0),
            };

            if (defaultValue != null)
            {
                codeField.InitExpression = CommandCodeGenerator.CreateLiteralExpression(defaultValue);
            }

            CreatePropertyGetterAndSetter(property, codeField.Name, CreateThisExpression(containingType, isStatic));

            containingType.Members.Add(codeField);
        }
        public void RegionsSnippetsAndLinePragmas()
        {
            CodeCompileUnit cu = new CodeCompileUnit();
            CodeNamespace ns = new CodeNamespace("Namespace1");

            cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
            cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cu.Namespaces.Add(ns);

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

            cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
            cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));

            CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
            CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
            field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
            field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
            field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberEvent evt1 = new CodeMemberEvent();
            evt1.Name = "Event1";
            evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
            evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            CodeMemberEvent evt2 = new CodeMemberEvent();
            evt2.Name = "Event2";
            evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
            evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
            evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method1.Statements.Add(
                new CodeDelegateInvokeExpression(
                    new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
                    new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));

            CodeMemberMethod method2 = new CodeMemberMethod();
            method2.Name = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.Statements.Add(
                new CodeDelegateInvokeExpression(
                    new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
                    new CodeExpression[] {
                    new CodeThisReferenceExpression(),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
            method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));

            method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
            method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeMemberProperty property1 = new CodeMemberProperty();
            property1.Name = "Property1";
            property1.Type = new CodeTypeReference(typeof(string));
            property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property1.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "field1")));

            CodeMemberProperty property2 = new CodeMemberProperty();
            property2.Name = "Property2";
            property2.Type = new CodeTypeReference(typeof(string));
            property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "field2")));

            property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
            property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeConstructor constructor1 = new CodeConstructor();
            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement conState1 = new CodeAssignStatement(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "field1"),
                                        new CodePrimitiveExpression("value1"));
            conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
            constructor1.Statements.Add(conState1);
            CodeStatement conState2 = new CodeAssignStatement(
                                        new CodeFieldReferenceExpression(
                                            new CodeThisReferenceExpression(),
                                            "field2"),
                                        new CodePrimitiveExpression("value2"));
            conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            constructor1.Statements.Add(conState2);

            constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
            constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeConstructor constructor2 = new CodeConstructor();
            constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
            constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));

            CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();

            typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
            typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

            CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
            CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
            nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
            nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));

            nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
            nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            CodeTypeDelegate delegate1 = new CodeTypeDelegate();
            delegate1.Name = "nestedDelegate1";
            delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
            delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));

            CodeTypeDelegate delegate2 = new CodeTypeDelegate();
            delegate2.Name = "nestedDelegate2";
            delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
            delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));

            delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
            delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            var snippet1 = new CodeSnippetTypeMember();
            var snippet2 = new CodeSnippetTypeMember();

            CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet2.StartDirectives.Add(regionStart);
            snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            cd.Members.Add(field1);
            cd.Members.Add(method1);
            cd.Members.Add(constructor1);
            cd.Members.Add(property1);
            cd.Members.Add(methodMain);

            cd.Members.Add(evt1);
            cd.Members.Add(nestedClass1);
            cd.Members.Add(delegate1);

            cd.Members.Add(snippet1);

            cd.Members.Add(field2);
            cd.Members.Add(method2);
            cd.Members.Add(constructor2);
            cd.Members.Add(property2);

            cd.Members.Add(typeConstructor2);
            cd.Members.Add(evt2);
            cd.Members.Add(nestedClass2);
            cd.Members.Add(delegate2);
            cd.Members.Add(snippet2);

            AssertEqual(cu,
                @"#Region ""Compile Unit Region""
                  '------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------
                  Option Strict Off
                  Option Explicit On
                  Namespace Namespace1
                      #Region ""Outer Type Region""
                      'Outer Type Comment
                      Public Class Class1
                          'Field 1 Comment
                          Private field1 As String
                          #Region ""Field Region""
                          Private field2 As String
                          #End Region
                          #Region ""Snippet Region""
                          #End Region
                          #Region ""Type Constructor Region""
                          Shared Sub New()
                          End Sub
                          #End Region
                          #Region ""Constructor Region""
                          Public Sub New()
                              MyBase.New
                              Me.field1 = ""value1""
                              Me.field2 = ""value2""
                          End Sub
                          #End Region
                          Public Sub New(ByVal value1 As String, ByVal value2 As String)
                              MyBase.New
                          End Sub
                          Public ReadOnly Property Property1() As String
                              Get
                                  Return Me.field1
                              End Get
                          End Property
                          #Region ""Property Region""
                          Public ReadOnly Property Property2() As String
                              Get
                                  Return Me.field2
                              End Get
                          End Property
                          #End Region
                          Public Event Event1 As System.EventHandler
                          #Region ""Event Region""
                          Public Event Event2 As System.EventHandler
                          #End Region
                          Public Sub Method1()
                              RaiseEvent Event1(Me, System.EventArgs.Empty)
                          End Sub
                          Public Shared Sub Main()
                          End Sub
                          #Region ""Method Region""
                          'Method 2 Comment
                          #ExternalSource(""MethodLinePragma.txt"",500)
                          Public Sub Method2()
                              RaiseEvent Event2(Me, System.EventArgs.Empty)
                          End Sub
                          #End ExternalSource
                          #End Region
                          Public Class NestedClass1
                          End Class
                          Public Delegate Sub nestedDelegate1(ByVal sender As Object, ByVal e As System.EventArgs)
                          #Region ""Nested Type Region""
                          'Nested Type Comment
                          #ExternalSource(""NestedTypeLinePragma.txt"",400)
                          Public Class NestedClass2
                          End Class
                          #End ExternalSource
                          #End Region
                          #Region ""Delegate Region""
                          Public Delegate Sub nestedDelegate2(ByVal sender As Object, ByVal e As System.EventArgs)
                          #End Region
                      End Class
                      #End Region
                  End Namespace
                  #End Region");
        }
        public static CodeCompileUnit GenerateCompileUnit(ITextTemplatingEngineHost host, ParsedTemplate pt,
                                                          TemplateSettings settings)
        {
            //prep the compile unit
            CodeCompileUnit ccu      = new CodeCompileUnit();
            CodeNamespace   namespac = new CodeNamespace(settings.Namespace);

            ccu.Namespaces.Add(namespac);

            HashSet <string> imports = new HashSet <string> ();

            imports.UnionWith(settings.Imports);
            imports.UnionWith(host.StandardImports);
            foreach (string ns in imports)
            {
                namespac.Imports.Add(new CodeNamespaceImport(ns));
            }

            //prep the type
            CodeTypeDeclaration type = new CodeTypeDeclaration(settings.Name);

            if (!String.IsNullOrEmpty(settings.Inherits))
            {
                type.BaseTypes.Add(new CodeTypeReference(settings.Inherits));
            }
            else
            {
                type.BaseTypes.Add(new CodeTypeReference(typeof(TextTransformation)));
            }
            namespac.Types.Add(type);

            //prep the transform method
            CodeMemberMethod transformMeth = new CodeMemberMethod();

            transformMeth.Name       = "TransformText";
            transformMeth.ReturnType = new CodeTypeReference(typeof(String));
            transformMeth.Attributes = MemberAttributes.Public | MemberAttributes.Override;

            //method references that will need to be used multiple times
            CodeMethodReferenceExpression writeMeth =
                new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "Write");
            CodeMethodReferenceExpression toStringMeth =
                new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ToStringHelper)), "ToStringWithCulture");

            //build the code from the segments
            foreach (TemplateSegment seg in pt.Content)
            {
                CodeStatement st = null;
                switch (seg.Type)
                {
                case SegmentType.Block:
                    st = new CodeSnippetStatement(seg.Text);
                    break;

                case SegmentType.Expression:
                    st = new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(writeMeth,
                                                       new CodeMethodInvokeExpression(toStringMeth, new CodeSnippetExpression(seg.Text))));
                    break;

                case SegmentType.Content:
                    st = new CodeExpressionStatement(new CodeMethodInvokeExpression(writeMeth, new CodePrimitiveExpression(seg.Text)));
                    break;

                case SegmentType.Helper:
                    CodeTypeMember mem = new CodeSnippetTypeMember(seg.Text);
                    mem.LinePragma = new CodeLinePragma(host.TemplateFile, seg.StartLocation.Line);
                    type.Members.Add(mem);
                    break;

                default:
                    throw new InvalidOperationException();
                }
                if (st != null)
                {
                    st.LinePragma = new CodeLinePragma(host.TemplateFile, seg.StartLocation.Line);
                    transformMeth.Statements.Add(st);
                }
            }

            //complete the transform method
            transformMeth.Statements.Add(new CodeMethodReturnStatement(
                                             new CodeMethodInvokeExpression(
                                                 new CodePropertyReferenceExpression(
                                                     new CodeThisReferenceExpression(),
                                                     "GenerationEnvironment"),
                                                 "ToString")));
            type.Members.Add(transformMeth);

            //generate the Host property if needed
            if (settings.HostSpecific)
            {
                CodeMemberField hostField = new CodeMemberField(new CodeTypeReference(typeof(ITextTemplatingEngineHost)), "hostValue");
                hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
                type.Members.Add(hostField);
                CodeMemberProperty hostProp = new CodeMemberProperty();
                hostProp.Name       = "Host";
                hostProp.Attributes = MemberAttributes.Public;
                hostProp.HasGet     = hostProp.HasGet = true;
                hostProp.Type       = hostField.Type;
                CodeFieldReferenceExpression hostFieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "hostValue");
                hostProp.SetStatements.Add(new CodeAssignStatement(hostFieldRef, new CodePropertySetValueReferenceExpression()));
                hostProp.GetStatements.Add(new CodeMethodReturnStatement(hostFieldRef));
                type.Members.Add(hostProp);
            }

            return(ccu);
        }
        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");
        }
        CodeMemberProperty CreateProperty(Widget widget, string returnType, CodeMemberField backingField, CodeMemberField backingFuncField, CodeMemberMethod creator, CodeExpression parent)
        {
            var ensureViewRef = new CodeMethodReferenceExpression(parent, "__EnsureView");

            ensureViewRef.TypeArguments.Add(new CodeTypeReference(returnType));

            var backingFuncFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingFuncField.Name);

            var ensureViewInvoke = new CodeMethodInvokeExpression(
                ensureViewRef,
                new CodeExpression [] {
                backingFuncFieldReference,
                new CodeDirectionExpression(FieldDirection.Ref, new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), backingField.Name)),
            }
                );

            var ret = new CodeMemberProperty {
                Name       = widget.Name,
                HasGet     = true,
                HasSet     = false,
                Type       = new CodeTypeReference(returnType),
                LinePragma = new CodeLinePragma(widget.FileName, widget.Line),
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            var assignFunc = new CodeAssignStatement(
                backingFuncFieldReference,
                new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), creator.Name)
                );

            ret.GetStatements.Add(new CodeConditionStatement(
                                      new CodeBinaryOperatorExpression(backingFuncFieldReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                                      new CodeStatement [] { assignFunc }
                                      ));
            ret.GetStatements.Add(new CodeMethodReturnStatement(ensureViewInvoke));
            return(ret);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace nspace = new CodeNamespace ("NSPC");
        nspace.Imports.Add (new CodeNamespaceImport ("System"));
        cu.Namespaces.Add (nspace);

        CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingStructs");
        cd.IsClass = true;
        nspace.Types.Add (cd);
        if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {
            // GENERATES (C#):
            //        public int CallingStructMethod(int i) {
            //            StructImplementation o = new StructImplementation ();
            //            return o.StructMethod(i);
            //        }
            AddScenario ("CheckCallingStructMethod");
            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "CallingStructMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("StructImplementation"), "o", new
                CodeObjectCreateExpression (new CodeTypeReference ("StructImplementation"))));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression (
                new CodeVariableReferenceExpression ("o"),
                "StructMethod"), new CodeArgumentReferenceExpression ("i"))));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingValueStruct(int i) {
            //            ValueStruct StructObject = new ValueStruct();
            //            StructObject.x = i;
            //            return StructObject.x;
            //        }
            AddScenario ("CheckUsingValueStruct");
            cmm = new CodeMemberMethod ();
            cmm.Name = "UsingValueStruct";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("ValueStruct", "StructObject", new
                CodeObjectCreateExpression ("ValueStruct")));
            cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"),
                new CodeArgumentReferenceExpression ("i")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new
                CodeVariableReferenceExpression ("StructObject"), "x")));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingStructProperty(int i) {
            //            StructImplementation StructObject = new StructImplementation();
            //            StructObject.UseIField = i;
            //            return StructObject.UseIField;
            //        }
            AddScenario ("CheckUsingStructProperty");
            cmm = new CodeMemberMethod ();
            cmm.Name = "UsingStructProperty";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("StructImplementation", "StructObject", new
                CodeObjectCreateExpression ("StructImplementation")));
            cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("StructObject"), "UseIField"),
                new CodeArgumentReferenceExpression ("i")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new
                CodeVariableReferenceExpression ("StructObject"), "UseIField")));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //        public int UsingInterfaceStruct(int i) {
            //            ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct();
            //            return IStructObject.InterfaceMethod(i);
            //        }
            if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
                AddScenario ("CheckUsingInterfaceStruct");
                // method to test struct implementing interfaces
                cmm = new CodeMemberMethod ();
                cmm.Name = "UsingInterfaceStruct";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cmm.Statements.Add (new CodeVariableDeclarationStatement ("ImplementInterfaceStruct", "IStructObject", new
                    CodeObjectCreateExpression ("ImplementInterfaceStruct")));
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (
                    new CodeVariableReferenceExpression ("IStructObject"), "InterfaceMethod",
                    new CodeArgumentReferenceExpression ("i"))));
                cd.Members.Add (cmm);
            }

            // GENERATES (C#):
            //    public struct StructImplementation { 
            //        int i;
            //        public int UseIField {
            //            get {
            //                return i;
            //            }
            //            set {
            //                i = value;
            //            }
            //        }
            //        public int StructMethod(int i) {
            //            return (5 + i);
            //        }
            //    }
            cd = new CodeTypeDeclaration ("StructImplementation");
            cd.IsStruct = true;
            nspace.Types.Add (cd);

            // declare an integer field
            CodeMemberField field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add (field);

            CodeMemberProperty prop = new CodeMemberProperty ();
            prop.Name = "UseIField";
            prop.Type = new CodeTypeReference (typeof (int));
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression ();
            fref.FieldName = "i";
            prop.GetStatements.Add (new CodeMethodReturnStatement (fref));
            prop.SetStatements.Add (new CodeAssignStatement (fref,
                new CodePropertySetValueReferenceExpression ()));

            cd.Members.Add (prop);

            cmm = new CodeMemberMethod ();
            cmm.Name = "StructMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                new CodePrimitiveExpression (5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i"))));
            cd.Members.Add (cmm);

            // GENERATES (C#):
            //    public struct ValueStruct {   
            //        public int x;
            //    }
            cd = new CodeTypeDeclaration ("ValueStruct");
            cd.IsStruct = true;
            nspace.Types.Add (cd);

            // declare an integer field
            field = new CodeMemberField (new CodeTypeReference (typeof (int)), "x");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add (field);

            if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
                // interface to be implemented    
                // GENERATES (C#):
                //    public interface InterfaceStruct {   
                //        int InterfaceMethod(int i);
                //    }
                cd = new CodeTypeDeclaration ("InterfaceStruct");
                cd.IsInterface = true;
                nspace.Types.Add (cd);

                // method in the interface
                cmm = new CodeMemberMethod ();
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cd.Members.Add (cmm);

                // struct to implement an interface
                // GENERATES (C#):
                //    public struct ImplementInterfaceStruct : InterfaceStruct {
                //        public int InterfaceMethod(int i) {
                //            return (8 + i);
                //        }
                //    }
                cd = new CodeTypeDeclaration ("ImplementInterfaceStruct");
                cd.BaseTypes.Add (new CodeTypeReference ("InterfaceStruct"));
                cd.IsStruct = true;
                nspace.Types.Add (cd);

                field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i");
                field.Attributes = MemberAttributes.Public;
                cd.Members.Add (field);
                // implement interface method
                cmm = new CodeMemberMethod ();
                cmm.Name = "InterfaceMethod";
                cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceStruct"));
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (8),
                    CodeBinaryOperatorType.Add,
                    new CodeArgumentReferenceExpression ("i"))));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
                cd.Members.Add (cmm);
            }
        }
    }
Beispiel #30
0
        private CodeTypeDeclaration GenerateGeometryShader()
        {
            CodeTypeDeclaration geometryShaderType = new CodeTypeDeclaration(this.ShaderName + "Geom");

            geometryShaderType.BaseTypes.Add(typeof(GeometryCSShaderCode));
            geometryShaderType.Comments.Add(new CodeCommentStatement(new CodeComment("<summary>", true)));
            geometryShaderType.Comments.Add(new CodeCommentStatement(new CodeComment(string.Format(
                                                                                         "一个<see cref=\"{0}\"/>对应一个(vertex shader+fragment shader+..shader)组成的shader program。",
                                                                                         this.ShaderName + "Geom"), true)));
            geometryShaderType.Comments.Add(new CodeCommentStatement(new CodeComment(string.Format(
                                                                                         "(GLSLVersion){0} is GLSLVersion.{1}", (uint)defaultVersion, defaultVersion), true)));
            geometryShaderType.Comments.Add(new CodeCommentStatement(new CodeComment("</summary>", true)));
            geometryShaderType.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                        new CodeTypeReference(typeof(Dump2FileAttribute)), new CodeAttributeArgument(
                                                            new CodePrimitiveExpression(true))));
            var codeVersionAttribute = new CodeAttributeDeclaration(
                new CodeTypeReference(typeof(GLSLVersionAttribute)),
                new CodeAttributeArgument(
                    new CodeCastExpression(typeof(GLSLVersion), new CodePrimitiveExpression((uint)defaultVersion))));

            geometryShaderType.CustomAttributes.Add(codeVersionAttribute);

            {
                var layoutInProperty = new CodeMemberProperty();
                layoutInProperty.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                layoutInProperty.Type       = new CodeTypeReference(typeof(GeometryCSShaderCode.InType));
                layoutInProperty.Name       = "LayoutIn";
                layoutInProperty.HasGet     = true;
                layoutInProperty.HasSet     = false;
                layoutInProperty.GetStatements.Add(new CodeMethodReturnStatement(
                                                       new CodeCastExpression(typeof(GeometryCSShaderCode.InType), new CodePrimitiveExpression((uint)defaultLayoutIn))));
                layoutInProperty.Comments.Add(new CodeCommentStatement(new CodeComment("<summary>", true)));
                layoutInProperty.Comments.Add(new CodeCommentStatement(new CodeComment(string.Format(
                                                                                           "(InType){0} is InType.{1}", (uint)defaultLayoutIn, defaultLayoutIn), true)));
                layoutInProperty.Comments.Add(new CodeCommentStatement(new CodeComment("</summary>", true)));
                geometryShaderType.Members.Add(layoutInProperty);
            }

            {
                var layoutOutProperty = new CodeMemberProperty();
                layoutOutProperty.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                layoutOutProperty.Type       = new CodeTypeReference(typeof(GeometryCSShaderCode.OutType));
                layoutOutProperty.Name       = "LayoutOut";
                layoutOutProperty.HasGet     = true;
                layoutOutProperty.HasSet     = false;
                layoutOutProperty.GetStatements.Add(new CodeMethodReturnStatement(
                                                        new CodeCastExpression(typeof(GeometryCSShaderCode.OutType), new CodePrimitiveExpression((uint)defaultLayoutOut))));
                layoutOutProperty.Comments.Add(new CodeCommentStatement(new CodeComment("<summary>", true)));
                layoutOutProperty.Comments.Add(new CodeCommentStatement(new CodeComment(string.Format(
                                                                                            "(OutType){0} is OutType.{1}", (uint)defaultLayoutOut, defaultLayoutOut), true)));
                layoutOutProperty.Comments.Add(new CodeCommentStatement(new CodeComment("</summary>", true)));
                geometryShaderType.Members.Add(layoutOutProperty);
            }

            {
                var max_verticesProperty = new CodeMemberProperty();
                max_verticesProperty.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                max_verticesProperty.Type       = new CodeTypeReference(typeof(int));
                max_verticesProperty.Name       = "max_vertices";
                max_verticesProperty.HasGet     = true;
                max_verticesProperty.HasSet     = false;
                max_verticesProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(100)));
                geometryShaderType.Members.Add(max_verticesProperty);
            }

            foreach (var item in this.GeometryShaderFieldList)
            {
                CodeMemberField fieldCode = GetCodeMemberField(item);
                fieldCode.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                   new CodeTypeReference(item.Qualider.GetAttributeType())));
                geometryShaderType.Members.Add(fieldCode);
            }

            CodeMemberMethod method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            method.ReturnType = new CodeTypeReference(typeof(void));
            method.Name       = "main";
            geometryShaderType.Members.Add(method);

            return(geometryShaderType);
        }
Beispiel #31
0
    public void PreMembersHook(Smoke* smoke, Smoke.Class* klass, CodeTypeDeclaration type)
    {
        if (type.Name == "QObject")
        {
            // Add 'Qt' base class
            type.BaseTypes.Add(new CodeTypeReference("Qt"));

            // add the Q_EMIT field
            CodeMemberField Q_EMIT = new CodeMemberField(typeof(object), "Q_EMIT");
            Q_EMIT.Attributes = MemberAttributes.Family;
            Q_EMIT.InitExpression = new CodePrimitiveExpression(null);
            type.Members.Add(Q_EMIT);
        }
    }
Beispiel #32
0
        public CodeMemberField CreateField(string typeName, string fieldName)
        {
            var codeMemberField = new CodeMemberField(typeName, fieldName);

            return(codeMemberField);
        }
Beispiel #33
0
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu)
    {
        CodeNamespace nspace = new CodeNamespace("NSPC");

        nspace.Imports.Add(new CodeNamespaceImport("System"));
        cu.Namespaces.Add(nspace);

        CodeTypeDeclaration cd = new CodeTypeDeclaration("TestingStructs");

        cd.IsClass = true;
        nspace.Types.Add(cd);
        if (Supports(provider, GeneratorSupport.DeclareValueTypes))
        {
            // GENERATES (C#):
            //        public int CallingStructMethod(int i) {
            //            StructImplementation o = new StructImplementation ();
            //            return o.StructMethod(i);
            //        }
            AddScenario("CheckCallingStructMethod");
            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name       = "CallingStructMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("StructImplementation"), "o", new
                                                                    CodeObjectCreateExpression(new CodeTypeReference("StructImplementation"))));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(
                                                                                                new CodeVariableReferenceExpression("o"),
                                                                                                "StructMethod"), new CodeArgumentReferenceExpression("i"))));
            cd.Members.Add(cmm);

            // GENERATES (C#):
            //        public int UsingValueStruct(int i) {
            //            ValueStruct StructObject = new ValueStruct();
            //            StructObject.x = i;
            //            return StructObject.x;
            //        }
            AddScenario("CheckUsingValueStruct");
            cmm            = new CodeMemberMethod();
            cmm.Name       = "UsingValueStruct";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeVariableDeclarationStatement("ValueStruct", "StructObject", new
                                                                    CodeObjectCreateExpression("ValueStruct")));
            cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("StructObject"), "x"),
                                                       new CodeArgumentReferenceExpression("i")));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
                                                                                              CodeVariableReferenceExpression("StructObject"), "x")));
            cd.Members.Add(cmm);

            // GENERATES (C#):
            //        public int UsingStructProperty(int i) {
            //            StructImplementation StructObject = new StructImplementation();
            //            StructObject.UseIField = i;
            //            return StructObject.UseIField;
            //        }
            AddScenario("CheckUsingStructProperty");
            cmm            = new CodeMemberMethod();
            cmm.Name       = "UsingStructProperty";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeVariableDeclarationStatement("StructImplementation", "StructObject", new
                                                                    CodeObjectCreateExpression("StructImplementation")));
            cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(
                                                           new CodeVariableReferenceExpression("StructObject"), "UseIField"),
                                                       new CodeArgumentReferenceExpression("i")));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new
                                                                                                 CodeVariableReferenceExpression("StructObject"), "UseIField")));
            cd.Members.Add(cmm);

            // GENERATES (C#):
            //        public int UsingInterfaceStruct(int i) {
            //            ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct();
            //            return IStructObject.InterfaceMethod(i);
            //        }
            if (Supports(provider, GeneratorSupport.DeclareInterfaces))
            {
                AddScenario("CheckUsingInterfaceStruct");
                // method to test struct implementing interfaces
                cmm            = new CodeMemberMethod();
                cmm.Name       = "UsingInterfaceStruct";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cmm.Statements.Add(new CodeVariableDeclarationStatement("ImplementInterfaceStruct", "IStructObject", new
                                                                        CodeObjectCreateExpression("ImplementInterfaceStruct")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(
                                                                     new CodeVariableReferenceExpression("IStructObject"), "InterfaceMethod",
                                                                     new CodeArgumentReferenceExpression("i"))));
                cd.Members.Add(cmm);
            }

            // GENERATES (C#):
            //    public struct StructImplementation {
            //        int i;
            //        public int UseIField {
            //            get {
            //                return i;
            //            }
            //            set {
            //                i = value;
            //            }
            //        }
            //        public int StructMethod(int i) {
            //            return (5 + i);
            //        }
            //    }
            cd          = new CodeTypeDeclaration("StructImplementation");
            cd.IsStruct = true;
            nspace.Types.Add(cd);

            // declare an integer field
            CodeMemberField field = new CodeMemberField(new CodeTypeReference(typeof(int)), "i");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add(field);

            CodeMemberProperty prop = new CodeMemberProperty();
            prop.Name       = "UseIField";
            prop.Type       = new CodeTypeReference(typeof(int));
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression();
            fref.FieldName = "i";
            prop.GetStatements.Add(new CodeMethodReturnStatement(fref));
            prop.SetStatements.Add(new CodeAssignStatement(fref,
                                                           new CodePropertySetValueReferenceExpression()));

            cd.Members.Add(prop);

            cmm            = new CodeMemberMethod();
            cmm.Name       = "StructMethod";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                                                                 new CodePrimitiveExpression(5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression("i"))));
            cd.Members.Add(cmm);

            // GENERATES (C#):
            //    public struct ValueStruct {
            //        public int x;
            //    }
            cd          = new CodeTypeDeclaration("ValueStruct");
            cd.IsStruct = true;
            nspace.Types.Add(cd);

            // declare an integer field
            field            = new CodeMemberField(new CodeTypeReference(typeof(int)), "x");
            field.Attributes = MemberAttributes.Public;
            cd.Members.Add(field);

            if (Supports(provider, GeneratorSupport.DeclareInterfaces))
            {
                // interface to be implemented
                // GENERATES (C#):
                //    public interface InterfaceStruct {
                //        int InterfaceMethod(int i);
                //    }
                cd             = new CodeTypeDeclaration("InterfaceStruct");
                cd.IsInterface = true;
                nspace.Types.Add(cd);

                // method in the interface
                cmm            = new CodeMemberMethod();
                cmm.Name       = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cd.Members.Add(cmm);

                // struct to implement an interface
                // GENERATES (C#):
                //    public struct ImplementInterfaceStruct : InterfaceStruct {
                //        public int InterfaceMethod(int i) {
                //            return (8 + i);
                //        }
                //    }
                cd = new CodeTypeDeclaration("ImplementInterfaceStruct");
                cd.BaseTypes.Add(new CodeTypeReference("InterfaceStruct"));
                cd.IsStruct = true;
                nspace.Types.Add(cd);

                field            = new CodeMemberField(new CodeTypeReference(typeof(int)), "i");
                field.Attributes = MemberAttributes.Public;
                cd.Members.Add(field);
                // implement interface method
                cmm      = new CodeMemberMethod();
                cmm.Name = "InterfaceMethod";
                cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceStruct"));
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new CodePrimitiveExpression(8),
                                                                                                  CodeBinaryOperatorType.Add,
                                                                                                  new CodeArgumentReferenceExpression("i"))));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cd.Members.Add(cmm);
            }
        }
    }
        /// <summary>
        /// See <see cref="CodeProcessor.ProcessGeneratedCode"/>.
        /// </summary>
        /// <param name="domainServiceDescription">The domainServiceDescription</param>
        /// <param name="codeCompileUnit">The codeCompileUnit</param>
        /// <param name="typeMapping">The typeMapping</param>
        public override void ProcessGeneratedCode(DomainServiceDescription domainServiceDescription, CodeCompileUnit codeCompileUnit, IDictionary <Type, CodeTypeDeclaration> typeMapping)
        {
            // Make sure the provider extends IAuthentication<T>
            Type genericDomainServiceType;

            AuthenticationCodeProcessor.CheckIAuthentication(domainServiceDescription, out genericDomainServiceType);

            Type userEntityType = genericDomainServiceType.GetGenericArguments()[0];

            AuthenticationCodeProcessor.CheckIUser(userEntityType);

            // Implement IPrincipal and IIdentity in the user type
            CodeTypeDeclaration entityTypeDeclaration;

            typeMapping.TryGetValue(userEntityType, out entityTypeDeclaration);

            if (entityTypeDeclaration != null)
            {
                CodeTypeReference identityInterfaceTypeReference =
                    new CodeTypeReference(typeof(IIdentity))
                {
                    Options = CodeTypeReferenceOptions.GlobalReference
                };
                CodeTypeReference principalInterfaceTypeReference =
                    new CodeTypeReference(typeof(IPrincipal))
                {
                    Options = CodeTypeReferenceOptions.GlobalReference
                };

                entityTypeDeclaration.BaseTypes.Add(identityInterfaceTypeReference);
                entityTypeDeclaration.BaseTypes.Add(principalInterfaceTypeReference);

                ////
                //// private string IIdentity.AuthenticationType
                ////
                CodeMemberProperty authenticationTypeProperty = new CodeMemberProperty()
                {
                    Attributes = MemberAttributes.Private | MemberAttributes.Final,
                    HasGet     = true,
                    Name       = "AuthenticationType",
                    Type       = new CodeTypeReference(typeof(string))
                };

                // get { return string.Empty; }
                authenticationTypeProperty.GetStatements.Add(new CodeMethodReturnStatement(
                                                                 new CodePropertyReferenceExpression(
                                                                     new CodeTypeReferenceExpression(typeof(string)),
                                                                     "Empty")));

                authenticationTypeProperty.PrivateImplementationType = identityInterfaceTypeReference;
                entityTypeDeclaration.Members.Add(authenticationTypeProperty);

                ////
                //// public bool IsAuthenticated
                ////
                CodeMemberProperty isAuthenticatedProperty = new CodeMemberProperty()
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    HasGet     = true,
                    Name       = "IsAuthenticated",
                    Type       = new CodeTypeReference(typeof(bool))
                };

                // get { return (true != string.IsNullOrEmpty(this.Name)); }
                isAuthenticatedProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeBinaryOperatorExpression(
                            new CodePrimitiveExpression(true),
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression(typeof(string)),
                                "IsNullOrEmpty",
                                new CodePropertyReferenceExpression(
                                    new CodeThisReferenceExpression(),
                                    "Name")))));

                isAuthenticatedProperty.Comments.AddRange(
                    AuthenticationCodeProcessor.GetDocComments(Resources.ApplicationServices_CommentIsAuth));
                isAuthenticatedProperty.ImplementationTypes.Add(identityInterfaceTypeReference);
                entityTypeDeclaration.Members.Add(isAuthenticatedProperty);

                ////
                //// private string IIdentity.Name
                ////
                // VB Codegen requires us to implement a ReadOnly version of Name as well
                CodeMemberProperty namePropertyExp = new CodeMemberProperty()
                {
                    Attributes = MemberAttributes.Private | MemberAttributes.Final,
                    HasGet     = true,
                    Name       = "Name",
                    Type       = new CodeTypeReference(typeof(string))
                };

                // get { return this.Name; }
                namePropertyExp.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodePropertyReferenceExpression(
                            new CodeThisReferenceExpression(),
                            "Name")));

                namePropertyExp.PrivateImplementationType = identityInterfaceTypeReference;
                entityTypeDeclaration.Members.Add(namePropertyExp);

                ////
                //// private IIdentity IPrincipal.Identity
                ////
                CodeMemberProperty identityProperty = new CodeMemberProperty()
                {
                    Attributes = MemberAttributes.Private | MemberAttributes.Final,
                    HasGet     = true,
                    Name       = "Identity",
                    Type       = identityInterfaceTypeReference,
                };

                // get { return this; }
                identityProperty.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeThisReferenceExpression()));

                identityProperty.PrivateImplementationType = principalInterfaceTypeReference;
                entityTypeDeclaration.Members.Add(identityProperty);

                ////
                //// public bool IsInRole(string role)
                ////
                CodeMemberMethod isInRoleMethod = new CodeMemberMethod()
                {
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    Name       = "IsInRole",
                    ReturnType = new CodeTypeReference(typeof(bool))
                };
                isInRoleMethod.Parameters.Add(
                    new CodeParameterDeclarationExpression(
                        new CodeTypeReference(typeof(string)),
                        "role"));

                // if (this.Roles == null)
                // {
                //     return false;
                // }
                // return this.Roles.Contains(role);
                CodeConditionStatement ifRolesNullStatement = new CodeConditionStatement();
                ifRolesNullStatement.Condition = new CodeBinaryOperatorExpression(
                    new CodePropertyReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "Roles"),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(null));
                ifRolesNullStatement.TrueStatements.Add(
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));

                isInRoleMethod.Statements.Add(ifRolesNullStatement);
                isInRoleMethod.Statements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(
                                new CodeTypeReference(typeof(Enumerable))
                {
                    Options = CodeTypeReferenceOptions.GlobalReference
                }),
                            "Contains",
                            new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Roles"),
                            new CodeVariableReferenceExpression("role"))));

                isInRoleMethod.Comments.AddRange(
                    AuthenticationCodeProcessor.GetDocComments(Resources.ApplicationServices_CommentIsInRole));
                isInRoleMethod.ImplementationTypes.Add(principalInterfaceTypeReference);
                entityTypeDeclaration.Members.Add(isInRoleMethod);

                // Changes to Name need to raise change notification for IsAuthenticated. To accomplish this,
                // we'll insert a change event at the end of the "if (this._name != value)" block.
                //
                // >> this.RaisePropertyChanged("IsAuthenticated");
                CodeMemberProperty nameProperty = entityTypeDeclaration.Members.OfType <CodeMemberProperty>().Where(c => c.Name == "Name").First();
                nameProperty.SetStatements.OfType <CodeConditionStatement>().First().TrueStatements.Add(
                    new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(),
                            "RaisePropertyChanged",
                            new CodePrimitiveExpression("IsAuthenticated"))));

                // Name should be set to string.Empty by default
                CodeMemberField nameField = entityTypeDeclaration.Members.OfType <CodeMemberField>().Where(c => c.Name == "_name").Single();
                nameField.InitExpression =
                    new CodePropertyReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(string)),
                        "Empty");
            }

            // Set context base type
            CodeTypeDeclaration providerTypeDeclaration;

            typeMapping.TryGetValue(domainServiceDescription.DomainServiceType, out providerTypeDeclaration);

            if (providerTypeDeclaration != null)
            {
                providerTypeDeclaration.BaseTypes.Clear();
                providerTypeDeclaration.BaseTypes.Add(
                    new CodeTypeReference(AuthenticationCodeProcessor.AuthenticationDomainContextBaseName)
                {
                    Options = CodeTypeReferenceOptions.GlobalReference
                });
            }
        }
Beispiel #35
0
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu)
    {
        // GENERATES (C#):
        //  namespace NS {
        //  using System;
        //        public class Test {
        //            public int NonStaticPublicField = 5;
        //        }
        //        public class Test2 {
        //            public int NonStaticPublicField = 5;
        //        }
        //    }
        CodeNamespace ns = new CodeNamespace("NS");

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

        // create a class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration();

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

        CodeMemberField field = new CodeMemberField();

        field.Name           = "NonStaticPublicField";
        field.Attributes     = MemberAttributes.Public | MemberAttributes.Final;
        field.Type           = new CodeTypeReference(typeof(int));
        field.InitExpression = new CodePrimitiveExpression(5);
        class1.Members.Add(field);

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

        field                = new CodeMemberField();
        field.Name           = "NonStaticPublicField";
        field.Attributes     = MemberAttributes.Public | MemberAttributes.Final;
        field.Type           = new CodeTypeReference(typeof(int));
        field.InitExpression = new CodePrimitiveExpression(5);
        class1.Members.Add(field);

        // GENERATES (C#):
        //    namespace NS2 {
        //        public class Test1 {
        //            public static int TestingMethod(int i) {
        //                NS.Test temp1 = new NS.Test();
        //                NS.Test2 temp2 = new NS.Test2();
        //                temp1.NonStaticPublicField = i;
        //                temp2.NonStaticPublicField = (i * 10);
        //                int sum;
        //                sum = (temp1.NonStaticPublicField + temp2.NonStaticPublicField);
        //                return sum;
        //            }
        //        }
        //    }
        AddScenario("CheckTestingMethod");
        ns = new CodeNamespace("NS2");
        cu.Namespaces.Add(ns);

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

        CodeMemberMethod cmm = new CodeMemberMethod();

        cmm.Name       = "TestingMethod";
        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("NS.Test", "temp1", new CodeObjectCreateExpression("NS.Test")));
        cmm.Statements.Add(new CodeVariableDeclarationStatement("NS.Test2", "temp2", new CodeObjectCreateExpression("NS.Test2")));
        cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("temp1"), "NonStaticPublicField")
                                                   , new CodeArgumentReferenceExpression("i")));
        cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("temp2"), "NonStaticPublicField")
                                                   , new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"), CodeBinaryOperatorType.Multiply, new CodePrimitiveExpression(10))));
        cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "sum"));
        cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sum"),
                                                   new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("temp1"), "NonStaticPublicField"),
                                                                                    CodeBinaryOperatorType.Add, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("temp2"), "NonStaticPublicField"))));
        cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("sum")));
        class1.Members.Add(cmm);
    }
        public static void CreateGetContentsRecursiveMethod(CodeTypeDeclaration type, ResourceFolder folder)
        {
            var cache = new CodeMemberField(GetIResourceIListType(), RecursiveLookupCacheName)
            {
                Attributes = MemberAttributes.Static | MemberAttributes.Private
            };

            type.Members.Add(cache);

            var method = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Static | MemberAttributes.Public,
                Name       = Strings.GetResourcesRecursiveMethodName,
                ReturnType = GetIResourceIListType()
            };

            method.Comments.AddRange(CompilerUtil.CreateDocsComment(Strings.GetContentsRecursiveCommentSummary,
                                                                    Strings.GetContentsRecursiveCommentReturns));

            method.Statements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeFieldReferenceExpression(null, RecursiveLookupCacheName),
                        CodeBinaryOperatorType.IdentityInequality,
                        new CodePrimitiveExpression(null)
                        ),
                    new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, RecursiveLookupCacheName))));

            // Create list
            method.Statements.Add(new CodeVariableDeclarationStatement(GetIResourceListType(), "tmp",
                                                                       new CodeObjectCreateExpression(GetIResourceListType())));

            // Add any resources from this folder
            method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("tmp"), "AddRange",
                                                                 new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, Strings.GetResourcesMethodName))));

            // Add any resources from subfolders
            foreach (var f in folder.Folders)
            {
                var name = CompilerUtil.GetSafeName(f.Name, true);

                // Skip if this folder hasn't been added to the type for some reason
                if (!CompilerUtil.IsDuplicate(name, type))
                {
                    continue;
                }

                // Add any resources from this folder
                method.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("tmp"),
                                                                     "AddRange",
                                                                     new CodeMethodInvokeExpression(
                                                                         new CodeMethodReferenceExpression(new CodeSnippetExpression(name),
                                                                                                           Strings.GetResourcesRecursiveMethodName))));
            }

            method.Statements.Add(
                new CodeAssignStatement(new CodeFieldReferenceExpression(null, RecursiveLookupCacheName),
                                        new CodeVariableReferenceExpression("tmp")));

            method.Statements.Add(
                new CodeMethodReturnStatement(new CodeFieldReferenceExpression(null, RecursiveLookupCacheName)));

            type.Members.Add(method);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        // [assembly: System.Reflection.AssemblyTitle("MyAssembly")]
        // [assembly: System.Reflection.AssemblyVersion("1.0.6.2")]
        // [assembly: System.CLSCompliantAttribute(false)]
        // 
        // namespace MyNamespace {
        //     using System;
        //     using System.Drawing;
        //     using System.Windows.Forms;
        //     using System.ComponentModel;
        //
        CodeNamespace ns = new CodeNamespace ();
        ns.Name = "MyNamespace";
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
        ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
        cu.Namespaces.Add (ns);

        cu.ReferencedAssemblies.Add ("System.Xml.dll");
        cu.ReferencedAssemblies.Add ("System.Drawing.dll");
        cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");

        // Assembly Attributes
        if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
            AddScenario ("CheckAssemblyAttributes", "Check that assembly attributes get generated properly.");
            CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new
                CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly"))));
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new
                CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2"))));
            attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new
                CodeAttributeArgument (new CodePrimitiveExpression (false))));
        }

        // GENERATES (C#):
        //     [System.Serializable()]
        //     [System.Obsolete("Don\'t use this Class")]
        //     [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")]
        //     public class MyClass {
        //
#if !WHIDBEY
        // Everett versions of C# and VB code providers will never have these generated properly
        if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider))
            AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#else
        AddScenario ("CheckClassAttributes", "Check that class attributes get generated properly.");
#endif
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "MyClass";
        class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable"));
        class1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Class"))));
        class1.CustomAttributes.Add (new
            CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName,
            new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID"))));
        ns.Types.Add (class1);

        // GENERATES (C#):
        //         [System.Serializable()]
        //         public class NestedClass {
        //         }

        if (Supports (provider, GeneratorSupport.NestedTypes)) {
#if !WHIDBEY
        // Everett versions of C# and VB code providers will never have these generated properly
        if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider))
            AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly.");
#else
            AddScenario ("CheckNestedClassAttributes", "Check that nested class attributes get generated properly.");
#endif
            CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("NestedClass");
            nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
            nestedClass.IsClass = true;
            nestedClass.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Serializable"));
            class1.Members.Add (nestedClass);
        }

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Method")]
        //         [System.ComponentModel.Editor("This", "That")]
        //         public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] int[] arrayit) {
        //         }
        AddScenario ("CheckMyMethodAttributes", "Check that attributes are generated properly on MyMethod().");
        CodeMemberMethod method1 = new CodeMemberMethod ();
        method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
        method1.Name = "MyMethod";
        method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Method"))));
        method1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.ComponentModel.Editor", new
            CodeAttributeArgument (new CodePrimitiveExpression ("This")), new CodeAttributeArgument (new
            CodePrimitiveExpression ("That"))));
        CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah");

        if (Supports (provider, GeneratorSupport.ParameterAttributes)) {
            AddScenario ("CheckParameterAttributes", "Check that parameter attributes are generated properly.");
            param1.CustomAttributes.Add (
                new CodeAttributeDeclaration (
                "System.Xml.Serialization.XmlElement",
                new CodeAttributeArgument (
                "Form",
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                new CodeAttributeArgument (
                "IsNullable",
                new CodePrimitiveExpression (false))));
        }
        method1.Parameters.Add (param1);
        CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression (typeof (int[]), "arrayit");

        if (Supports (provider, GeneratorSupport.ParameterAttributes)) {
            param2.CustomAttributes.Add (
                new CodeAttributeDeclaration (
                "System.Xml.Serialization.XmlElement",
                new CodeAttributeArgument (
                "Form",
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                new CodeAttributeArgument (
                "IsNullable",
                new CodePrimitiveExpression (false))));
        }
        //param2.CustomAttributes.Add(new CodeAttributeDeclaration("System.ParamArray"));
        method1.Parameters.Add (param2);
        class1.Members.Add (method1);

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Function")]
        //         [return: System.Xml.Serialization.XmlIgnoreAttribute()]
        //         [return: System.Xml.Serialization.XmlRootAttribute(Namespace="Namespace Value", ElementName="Root, hehehe")]
        //         public string MyFunction() {
        //             return "Return";
        //         }
        //
        if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) {
            AddScenario ("CheckMyFunctionAttributes", "Check return type attributes.");
            CodeMemberMethod function1 = new CodeMemberMethod ();
            function1.Attributes = MemberAttributes.Public;
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference (typeof (string));
            function1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
                CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Function"))));

            function1.ReturnTypeCustomAttributes.Add (new
                CodeAttributeDeclaration ("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument ("Namespace", new CodePrimitiveExpression ("Namespace Value")), new
                CodeAttributeArgument ("ElementName", new CodePrimitiveExpression ("Root, hehehe"))));
            function1.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("Return")));
            class1.Members.Add (function1);
        }

        // GENERATES (C#):
        //         [System.Xml.Serialization.XmlElementAttribute()]
        //         private string myField = "hi!";
        //
        AddScenario ("CheckMyFieldAttributes", "Check that attributes are generated properly on MyField.");
        CodeMemberField field1 = new CodeMemberField ();
        field1.Name = "myField";
        field1.Attributes = MemberAttributes.Public;
        field1.Type = new CodeTypeReference (typeof (string));
        field1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlElementAttribute"));
        field1.InitExpression = new CodePrimitiveExpression ("hi!");
        class1.Members.Add (field1);


        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Property")]
        //         public string MyProperty {
        //             get {
        //                 return this.myField;
        //             }
        //         }
        AddScenario ("CheckMyPropertyAttributes", "Check that attributes are generated properly on MyProperty.");
        CodeMemberProperty prop1 = new CodeMemberProperty ();
        prop1.Attributes = MemberAttributes.Public;
        prop1.Name = "MyProperty";
        prop1.Type = new CodeTypeReference (typeof (string));
        prop1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Property"))));
        prop1.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "myField")));
        class1.Members.Add (prop1);

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Constructor")]
        //         public MyClass() {
        //         }

        if (!(provider is JScriptCodeProvider))
            AddScenario ("CheckConstructorAttributes", "Check that attributes are generated properly on the constructor.");
        CodeConstructor const1 = new CodeConstructor ();
        const1.Attributes = MemberAttributes.Public;
        const1.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
            CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor"))));
        class1.Members.Add (const1);

        // GENERATES (C#):
        //         [System.Obsolete("Don\'t use this Constructor")]
        //         static MyClass() {
        //         }

        if (Supports (provider, GeneratorSupport.StaticConstructors)) {

            // C#, VB and JScript code providers don't generate this properly.  This will
            // be fixed in Beta2 (with the exception of JScript code provider.  JScript doesn't
            // support static constructor custom attributes)
            //if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) {
                AddScenario ("CheckStaticConstructorAttributes", "Check that attributes are generated properly on type constructors.");
            //}
            CodeTypeConstructor typecons = new CodeTypeConstructor ();
            typecons.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
                CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Constructor"))));
            class1.Members.Add (typecons);
        }

        // GENERATES (C#):
        //         [System.Obsolete ("Don\'t use this entry point")]
        //         public static void Main () {
        //         }
        if (Supports (provider, GeneratorSupport.EntryPointMethod)) {
            // C#, VB and JScript code providers don't generate this properly.  This will
            // be fixed in Beta2 (with the exception of JScript code provider.  JScript doesn't
            // support static constructor custom attributes)
            ///if (!(provider is CSharpCodeProvider) && !(provider is VBCodeProvider) && !(provider is JScriptCodeProvider)) {
                AddScenario ("CheckEntryPointMethodAttributes", "Check that attributes are generated properly on entry point methods.");
            //}
            CodeEntryPointMethod entpoint = new CodeEntryPointMethod ();
            entpoint.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
                CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this entry point"))));
            class1.Members.Add (entpoint);
        }

        if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
            AddScenario ("CheckDelegateAttributes");
            CodeTypeDelegate del = new CodeTypeDelegate ("MyDelegate");
            del.TypeAttributes = TypeAttributes.Public;
            del.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new
                CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this delegate"))));
            ns.Types.Add (del);
        }

        if (Supports (provider, GeneratorSupport.DeclareEvents)) {
            // GENERATES (C#):
            //     public class Test : Form {
            //         
            //         private Button b = new Button();
            //
            // 
            AddScenario ("CheckEventAttributes", "test attributes on an event");
            class1 = new CodeTypeDeclaration ("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add (new CodeTypeReference ("Form"));
            ns.Types.Add (class1);
            CodeMemberField mfield = new CodeMemberField (new CodeTypeReference ("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("Button"));
            class1.Members.Add (mfield);

            // GENERATES (C#):
            //         public Test() {
            //             this.Size = new Size(600, 600);
            //             b.Text = "Test";
            //             b.TabIndex = 0;
            //             b.Location = new Point(400, 525);
            //             this.MyEvent += new EventHandler(this.b_Click);
            //         }
            //
            CodeConstructor ctor = new CodeConstructor ();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
                "Size"), new CodeObjectCreateExpression (new CodeTypeReference ("Size"),
                new CodePrimitiveExpression (600), new CodePrimitiveExpression (600))));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "Text"), new CodePrimitiveExpression ("Test")));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "TabIndex"), new CodePrimitiveExpression (0)));
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeFieldReferenceExpression (null, "b"),
                "Location"), new CodeObjectCreateExpression (new CodeTypeReference ("Point"),
                new CodePrimitiveExpression (400), new CodePrimitiveExpression (525))));
            ctor.Statements.Add (new CodeAttachEventStatement (new CodeEventReferenceExpression (new
                CodeThisReferenceExpression (), "MyEvent"), new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler")
                , new CodeThisReferenceExpression (), "b_Click")));
            class1.Members.Add (ctor);

            // GENERATES (C#):
            //         [System.CLSCompliantAttribute(false)]
            //         public event System.EventHandler MyEvent;
            CodeMemberEvent evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false))));
            class1.Members.Add (evt);

            // GENERATES (C#):
            //         private void b_Click(object sender, System.EventArgs e) {
            //         }
            //     }
            // }
            //
            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "b_Click";
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
            class1.Members.Add (cmm);
        }

    }
        public static CodeCompileUnit TestSimpleStructCompileUnit()
        {
            CodeCompileUnit     compileUnit      = new CodeCompileUnit();
            CodeNamespace       codeNamespace    = new CodeNamespace("Test.Namespace");
            CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration("TestClass")
            {
                IsStruct = true
            };

            classDeclaration.TypeAttributes =
                (classDeclaration.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NotPublic;

            var field1 = new CodeMemberField(typeof(int), "count");

            field1.Attributes = (field1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
            var field2 = new CodeMemberField(typeof(int), "increment");

            field2.Attributes = (field2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;

            classDeclaration.Members.Add(field1);
            classDeclaration.Members.Add(field2);

            var constructor = new CodeConstructor();

            constructor.Attributes = (constructor.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "count"));
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "increment"));

            constructor.Statements.Add(new CodeAssignStatement(
                                           FieldReferenceExpression.This("count"),
                                           new CodeArgumentReferenceExpression("count")));
            constructor.Statements.Add(new CodeAssignStatement(
                                           FieldReferenceExpression.This("increment"),
                                           new CodeArgumentReferenceExpression("increment")));

            classDeclaration.Members.Add(constructor);
            classDeclaration.Attributes = (classDeclaration.Attributes & ~MemberAttributes.AccessMask) |
                                          MemberAttributes.Assembly;

            var method = new CodeMemberMethod()
            {
                Name       = "IncrementAndGet",
                ReturnType = Types.Int,
                Attributes = MemberAttributes.Assembly | MemberAttributes.Final
            };

            method.Statements.Add(
                new CodeOperationAssignmentStatement(
                    FieldReferenceExpression.Default("count"),
                    CodeBinaryOperatorTypeMore.Add,
                    FieldReferenceExpression.Default("increment")).AsAssignStatement());
            method.Statements.Add(new CodeMethodReturnStatement(FieldReferenceExpression.Default("count")));

            classDeclaration.Members.Add(method);

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

            return(compileUnit);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace ns = new CodeNamespace ("Namespace1");

        cu.Namespaces.Add (ns);

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

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

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

            // things to enumerate
            for (int k = 0; k < 5; k++) {
                CodeMemberField Field = new CodeMemberField ("System.Int32", "Num" + (k).ToString ());
                //Field.InitExpression = new CodePrimitiveExpression (k);
                ce.Members.Add (Field);
            }

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

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

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

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

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

            // GENERATE (C#):
            //        public int OutputDecimalEnumVal(int i) {
            //                if ((i == 3)) {
            //                        return ((int)(DecimalEnum.Num3));
            //                }
            //                if ((i == 4)) {
            //                        return ((int)(DecimalEnum.Num4));
            //                }
            //                if ((i == 2)) {
            //                        return ((int)(DecimalEnum.Num2));
            //                }
            //                if ((i == 1)) {
            //                        return ((int)(DecimalEnum.Num1));
            //                }
            //                if ((i == 0)) {
            //                        return ((int)(DecimalEnum.Num0));
            //                }
            //                    return (i + 10);
            //            }
    
            // generate 5 scenarios for OutputDecimalEnumVal
            for (int k = 0; k < 5; k++)
                AddScenario ("CheckOutputDecimalEnumVal" + k);

            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "OutputDecimalEnumVal";
            cmm.Attributes = MemberAttributes.Public;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i");
            cmm.Parameters.Add (param);
            CodeBinaryOperatorExpression eq       = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (3));
            CodeMethodReturnStatement    truestmt = new CodeMethodReturnStatement (
                new CodeCastExpression (typeof (int),
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num3")));
            CodeConditionStatement       condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (4));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num4")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);
            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (2));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num2")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (1));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num1")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (0));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num0")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            cmm.ReturnType = new CodeTypeReference ("System.Int32");

            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (10))));
            cd.Members.Add (cmm);


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

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

            cmm = new CodeMemberMethod ();
            cmm.Name = "OutputBinaryEnumVal";
            cmm.Attributes = MemberAttributes.Public;
            param = new CodeParameterDeclarationExpression (typeof (int), "i");
            cmm.Parameters.Add (param);
            eq = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (3));
            truestmt = new CodeMethodReturnStatement (
                new CodeCastExpression (typeof (int),
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin3")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (4));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin4")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);
            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (2));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin2")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (1));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin1")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (5));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("BinaryEnum"), "Bin5")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            cmm.ReturnType = new CodeTypeReference ("System.Int32");

            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (10))));
            cd.Members.Add (cmm);


#if WHIDBEY
            // GENERATE (C#):
            //        public long VerifyMyEnumExists(int num) {
            //            if ((num == Int32.MaxValue)) {
            //                return ((int)(MyEnum.Large));
            //            }
            //            return 0;
            //        }

            AddScenario ("CheckVerifyMyEnumExists");
            cmm = new CodeMemberMethod ();
            cmm.Name = "VerifyMyEnumExists";
            cmm.Attributes = MemberAttributes.Public;
            param = new CodeParameterDeclarationExpression (typeof (int), "num");
            cmm.Parameters.Add (param);
            cmm.ReturnType = new CodeTypeReference ("System.Int64");
            eq = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("num"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (Int32.MaxValue));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (long),
                        new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("MyEnum"),
                            "Large")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (0)));
            cd.Members.Add (cmm);
#endif
        }
    }
        public static CodeCompileUnit TestSimpleClassCompileUnit()
        {
            CodeCommentStatement docComment = new CodeCommentStatement("this is a doc comment", true);
            CodeCommentStatement comment    = new CodeCommentStatement("this is a comment", false);

            CodeCompileUnit     compileUnit      = new CodeCompileUnit();
            CodeNamespace       codeNamespace    = new CodeNamespace("Test.Namespace");
            CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration("TestClass")
            {
                IsClass = true
            };

            classDeclaration.TypeAttributes =
                (classDeclaration.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NotPublic;

            var field1 = new CodeMemberField(typeof(int), "count");

            field1.Attributes = (field1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
            var field2 = new CodeMemberField(typeof(int), "increment");

            field2.Attributes = (field2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.FamilyAndAssembly;

            classDeclaration.Members.Add(field1);
            classDeclaration.Members.Add(field2);

            var prop1 = new CodeMemberProperty()
            {
                Name       = "Prop",
                HasGet     = true,
                HasSet     = true,
                Type       = Types.Int,
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };
            var prop2 = new CodeMemberProperty()
            {
                Name       = "Prop2",
                HasSet     = true,
                Type       = Types.Int,
                Attributes = MemberAttributes.Public
            };

            prop1.GetStatements.Add(new CodeMethodReturnStatement(FieldReferenceExpression.Default("increment")));
            prop1.SetStatements.Add(
                new CodeAssignStatement(FieldReferenceExpression.Default("increment"),
                                        new CodePropertySetValueReferenceExpression()));
            prop2.SetStatements.Add(new CodeThrowExceptionStatement(
                                        new CodeObjectCreateExpression(new CodeTypeReference("Exception"))));

            classDeclaration.Members.Add(prop1);
            classDeclaration.Members.Add(prop2);

            var constructor = new CodeConstructor();

            constructor.Attributes = (constructor.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Family;

            constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "count"));
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "increment"));

            constructor.Statements.Add(new CodeAssignStatement(
                                           FieldReferenceExpression.This("count"),
                                           new CodeArgumentReferenceExpression("count")));
            constructor.Statements.Add(new CodeAssignStatement(
                                           FieldReferenceExpression.This("increment"),
                                           new CodeArgumentReferenceExpression("increment")));

            classDeclaration.Members.Add(constructor);
            classDeclaration.Attributes = (classDeclaration.Attributes & ~MemberAttributes.AccessMask) |
                                          MemberAttributes.FamilyOrAssembly;

            var method = new CodeMemberMethod()
            {
                Name       = "IncrementAndGet",
                ReturnType = Types.Int,
                Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final
            };

            method.Statements.Add(comment);
            method.Statements.Add(
                new CodeOperationAssignmentStatement(
                    FieldReferenceExpression.Default("count"),
                    CodeBinaryOperatorTypeMore.Add,
                    FieldReferenceExpression.Default("increment")).AsAssignStatement());
            method.Statements.Add(new CodeMethodReturnStatement(FieldReferenceExpression.Default("count")));

            classDeclaration.Members.Add(method);

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

            codeNamespace.Comments.Add(comment);
            codeNamespace.Comments.Add(docComment);

            classDeclaration.Comments.Add(docComment);
            classDeclaration.Comments.Add(docComment);

            method.Comments.Add(comment);

            return(compileUnit);
        }
Beispiel #41
0
 public CodeMemberField Field(string fieldName)
 {
     var field = new CodeMemberField(typeof(object), fieldName)
     {
         Attributes = MemberAttributes.Public,
     };
     CurrentType.Members.Add(field);
     return field;
 }
Beispiel #42
0
        public override void Create()
        {
            System.Windows.Forms.MessageBox.Show("请选择要输出的目录");
            if (dlgSavePath.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            string outputPath = dlgSavePath.SelectedPath;
            Dictionary <string, List <RefKeyMap> > refEntities = GetFKMapping();

            foreach (Table table in project.Tables)
            {
                Stream       s  = File.Open(outputPath + "\\" + table.Name + ".cs", FileMode.Create);
                StreamWriter sw = new StreamWriter(s, Encoding.Default);

                CSharpCodeProvider   cscProvider = new CSharpCodeProvider();
                ICodeGenerator       cscg        = cscProvider.CreateGenerator(sw);
                CodeGeneratorOptions cop         = new CodeGeneratorOptions();
                cop.BlankLinesBetweenMembers = false;
                cop.ElseOnClosing            = true;

                //Create Class Using Statements
                cscg.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("using System;"), sw, cop);
                cscg.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("using System.Collections.Generic;"), sw, cop);
                cscg.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("using System.Data;"), sw, cop);
                cscg.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("using System.Text;"), sw, cop);

                sw.WriteLine();

                //创建命名空间
                CodeNamespace cnsCodeDom = new CodeNamespace(Namespace);

                //创建类
                CodeTypeDeclaration ctd = new CodeTypeDeclaration();
                cnsCodeDom.Types.Add(ctd);
                ctd.IsClass = true;
                ctd.Name    = table.Name;
                ctd.BaseTypes.Add(project.Namespace + ".Entity." + table.Name); //继承 实体
                ctd.TypeAttributes = TypeAttributes.Public;


                foreach (RefKeyMap wmap in refEntities[table.Name])  //增加外键子元素的集合
                {
                    string fieldName = wmap.Col.Name + "s" + wmap.Table.Name + "s";

                    ctd.Members.Add(new CodeMemberField("List<" + wmap.Table.Name + ">", "_" + fieldName));

                    CodeMemberProperty cmp = new CodeMemberProperty();
                    cmp.Type       = new CodeTypeReference("List<" + wmap.Table.Name + ">");
                    cmp.Attributes = MemberAttributes.Public;
                    cmp.Name       = fieldName;
                    cmp.Comments.Add(new CodeCommentStatement("<summary>", true));
                    cmp.Comments.Add(new CodeCommentStatement("表示 [" + wmap.Col.Title + "] 的 [" + wmap.Table.Title + "] 集合", true));
                    cmp.Comments.Add(new CodeCommentStatement("</summary>", true));
                    cmp.HasGet = true;
                    cmp.GetStatements.Add(new CodeSnippetExpression(@"if (_" + fieldName + @" == null) {
                    if (this." + wmap.Col.Name + @" == null)
					    _"                     + fieldName + @" = new List<" + wmap.Table.Name + @">();
                    else
                        _" + fieldName + @" = db.Take<" + wmap.Table.Name + @">(""" + wmap.Col.Name + @"=@" + wmap.Col.Name + @""", Zippy.Helper.ZData.CreateParameter(""" + wmap.Col.Name + @""", this." + wmap.Col.RefCol + @"));
                }
                return _" + fieldName));
                    //cmp.HasSet = true;
                    //cmp.SetStatements.Add(new CodeSnippetExpression("_" + fieldName + " = value"));
                    ctd.Members.Add(cmp);
                }

                foreach (Col col in table.Cols) //找到外键映射的实体
                {
                    if (!string.IsNullOrEmpty(col.RefTable))
                    {
                        string fieldName = col.Name + "s" + col.RefTable + "";

                        ctd.Members.Add(new CodeMemberField(col.RefTable, "_" + fieldName));

                        CodeMemberProperty cmp = new CodeMemberProperty();
                        cmp.Type       = new CodeTypeReference(col.RefTable);
                        cmp.Attributes = MemberAttributes.Public;
                        cmp.Name       = fieldName;
                        cmp.Comments.Add(new CodeCommentStatement("<summary>", true));
                        cmp.Comments.Add(new CodeCommentStatement("表示 [" + col.Title + "] 对应的实体", true));
                        cmp.Comments.Add(new CodeCommentStatement("</summary>", true));
                        cmp.HasGet = true;
                        cmp.GetStatements.Add(new CodeSnippetExpression(@"if (_" + fieldName + @" == null) 
                    _" + fieldName + @" = db.FindUnique<" + col.RefTable + @">(""" + col.RefCol + @"=@" + col.RefCol + @""", Zippy.Helper.ZData.CreateParameter(""" + col.RefCol + @""", this." + col.Name + @"));
                return _" + fieldName));
                        //cmp.HasSet = true;
                        //cmp.SetStatements.Add(new CodeSnippetExpression("_" + fieldName + " = value"));
                        ctd.Members.Add(cmp);
                    }
                }

                CodeMemberField dbField = new CodeMemberField("Zippy.Data.IDalProvider", "db");
                dbField.Attributes = MemberAttributes.Public;
                ctd.Members.Add(dbField);

                CodeConstructor ctor0 = new CodeConstructor();
                ctd.Members.Add(ctor0);
                ctor0.Attributes = MemberAttributes.Public;
                ctor0.Statements.Add(new CodeSnippetExpression("db = Zippy.Data.DalFactory.CreateProvider()"));

                CodeConstructor ctor1 = new CodeConstructor();
                ctd.Members.Add(ctor1);
                ctor1.Parameters.Add(new CodeParameterDeclarationExpression("Zippy.Data.IDalProvider", "_db"));
                ctor1.Attributes = MemberAttributes.Public;
                ctor1.Statements.Add(new CodeSnippetExpression("db = _db"));

                Col colPK = FindPKCol(table);
                if (colPK != null)
                {
                    System.Data.DbType xtyppe = TypeConverter.ToDbType(colPK.DataType);
                    Type colType = ZippyCoder.TypeConverter.ToNetType(colPK.DataType);

                    ctd.Members.Add(CreateStaticMethod("FindUnique", table.Name, @"Zippy.Data.IDalProvider db = Zippy.Data.DalFactory.CreateProvider();
            return db.FindUnique<" + table.Name + ">(pkValue)", new CodeParameterDeclarationExpression(colType, "pkValue")));
                    ctd.Members.Add(CreateStaticMethod("FindUnique", table.Name, @"return db.FindUnique<" + table.Name + ">(pkValue)", new CodeParameterDeclarationExpression(colType, "pkValue"), new CodeParameterDeclarationExpression("Zippy.Data.IDalProvider", "db")));

                    ctd.Members.Add(CreateMethod("Delete", typeof(int), "return db.Delete<" + table.Name + ">(this." + colPK.Name + ")"));
                    ctd.Members.Add(CreateMethod("Insert", typeof(int), "int rtn = db.Insert<" + table.Name + @">(this); 
            this." + colPK.Name + @" = rtn;
            return rtn"));
                    ctd.Members.Add(CreateMethod("Update", typeof(int), "return db.Update<" + table.Name + ">(this)"));
                    ctd.Members.Add(CreateMethod("Save", typeof(bool), @"int rtn = 0;
            if (this." + colPK.Name + @" != null) 
                rtn = db.Update<" + table.Name + @">(this);
            else {
                rtn = db.Insert<" + table.Name + @">(this);
                this." + colPK.Name + @" = rtn;
            }
            return rtn > 0"));
                }


                ctd.Members.Add(CreateMethod("Take", "List<" + table.Name + ">", "return db.Take<" + table.Name + ">(true)"));
                ctd.Members.Add(CreateMethod("Take", "List<" + table.Name + ">", "return db.Take<" + table.Name + ">(count, true)", new CodeParameterDeclarationExpression(typeof(int), "count")));
                ctd.Members.Add(CreateMethod("Take", "List<" + table.Name + ">", "return db.Take<" + table.Name + ">(sqlEntry, cmdParameters)",
                                             new CodeParameterDeclarationExpression(typeof(string), "sqlEntry"),
                                             new CodeParameterDeclarationExpression("params System.Data.Common.DbParameter[]", "cmdParameters")));
                ctd.Members.Add(CreateMethod("Take", "Zippy.Data.Collections.PaginatedList<" + table.Name + ">", @"Zippy.Data.Collections.PaginatedList<" + table.Name + @"> rtn = new Zippy.Data.Collections.PaginatedList<" + table.Name + @">();           
            List<" + table.Name + @"> records = db.Take<" + table.Name + @">(where + "" order by "" + orderby, pageSize, pageNumber, cmdParameters);
            rtn.AddRange(records);
            rtn.PageIndex = pageNumber;
            rtn.PageSize = pageSize;
            rtn.TotalCount = db.Count<" + table.Name + @">(where, cmdParameters);
            return rtn",
                                             new CodeParameterDeclarationExpression(typeof(string), "where"),
                                             new CodeParameterDeclarationExpression(typeof(string), "orderby"),
                                             new CodeParameterDeclarationExpression(typeof(int), "pageSize"),
                                             new CodeParameterDeclarationExpression(typeof(int), "pageNumber"),
                                             new CodeParameterDeclarationExpression("params System.Data.Common.DbParameter[]", "cmdParameters")));


                cscg.GenerateCodeFromNamespace(cnsCodeDom, sw, cop);
                sw.Close();
                s.Close();
            }
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // GENERATES (C#):
        //  namespace NS {
        //  using System;
        //        public class Test {  
        //            public int NonStaticPublicField = 5;
        //        }
        //        public class Test2 {
        //            public int NonStaticPublicField = 5;
        //        }
        //    }  
        CodeNamespace ns = new CodeNamespace ("NS");
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        cu.Namespaces.Add (ns);

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

        CodeMemberField field = new CodeMemberField ();
        field.Name = "NonStaticPublicField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        class1.Members.Add (field);

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

        field = new CodeMemberField ();
        field.Name = "NonStaticPublicField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        class1.Members.Add (field);

        // GENERATES (C#):
        //    namespace NS2 {
        //        public class Test1 {   
        //            public static int TestingMethod(int i) {
        //                NS.Test temp1 = new NS.Test();
        //                NS.Test2 temp2 = new NS.Test2();
        //                temp1.NonStaticPublicField = i;
        //                temp2.NonStaticPublicField = (i * 10);
        //                int sum;
        //                sum = (temp1.NonStaticPublicField + temp2.NonStaticPublicField);
        //                return sum;
        //            }
        //        }
        //    }
        AddScenario ("CheckTestingMethod");
        ns = new CodeNamespace ("NS2");
        cu.Namespaces.Add (ns);

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

        CodeMemberMethod cmm = new CodeMemberMethod ();
        cmm.Name = "TestingMethod";
        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 ("NS.Test", "temp1", new CodeObjectCreateExpression ("NS.Test")));
        cmm.Statements.Add (new CodeVariableDeclarationStatement ("NS.Test2", "temp2", new CodeObjectCreateExpression ("NS.Test2")));
        cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("temp1"), "NonStaticPublicField")
            , new CodeArgumentReferenceExpression ("i")));
        cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("temp2"), "NonStaticPublicField")
            , new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Multiply, new CodePrimitiveExpression (10))));
        cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "sum"));
        cmm.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("sum"),
            new CodeBinaryOperatorExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("temp1"), "NonStaticPublicField"),
            CodeBinaryOperatorType.Add, new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("temp2"), "NonStaticPublicField"))));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("sum")));
        class1.Members.Add (cmm);
    }
        protected override void DoGenerate(CodeTypeDeclaration genClass)
        {
            genClass.BaseTypes.Add(typeof(QuerySproc));

            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            constructor.Name       = NameWithoutSpaces;
            constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(NameWithoutSpaces));
            constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(OutputDefaultConnectionStringName));
            genClass.Members.Add(constructor);

            var criteria   = new EmptyQuerySproc(Name, OutputDefaultConnectionStringName).CreateSprocCriteria();
            var cmd        = _cmdFac.CreateCommand(criteria, false);
            var sqlCommand = new SqlCommand
            {
                CommandText = cmd.CommandText,
                CommandType = CommandType.StoredProcedure,
                Connection  = (SqlConnection)cmd.Connection
            };

            using (var conn = sqlCommand.Connection)
            {
                conn.Open();
                SqlCommandBuilder.DeriveParameters(sqlCommand);
                conn.Close();
            }

            foreach (SqlParameter parameter in sqlCommand.Parameters)
            {
                var paramName = parameter.ParameterName.TrimStart('@');
                var field     = new CodeMemberField();
                field.Name       = "_" + paramName;
                field.Attributes = MemberAttributes.Private;
                var paramType = GetSprocParameterType(parameter.DbType);
                field.Type           = new CodeTypeReference(paramType);
                field.InitExpression = new CodeObjectCreateExpression(
                    field.Type,
                    paramType == typeof(StringParameterExpression) ?
                    new CodeExpression[] { new CodePrimitiveExpression(paramName), CreateSprocParameterDirectionEnumExpression(parameter.Direction), new CodePrimitiveExpression(IsUnicodeDbType(parameter.DbType)) }
                        :
                    new CodeExpression[] { new CodePrimitiveExpression(paramName), CreateSprocParameterDirectionEnumExpression(parameter.Direction) }
                    );
                genClass.Members.Add(field);

                var property = new CodeMemberProperty();
                property.Name       = paramName;
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                property.Type       = field.Type;
                property.HasGet     = true;
                property.HasSet     = false;
                property.GetStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            field.Name
                            )
                        )
                    );
                genClass.Members.Add(property);
            }
        }
Beispiel #45
0
 protected abstract void GenerateField(CodeMemberField e);
 protected virtual void GenerateEnumItem(CodeMemberField codeField, EnumMap.EnumMapMember emem)
 {
 }
Beispiel #47
0
    void GenerateCode()
    {
        Directory.CreateDirectory (OutputDir);

        Provider = new CSharpCodeProvider ();
        CodeGenOptions = new CodeGeneratorOptions { BlankLinesBetweenMembers = false };

        CodeTypeDeclaration libDecl = null;

        // Generate Libs class
        {
            var cu = new CodeCompileUnit ();
            var ns = new CodeNamespace (Namespace);
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
            cu.Namespaces.Add (ns);

            var decl = new CodeTypeDeclaration ("Libs");

            var field = new CodeMemberField (new CodeTypeReference ("CppLibrary"), LibBaseName);
            field.Attributes = MemberAttributes.Public|MemberAttributes.Static;
            field.InitExpression = new CodeObjectCreateExpression (new CodeTypeReference ("CppLibrary"), new CodeExpression [] { new CodePrimitiveExpression (LibBaseName) });
            decl.Members.Add (field);

            ns.Types.Add (decl);

            libDecl = decl;

            //Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
            using (TextWriter w = File.CreateText (Path.Combine (OutputDir, "Libs.cs"))) {
                Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
            }
        }

        // Generate user classes
        foreach (Class klass in Classes) {
            if (klass.Disable)
                continue;

            var cu = new CodeCompileUnit ();
            var ns = new CodeNamespace (Namespace);
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("Mono.VisualC.Interop"));
            cu.Namespaces.Add (ns);

            ns.Types.Add (klass.GenerateClass (this, libDecl, LibBaseName));

            //Provider.GenerateCodeFromCompileUnit(cu, Console.Out, CodeGenOptions);
            using (TextWriter w = File.CreateText (Path.Combine (OutputDir, klass.Name + ".cs"))) {
                // These are reported for the fields of the native layout structures
                Provider.GenerateCodeFromCompileUnit (new CodeSnippetCompileUnit("#pragma warning disable 0414, 0169"), w, CodeGenOptions);
                Provider.GenerateCodeFromCompileUnit(cu, w, CodeGenOptions);
            }
        }
    }
        public void Generate()
        {
            var errorEnum = this.generator.Types.SingleOrDefault(t => t.Name.EndsWith("Error"));

            if (errorEnum == null)
            {
                return;
            }

            // Add the exception type

            // Generate the {Name}Exception class
            CodeTypeDeclaration exceptionType = new CodeTypeDeclaration();

            exceptionType.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            exceptionType.Name       = $"{this.generator.Name}Exception";
            exceptionType.BaseTypes.Add(typeof(Exception));
            exceptionType.Comments.Add(
                new CodeCommentStatement(
                    $"Represents an exception that occurred when interacting with the {this.generator.Name} API.",
                    true));
            exceptionType.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(
                        typeof(SerializableAttribute))));

            var defaultConstrutor = new CodeConstructor();

            defaultConstrutor.Attributes = MemberAttributes.Public;
            defaultConstrutor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class.\r\n </summary>",
                    true));
            exceptionType.Members.Add(defaultConstrutor);

            // Add the constructor which takes an error code
            var errorConstructor = new CodeConstructor();

            errorConstructor.Attributes = MemberAttributes.Public;
            errorConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class with a specified error code.\r\n </summary>",
                    true));
            errorConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"error\">\r\n The error code of the error that occurred.\r\n </param>",
                    true));
            errorConstructor.BaseConstructorArgs.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(string)),
                        "Format"),
                    new CodePrimitiveExpression($"An {this.generator.Name} error occurred. The error code was {{0}}"),
                    new CodeArgumentReferenceExpression("error")));
            errorConstructor.Statements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "errorCode"),
                    new CodeArgumentReferenceExpression("error")));
            errorConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference($"{this.generator.Name}Error"),
                    "error"));
            exceptionType.Members.Add(errorConstructor);

            // Add the constructor which takes an error code and an error message
            var errorWithMessageConstructor = new CodeConstructor();

            errorWithMessageConstructor.Attributes = MemberAttributes.Public;
            errorWithMessageConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class with a specified error code and error message.\r\n <summary>",
                    true));
            errorWithMessageConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"error\">\r\n The error code of the error that occurred.\r\n </param>",
                    true));
            errorWithMessageConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"message\">\r\n A message which describes the error.\r\n </param>",
                    true));
            errorWithMessageConstructor.BaseConstructorArgs.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(string)),
                        "Format"),
                    new CodePrimitiveExpression($"An {this.generator.Name} error occurred. {{1}}. The error code was {{0}}"),
                    new CodeArgumentReferenceExpression("error"),
                    new CodeArgumentReferenceExpression("message")));
            errorWithMessageConstructor.Statements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "errorCode"),
                    new CodeArgumentReferenceExpression("error")));
            errorWithMessageConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference($"{this.generator.Name}Error"),
                    "error"));
            errorWithMessageConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)),
                    "message"));
            exceptionType.Members.Add(errorWithMessageConstructor);

            // Add the Error field
            var errorCodeField = new CodeMemberField();

            errorCodeField.Name = "errorCode";
            errorCodeField.Type = new CodeTypeReference($"{this.generator.Name}Error");
            errorCodeField.Comments.Add(
                new CodeCommentStatement(
                    "<summary>\r\n Backing field for the <see cref=\"ErrorCode\"/> property.\r\n </summary>",
                    true));
            exceptionType.Members.Add(errorCodeField);

            var errorCodeProperty = new CodeMemberProperty();

            errorCodeProperty.Attributes = MemberAttributes.Public;
            errorCodeProperty.Name       = "ErrorCode";
            errorCodeProperty.Type       = new CodeTypeReference($"{this.generator.Name}Error");
            errorCodeProperty.HasGet     = true;
            errorCodeProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "errorCode")));
            errorCodeProperty.Comments.Add(
                new CodeCommentStatement(
                    "<summary>\r\n Gets the error code that represents the error.\r\n </summary>",
                    true));
            exceptionType.Members.Add(errorCodeProperty);

            var messageConstructor = new CodeConstructor();

            messageConstructor.Attributes = MemberAttributes.Public;
            messageConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class with a specified error message.\r\n</summary>",
                    true));
            messageConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"message\">\r\n The message that describes the error.\r\n</param>",
                    true));
            messageConstructor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("message"));
            messageConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(string),
                    "message"));
            exceptionType.Members.Add(messageConstructor);

            var messageAndInnerConstructor = new CodeConstructor();

            messageAndInnerConstructor.Attributes = MemberAttributes.Public;
            messageAndInnerConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.\r\n </summary>",
                    true));
            messageAndInnerConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"message\">\r\n The error message that explains the reason for the exception.\r\n </param>",
                    true));
            messageAndInnerConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"inner\">\r\n The exception that is the cause of the current exception, or <see langword=\"null\"/> if no inner exception is specified.\r\n </param>",
                    true));
            messageAndInnerConstructor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("message"));
            messageAndInnerConstructor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("inner"));
            messageAndInnerConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(string),
                    "message"));
            messageAndInnerConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(Exception),
                    "inner"));
            exceptionType.Members.Add(messageAndInnerConstructor);

            var serializedConstructor = new CodeConstructor();

            serializedConstructor.Attributes = MemberAttributes.Family;
            serializedConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<summary>\r\n Initializes a new instance of the <see cref=\"{exceptionType.Name}\"/> class with serialized data.\r\n </summary>",
                    true));
            serializedConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"info\">\r\n The <see cref=\"System.Runtime.Serialization.SerializationInfo\"/> that holds the serialized object data about the exception being thrown.\r\n </param>",
                    true));
            serializedConstructor.Comments.Add(
                new CodeCommentStatement(
                    $"<param name=\"context\">\r\n The <see cref=\"System.Runtime.Serialization.StreamingContext\"/> that contains contextual information about the source or destination.\r\n </param>",
                    true));
            serializedConstructor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("info"));
            serializedConstructor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("context"));
            serializedConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(SerializationInfo),
                    "info"));
            serializedConstructor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(StreamingContext),
                    "context"));
            serializedConstructor.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "!core"));
            exceptionType.Members.Add(serializedConstructor);
            serializedConstructor.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, "!core"));

            this.generator.AddType(exceptionType.Name, exceptionType);

            CodeTypeDeclaration extensionsType = new CodeTypeDeclaration();

            extensionsType.Name       = $"{errorEnum.Name}Extensions";
            extensionsType.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            // Add the ThrowOnError method
            CodeMemberMethod throwOnErrorMethod = new CodeMemberMethod();

            throwOnErrorMethod.Name       = "ThrowOnError";
            throwOnErrorMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;

            var parameter = new CodeParameterDeclarationExpression();

            parameter.Name = "value";
            parameter.Type = new CodeTypeReference("this " + errorEnum.Name);
            throwOnErrorMethod.Parameters.Add(parameter);

            throwOnErrorMethod.Statements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeArgumentReferenceExpression("value"),
                        CodeBinaryOperatorType.IdentityInequality,
                        new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(errorEnum.Name),
                            "Success")),
                    new CodeThrowExceptionStatement(
                        new CodeObjectCreateExpression(
                            new CodeTypeReference(exceptionType.Name),
                            new CodeArgumentReferenceExpression("value")))));

            extensionsType.Members.Add(throwOnErrorMethod);

            // Add the ThrowOnError overload which takes an error message
            CodeMemberMethod throwOnErrorWithMessageMethod = new CodeMemberMethod();

            throwOnErrorWithMessageMethod.Name       = "ThrowOnError";
            throwOnErrorWithMessageMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;

            var throwOnErrorWithMessageMethodParameter = new CodeParameterDeclarationExpression();

            throwOnErrorWithMessageMethodParameter.Name = "value";
            throwOnErrorWithMessageMethodParameter.Type = new CodeTypeReference("this " + errorEnum.Name);
            throwOnErrorWithMessageMethod.Parameters.Add(throwOnErrorWithMessageMethodParameter);

            var messageParameter = new CodeParameterDeclarationExpression();

            messageParameter.Name = "message";
            messageParameter.Type = new CodeTypeReference(typeof(string));
            throwOnErrorWithMessageMethod.Parameters.Add(messageParameter);

            throwOnErrorWithMessageMethod.Statements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeArgumentReferenceExpression("value"),
                        CodeBinaryOperatorType.IdentityInequality,
                        new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(errorEnum.Name),
                            "Success")),
                    new CodeThrowExceptionStatement(
                        new CodeObjectCreateExpression(
                            new CodeTypeReference(exceptionType.Name),
                            new CodeArgumentReferenceExpression("value"),
                            new CodeArgumentReferenceExpression("message")))));

            extensionsType.Members.Add(throwOnErrorWithMessageMethod);

            // Add the CheckError method
            CodeMemberMethod isErrorMethod = new CodeMemberMethod();

            isErrorMethod.Name       = "IsError";
            isErrorMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            isErrorMethod.ReturnType = new CodeTypeReference(typeof(bool));

            isErrorMethod.Parameters.Add(parameter);

            isErrorMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeArgumentReferenceExpression("value"),
                        CodeBinaryOperatorType.IdentityInequality,
                        new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(errorEnum.Name),
                            "Success"))));

            extensionsType.Members.Add(isErrorMethod);

            this.generator.AddType(extensionsType.Name, extensionsType);
        }
        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");
        }
Beispiel #50
0
        public override void ModifyImplementation(CodeNamespace cns, CodeTypeDeclaration ctd, Type type)
        {
            if (implementation == NullableImplementation.Default || implementation == NullableImplementation.Abstract)
            {
                ctd.BaseTypes.Add(new CodeTypeReference("INullable"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name       = "IsNull";
                prop.Type       = new CodeTypeReference(typeof(bool));
                prop.Attributes = MemberAttributes.Public;
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
                ctd.Members.Add(prop);
            }
            if (implementation != NullableImplementation.Abstract)
            {
                CodeTypeDeclaration newType = new CodeTypeDeclaration("Null" + ctd.Name);
                newType.TypeAttributes = TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed;
                newType.BaseTypes.Add(new CodeTypeReference(ctd.Name));
                cns.Types.Add(newType);

                System.Reflection.ConstructorInfo baseCtor = MainClass.GetBaseCtor(type);
                if (baseCtor != null)
                {
                    CodeConstructor ctor = new CodeConstructor();
                    ctor.Attributes = MemberAttributes.Private;
                    foreach (object o in baseCtor.GetParameters())
                    {
                        ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(null));
                    }
                    newType.Members.Add(ctor);
                }

                CodeMemberField field = new CodeMemberField(newType.Name, "Instance");
                field.Attributes     = MemberAttributes.Static | MemberAttributes.Assembly;
                field.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference(newType.Name));
                newType.Members.Add(field);

                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name       = "IsNull";
                prop.Type       = new CodeTypeReference(typeof(bool));
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
                newType.Members.Add(prop);

                CodeMemberMethod method = new CodeMemberMethod();
                method.Name       = "AcceptVisitor";
                method.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                method.Parameters.Add(new CodeParameterDeclarationExpression("IAstVisitor", "visitor"));
                method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "data"));
                method.ReturnType = new CodeTypeReference(typeof(object));
                method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
                newType.Members.Add(method);

                method            = new CodeMemberMethod();
                method.Name       = "ToString";
                method.Attributes = MemberAttributes.Public | MemberAttributes.Override;
                method.ReturnType = new CodeTypeReference(typeof(string));
                method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("[" + newType.Name + "]")));
                newType.Members.Add(method);

                prop            = new CodeMemberProperty();
                prop.Name       = "Null";
                prop.Type       = new CodeTypeReference(ctd.Name);
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                if (implementation == NullableImplementation.Shadow)
                {
                    prop.Attributes |= MemberAttributes.New;
                }
                CodeExpression ex = new CodeTypeReferenceExpression(newType.Name);
                ex = new CodePropertyReferenceExpression(ex, "Instance");
                prop.GetStatements.Add(new CodeMethodReturnStatement(ex));
                ctd.Members.Add(prop);
            }
        }
        public void Properties()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));

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

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

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

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

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

            class1.Members.Add(overrideProp);

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

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

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

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

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

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

            AssertEqual(ns,
                @"Imports System
                  Namespace NS
                      Public Class Test
                          Inherits System.Exception
                          Private int1 As Integer
                          Private tempString As String
                          Public Overridable Property prop1() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Public Overrides Property Text() As String
                              Get
                                  Return ""Hello World""
                              End Get
                              Set
                                  tempString = value
                              End Set
                          End Property
                          Private Property PrivateProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Protected Overridable Property FamilyProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Friend Overridable Property AssemblyProp() As Integer
                              Get
                                  Return (int1 + 1)
                              End Get
                              Set
                                  int1 = value
                              End Set
                          End Property
                          Public Shared ReadOnly Property staticProp() As Integer
                              Get
                                  Return 99
                              End Get
                          End Property
                          Public Overridable Function thisRef(ByVal value As Integer) As Integer
                              Me.privProp1 = value
                              Return Me.privProp1
                          End Function
                          Public Overridable Function setProp(ByVal value As Integer) As Integer
                              Me.prop1 = value
                              Return int1
                          End Function
                      End Class
                  End Namespace");
        }
        private void AddGetHashCodeMethod(CodeTypeDeclaration declaration)
        {
            // Generates code like like

            // private int? _hashcode;
            //
            // public override int GetHashCode()
            // {
            //     if(_hashcode == null)
            //     {
            //         _hashcode = _fullPath.GetHashCode() ^ ....;
            //     }
            //
            //     return _hashcode.Value;
            // }

            var hashcodeField = new CodeMemberField(typeof(int?), "_hashcode");

            var method = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Override,
                Name       = "GetHashCode",
                ReturnType = new CodeTypeReference(typeof(int))
            };

            Verify.That(_dataTypeDescriptor.KeyPropertyNames.Count > 0, "A dynamic type should have at least one key property");

            CodeExpression hashCodeExpression = null;

#warning We DO want IDataId classes to reflect both id and VersionId for data, right?
            foreach (string keyPropertyName in _dataTypeDescriptor.PhysicalKeyFields.Select(f => f.Name))
            {
                string propertyFieldName = MakePropertyFieldName(_dataTypeDescriptor.Fields[keyPropertyName].Name);

                CodeExpression hashCodePart =
                    new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), propertyFieldName),
                        "GetHashCode");

                if (hashCodeExpression == null)
                {
                    hashCodeExpression = hashCodePart;
                }
                else
                {
                    hashCodeExpression = new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(DataProviderHelperBase)),
                                                          "Xor"),
                        hashCodeExpression, hashCodePart);
                }
            }

            // "this.__hashcode"
            var hashCodeFieldReference =
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_hashcode");

            method.Statements.Add(new CodeConditionStatement(
                                      new CodeBinaryOperatorExpression(hashCodeFieldReference,
                                                                       CodeBinaryOperatorType.ValueEquality,
                                                                       new CodePrimitiveExpression(null)),
                                      new CodeAssignStatement(hashCodeFieldReference, hashCodeExpression)));

            // "return __hashcode.Value;"
            method.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(hashCodeFieldReference, "Value")));

            declaration.Members.Add(hashcodeField);
            declaration.Members.Add(method);
        }
        public void GlobalKeyword()
        {
            CodeNamespace ns = new CodeNamespace("Foo");
            ns.Comments.Add(new CodeCommentStatement("Foo namespace"));

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

            string fieldName1 = "_verifyGlobalGeneration1";
            CodeMemberField field = new CodeMemberField();
            field.Name = fieldName1;
            field.Type = new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference);
            field.Attributes = MemberAttributes.Public;
            field.InitExpression = new CodePrimitiveExpression(int.MaxValue);
            cd.Members.Add(field);

            string fieldName2 = "_verifyGlobalGeneration2";
            CodeMemberField field2 = new CodeMemberField();
            field2.Name = fieldName2;
            CodeTypeReference typeRef = new CodeTypeReference("System.Nullable", CodeTypeReferenceOptions.GlobalReference);
            typeRef.TypeArguments.Add(new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference));
            field2.Type = typeRef;
            field2.InitExpression = new CodePrimitiveExpression(0);
            cd.Members.Add(field2);

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "TestMethod01";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public | MemberAttributes.Static;
            method1.ReturnType = new CodeTypeReference(typeof(int));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(int.MaxValue)));
            cd.Members.Add(method1);

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

            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                              new CodeTypeReferenceExpression(new CodeTypeReference("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "TestMethod01"));
            CodeAssignStatement cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie);
            method2.Statements.Add(cas);
            method2.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn")));
            cd.Members.Add(method2);

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

            CodeMemberProperty property = new CodeMemberProperty();
            property.Name = "GlobalTestProperty1";
            property.Type = new CodeTypeReference(typeof(int));
            property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName1)));
            property.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName1), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property);

            CodeMemberProperty property2 = new CodeMemberProperty();
            property2.Name = "GlobalTestProperty2";
            property2.Type = typeRef;
            property2.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName2)));
            property2.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName2), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property2);

            AssertEqual(ns,
                @"'Foo namespace
                  Namespace Foo
                      Public Class Foo
                          Public _verifyGlobalGeneration1 As Integer = 2147483647
                          Private _verifyGlobalGeneration2 As Global.System.Nullable(Of Integer) = 0
                          Public Property GlobalTestProperty1() As Integer
                              Get
                                  Return _verifyGlobalGeneration1
                              End Get
                              Set
                                  _verifyGlobalGeneration1 = value
                              End Set
                          End Property
                          Public Property GlobalTestProperty2() As Global.System.Nullable(Of Integer)
                              Get
                                  Return _verifyGlobalGeneration2
                              End Get
                              Set
                                  _verifyGlobalGeneration2 = value
                              End Set
                          End Property
                          Public Shared Function TestMethod01() As Integer
                              Return 2147483647
                          End Function
                          Public Function TestMethod02() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.Foo.Foo.TestMethod01
                              Return iReturn
                          End Function
                          Public Function TestMethod03() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.System.Math.Abs(-1)
                              Return iReturn
                          End Function
                      End Class
                  End Namespace");
        }
Beispiel #54
0
        public string GenerateCode(string nameSpace, string className, string serviceName)
        {
            CodeHelper.CurrentCreatedSubTypes.Value = new Dictionary <Type, string>();
            var controllerTypeInfo = _microServiceProvider.ServiceNames[serviceName];

            CodeHelper.CurrentControllerType.Value = controllerTypeInfo.Type;

            System.Xml.XmlDocument xmldoc = null;
            var xmlpath = $"{Path.GetDirectoryName(controllerTypeInfo.Type.Assembly.Location)}/{Path.GetFileNameWithoutExtension(controllerTypeInfo.Type.Assembly.Location)}.xml";

            if (File.Exists(xmlpath))
            {
                xmldoc = new System.Xml.XmlDocument();
                xmldoc.Load(xmlpath);
            }
            XmlElement memberXmlNodeList = null;

            if (xmldoc != null)
            {
                CodeHelper.CurrentXmlMembersElement.Value = memberXmlNodeList = (XmlElement)xmldoc.DocumentElement.SelectSingleNode("members");
            }

            var methods = controllerTypeInfo.Methods.Select(m => m.Method).ToArray();

            //https://docs.microsoft.com/zh-cn/dotnet/api/system.codedom.codepropertysetvaluereferenceexpression?view=dotnet-plat-ext-3.1
            CodeCompileUnit unit = new CodeCompileUnit();

            //设置命名空间(这个是指要生成的类的空间)

            CodeNamespace codeNamespace = new CodeNamespace(nameSpace);

            unit.Namespaces.Add(codeNamespace);

            codeNamespace.Imports.Add(new CodeNamespaceImport("JMS"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Threading.Tasks"));

            CodeTypeDeclaration myClass = new CodeTypeDeclaration(className);

            CodeHelper.CurrentClassCode.Value = myClass;
            myClass.BaseTypes.Add(new CodeTypeReference("IImplInvoker"));
            codeNamespace.Types.Add(myClass);

            //添加ServiceName attribute
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("InvokerInfo", new CodeAttributeArgument(new CodePrimitiveExpression(serviceName)));

            myClass.CustomAttributes.Add(attr);

            foreach (var methodInfo in methods)
            {
                var methodcode = getMethodCode(methodInfo, false);
                var comment    = AddComment(methodcode, methodInfo, memberXmlNodeList);
                myClass.Members.Add(methodcode);

                codeNamespace.Comments.Add(new CodeCommentStatement(comment));

                methodcode = getMethodCode(methodInfo, true);
                AddComment(methodcode, methodInfo, memberXmlNodeList);
                myClass.Members.Add(methodcode);
            }

            CodeMemberField field = new CodeMemberField("JMS.IMicroService", "_microService");

            field.Attributes = MemberAttributes.Family;
            myClass.Members.Add(field);

            ///将构造方法添加到类中
            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            constructor.Parameters.Add(new CodeParameterDeclarationExpression("JMS.IMicroService", "microService"));
            constructor.Statements.Add(new CodeAssignStatement(
                                           new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_microService"),
                                           new CodeFieldReferenceExpression(null, "microService")
                                           ));
            myClass.Members.Add(constructor);


            //添加特特性
            //myClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializeField))));


            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");


            CodeGeneratorOptions options = new CodeGeneratorOptions();

                        //代码风格:大括号的样式{}
                        options.BracingStyle = "C";

            //是否在字段、属性、方法之间添加空白行
            options.BlankLinesBetweenMembers = true;


                        //保存
            using (var ms = new System.IO.MemoryStream())
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ms, Encoding.UTF8))
                {
                                  provider.GenerateCodeFromCompileUnit(unit, sw, options);

                    sw.Flush();
                    return(Encoding.UTF8.GetString(ms.ToArray()));
                }
        }
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var ns = new CodeNamespace();
            ns.Name = "MyNamespace";
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(ns);

            var attrs = cu.AssemblyCustomAttributes;
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));

            var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
            ns.Types.Add(class1);

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

            var method1 = new CodeMemberMethod() { Name = "MyMethod" };
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
            var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
            param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param1);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.CustomAttributes.Add(
                        new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference(typeof(string));
            function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
            function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
            class1.Members.Add(function1);

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

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

            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "MyProperty";
            prop1.Type = new CodeTypeReference(typeof(string));
            prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
            class1.Members.Add(prop1);

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

            class1 = new CodeTypeDeclaration("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference("Form"));
            ns.Types.Add(class1);

            CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
            class1.Members.Add(mfield);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                                new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Text"), new CodePrimitiveExpression("Test")));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "TabIndex"), new CodePrimitiveExpression(0)));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                                new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
            ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                , new CodeThisReferenceExpression(), "b_Click")));
            class1.Members.Add(ctor);

            CodeMemberEvent evt = new CodeMemberEvent();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "b_Click";
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
            class1.Members.Add(cmm);

            AssertEqual(cu,
                @"'------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------

                  Option Strict Off
                  Option Explicit On

                  Imports System
                  Imports System.ComponentModel
                  Imports System.Drawing
                  Imports System.Windows.Forms
                  <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""),  _
                   Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""),  _
                   Assembly: System.CLSCompliantAttribute(false)>

                  Namespace MyNamespace

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

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

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

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

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

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

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

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

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

                          Public Sub New()
                              MyBase.New
                              Me.Size = New Size(600, 600)
                              b.Text = ""Test""
                              b.TabIndex = 0
                              b.Location = New Point(400, 525)
                              AddHandler MyEvent, AddressOf Me.b_Click
                          End Sub

                          <System.CLSCompliantAttribute(false)>  _
                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
Beispiel #56
0
        private void AddClassVariableToCodeBase(GameDataVariable classVariable)
        {
            if (classVariable.VariableType.Contains("List"))
            {
                CodeMemberProperty publicProperty = new CodeMemberProperty();
                publicProperty.Attributes = MemberAttributes.Public;
                publicProperty.HasGet     = true;
                publicProperty.HasSet     = true;
                publicProperty.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(classVariable.PrivateVariableName), new CodeVariableReferenceExpression("value")));
                publicProperty.Name = classVariable.PublicVariableName;
                publicProperty.Type = new CodeTypeReference(classVariable.VariableType);
                CodeExpression getter = new CodeSnippetExpression(string.Format("return {0}", classVariable.PrivateVariableName));
                publicProperty.GetStatements.Add(getter);
                _codeBase.Namespaces[0].Types[0].Members.Add(publicProperty);

                CodeMemberField var = new CodeMemberField(classVariable.VariableType, classVariable.PrivateVariableName);
                var.Attributes     = MemberAttributes.Private;
                var.InitExpression = new CodeSnippetExpression("new " + classVariable.VariableType + "()");
                _codeBase.Namespaces[0].Types[0].Members.Add(var);
            }
            else if (classVariable.VariableType.Contains("I18n"))
            {
                CodeMemberProperty publicProperty = new CodeMemberProperty();
                publicProperty.Attributes = MemberAttributes.Public;
                publicProperty.HasGet     = true;
                publicProperty.HasSet     = true;
                publicProperty.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(classVariable.PrivateVariableName), new CodeVariableReferenceExpression("value")));
                publicProperty.Name = classVariable.PublicVariableName;
                publicProperty.Type = new CodeTypeReference(typeof(string));
                CodeExpression getter = new CodeSnippetExpression(string.Format("return {0}", classVariable.PrivateVariableName + ".GetText()"));
                publicProperty.GetStatements.Add(getter);
                _codeBase.Namespaces[0].Types[0].Members.Add(publicProperty);

                CodeMemberField privateVar = new CodeMemberField("I18nProperty", classVariable.PrivateVariableName);
                privateVar.Attributes = MemberAttributes.Private;
                _codeBase.Namespaces[0].Types[0].Members.Add(privateVar);
            }
            else if (_primitiveType.ContainsKey(classVariable.VariableType))
            {
                Type Type = _primitiveType[classVariable.VariableType];
                CodeMemberProperty publicProperty = new CodeMemberProperty();
                publicProperty.Attributes = MemberAttributes.Public;
                publicProperty.HasGet     = true;
                publicProperty.HasSet     = true;
                publicProperty.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(classVariable.PrivateVariableName), new CodeVariableReferenceExpression("value")));
                publicProperty.Name = classVariable.PublicVariableName;
                publicProperty.Type = new CodeTypeReference(Type);
                CodeExpression getter = new CodeSnippetExpression(string.Format("return {0}", classVariable.PrivateVariableName));
                publicProperty.GetStatements.Add(getter);
                _codeBase.Namespaces[0].Types[0].Members.Add(publicProperty);

                CodeMemberField privateVar = new CodeMemberField(Type, classVariable.PrivateVariableName);
                privateVar.Attributes = MemberAttributes.Private;
                _codeBase.Namespaces[0].Types[0].Members.Add(privateVar);
            }
            else
            {
                CodeMemberProperty publicProperty = new CodeMemberProperty();
                publicProperty.Attributes = MemberAttributes.Public;
                publicProperty.HasGet     = true;
                publicProperty.HasSet     = true;
                publicProperty.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(classVariable.PrivateVariableName), new CodeVariableReferenceExpression("value")));
                publicProperty.Name = classVariable.PublicVariableName;
                publicProperty.Type = new CodeTypeReference(classVariable.VariableType.Replace(";", ""));
                CodeExpression getter = new CodeSnippetExpression(string.Format("return {0}", classVariable.PrivateVariableName));
                publicProperty.GetStatements.Add(getter);
                _codeBase.Namespaces[0].Types[0].Members.Add(publicProperty);

                CodeMemberField var = new CodeMemberField(classVariable.VariableType.Replace(";", ""), classVariable.PrivateVariableName);
                _codeBase.Namespaces[0].Types[0].Members.Add(var);
            }
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        CodeNamespace nspace = new CodeNamespace("NSPC");
        nspace.Imports.Add(new CodeNamespaceImport("System"));
        cu.Namespaces.Add(nspace);

        CodeTypeDeclaration cd = new CodeTypeDeclaration("TestFields");
        cd.IsClass = true;
        nspace.Types.Add(cd);

        // GENERATES (C#):
        //        public static int UseStaticPublicField(int i) {
        //            ClassWithFields.StaticPublicField = i;
        //            return ClassWithFields.StaticPublicField;
        //
        CodeMemberMethod cmm;
        if (Supports(provider, GeneratorSupport.PublicStaticMembers))
        {
          AddScenario("CheckUseStaticPublicField");
          cmm = new CodeMemberMethod();
          cmm.Name = "UseStaticPublicField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
              new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //        public static int UseNonStaticPublicField(int i) {
        //            ClassWithFields variable = new ClassWithFields();
        //            variable.NonStaticPublicField = i;
        //            return variable.NonStaticPublicField;
        //        }
        AddScenario("CheckUseNonStaticPublicField");
        cmm = new CodeMemberMethod();
        cmm.Name = "UseNonStaticPublicField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
        cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
            new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"),
            new CodeArgumentReferenceExpression("i")));
        cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
            CodeVariableReferenceExpression("variable"), "NonStaticPublicField")));
        cd.Members.Add(cmm);

        // GENERATES (C#):
        //        public static int UseNonStaticInternalField(int i) {
        //            ClassWithFields variable = new ClassWithFields();
        //            variable.NonStaticInternalField = i;
        //            return variable.NonStaticInternalField;
        //        }          

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
        {
          cmm = new CodeMemberMethod();
          AddScenario("CheckUseNonStaticInternalField");
          cmm.Name = "UseNonStaticInternalField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
              new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeVariableReferenceExpression("variable"), "NonStaticInternalField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //        public static int UseInternalField(int i) {
        //            ClassWithFields.InternalField = i;
        //            return ClassWithFields.InternalField;
        //        }
        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
        {
          AddScenario("CheckUseInternalField");
          cmm = new CodeMemberMethod();
          cmm.Name = "UseInternalField";
          cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
          cmm.ReturnType = new CodeTypeReference(typeof(int));
          cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
          cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "InternalField"),
              new CodeArgumentReferenceExpression("i")));
          cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
              CodeTypeReferenceExpression("ClassWithFields"), "InternalField")));
          cd.Members.Add(cmm);
        }

        // GENERATES (C#):
        //       public static int UseConstantField(int i) {
        //            return ClassWithFields.ConstantField;
        //        }
        AddScenario("CheckUseConstantField");
        cmm = new CodeMemberMethod();
        cmm.Name = "UseConstantField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
            CodeTypeReferenceExpression("ClassWithFields"), "ConstantField")));
        cd.Members.Add(cmm);

        // code a new class to test that the protected field can be accessed by classes that inherit it
        // GENERATES (C#):
        //    public class TestProtectedField : ClassWithFields {
        //        public static int UseProtectedField(int i) {
        //            ProtectedField = i;
        //            return ProtectedField;
        //        }
        //    }
        cd = new CodeTypeDeclaration("TestProtectedField");
        cd.BaseTypes.Add(new CodeTypeReference("ClassWithFields"));
        cd.IsClass = true;
        nspace.Types.Add(cd);

        cmm = new CodeMemberMethod();
        AddScenario("CheckUseProtectedField");
        cmm.Name = "UseProtectedField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference(typeof(int));
        cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
        CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression();
        reference.FieldName = "ProtectedField";
        reference.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
        cmm.Statements.Add(new CodeAssignStatement(reference,
            new CodeArgumentReferenceExpression("i")));
        cmm.Statements.Add(new CodeMethodReturnStatement(reference));
        cd.Members.Add(cmm);


        // declare class with fields
        //  GENERATES (C#):
        //            public class ClassWithFields {
        //                public static int StaticPublicField = 5;
        //                /*FamANDAssem*/ internal static int InternalField = 0;
        //                public const int ConstantField = 0;
        //                protected static int ProtectedField = 0;
        //                private static int PrivateField = 5;
        //                public int NonStaticPublicField = 5;
        //                /*FamANDAssem*/ internal int NonStaticInternalField = 0;
        //                public static int UsePrivateField(int i) {
        //                    PrivateField = i;
        //                    return PrivateField;
        //                }
        //            }
        cd = new CodeTypeDeclaration ("ClassWithFields");
        cd.IsClass = true;
        nspace.Types.Add (cd);

        CodeMemberField field;
        if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
            field = new CodeMemberField ();
            field.Name = "StaticPublicField";
            field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (5);
            cd.Members.Add (field);
        }

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
            field = new CodeMemberField ();
            field.Name = "InternalField";
            field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (0);
            cd.Members.Add (field);
        }

        field = new CodeMemberField ();
        field.Name = "ConstantField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Const;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (0);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "ProtectedField";
        field.Attributes = MemberAttributes.Family | MemberAttributes.Static;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (0);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "PrivateField";
        field.Attributes = MemberAttributes.Private | MemberAttributes.Static;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        cd.Members.Add (field);

        field = new CodeMemberField ();
        field.Name = "NonStaticPublicField";
        field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        field.Type = new CodeTypeReference (typeof (int));
        field.InitExpression = new CodePrimitiveExpression (5);
        cd.Members.Add (field);

        if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
            field = new CodeMemberField ();
            field.Name = "NonStaticInternalField";
            field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final;
            field.Type = new CodeTypeReference (typeof (int));
            field.InitExpression = new CodePrimitiveExpression (0);
            cd.Members.Add (field);
        }

        // create a method to test access to private field
        AddScenario ("CheckUsePrivateField");
        cmm = new CodeMemberMethod ();
        cmm.Name = "UsePrivateField";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
        CodeFieldReferenceExpression fieldref = new CodeFieldReferenceExpression ();
        fieldref.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
        fieldref.FieldName = "PrivateField";
        cmm.Statements.Add (new CodeAssignStatement (fieldref, new CodeArgumentReferenceExpression ("i")));
        cmm.Statements.Add (new CodeMethodReturnStatement (fieldref));
        cd.Members.Add (cmm);
    }
        protected override void OnBeforeCreateFirstForm()
        {
            //create background form variable
            CodeMemberField cmf = new CodeMemberField(typeof(ScreenSaverBackgroundForm[]), formBKName);

            cmf.Attributes = (MemberAttributes.Static | MemberAttributes.Public);
            typeDeclaration.Members.Add(cmf);
            //
            CodeMemberMethod mm = new CodeMemberMethod();

            typeDeclaration.Members.Add(mm);
            mm.Name       = "OnConfigure";
            mm.Attributes = MemberAttributes.Static;
            mm            = new CodeMemberMethod();
            typeDeclaration.Members.Add(mm);
            mm.Name       = "OnPreview";
            mm.Attributes = MemberAttributes.Static;
            //
            CodeMethodReferenceExpression mre = new CodeMethodReferenceExpression();

            mre.MethodName = "InitializeComponent";
            mainMethod.Statements.Add(new CodeExpressionStatement(
                                          new CodeMethodInvokeExpression(mre, new CodeExpression[] { })
                                          ));
            //
            //call ScreenSaverBackgroundForm.ParseScreensaverCommandLine(string[] args, out string cmd, out int parentHandle)
            CodeVariableDeclarationStatement cv1 = new CodeVariableDeclarationStatement();

            cv1.Type = new CodeTypeReference(typeof(int));
            cv1.Name = "parentHandle";
            mainMethod.Statements.Add(cv1);
            CodeVariableDeclarationStatement cv2 = new CodeVariableDeclarationStatement();

            cv2.Type = new CodeTypeReference(typeof(EnumScreenSaverStartType));
            cv2.Name = "sscmd";
            CodeMethodInvokeExpression cmi = new CodeMethodInvokeExpression();

            cmi.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(ScreenSaverBackgroundForm)), "ParseScreensaverCommandLine");
            cmi.Parameters.Add(new CodeVariableReferenceExpression("CommandArguments"));
            CodeDirectionExpression vr = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("parentHandle"));

            cmi.Parameters.Add(vr);

            cv2.InitExpression = cmi;
            mainMethod.Statements.Add(cv2);
            //
            CodeTypeReferenceExpression sss = new CodeTypeReferenceExpression(typeof(EnumScreenSaverStartType));
            //
            CodeVariableReferenceExpression sscmd = new CodeVariableReferenceExpression("sscmd");
            CodeConditionStatement          ccs   = new CodeConditionStatement();

            mainMethod.Statements.Add(ccs);
            ccs.Condition = new CodeBinaryOperatorExpression(sscmd, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(sss, "Config"));
            CodeMethodInvokeExpression cmi2 = new CodeMethodInvokeExpression();

            cmi2.Method            = new CodeMethodReferenceExpression();
            cmi2.Method.MethodName = "OnConfigure";
            ccs.TrueStatements.Add(new CodeExpressionStatement(cmi2));
            //
            CodeConditionStatement ccs2 = new CodeConditionStatement();

            ccs.FalseStatements.Add(ccs2);
            ccs2.Condition = new CodeBinaryOperatorExpression(sscmd, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(sss, "Preview"));
            //
            CodeConditionStatement ccs3 = new CodeConditionStatement();

            ccs2.FalseStatements.Add(ccs3);
            ccs3.Condition = new CodeBinaryOperatorExpression(sscmd, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(sss, "Password"));
            //
            CodeConditionStatement ccs4 = new CodeConditionStatement();

            ccs3.FalseStatements.Add(ccs4);
            ccs4.Condition = new CodeBinaryOperatorExpression(sscmd, CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(sss, "Start"));

            //
            CodeAssignStatement code = new CodeAssignStatement();

            code.Left = new CodeVariableReferenceExpression(formBKName);
            CodePropertyReferenceExpression sl = new CodePropertyReferenceExpression(
                new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(Screen)), "AllScreens"), "Length");
            CodeArrayCreateExpression ac = new CodeArrayCreateExpression(typeof(ScreenSaverBackgroundForm[]), sl);

            code.Right = ac;
            ccs4.TrueStatements.Add(code);
            //
            CodeMethodInvokeExpression mim = new CodeMethodInvokeExpression();

            mim.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursor)), "Hide");
            ccs4.TrueStatements.Add(new CodeExpressionStatement(mim));
            //
            CodeIterationStatement cis = new CodeIterationStatement();

            ccs4.TrueStatements.Add(cis);

            CodeVariableDeclarationStatement ii = new CodeVariableDeclarationStatement();

            ii.Name                = "i";
            ii.Type                = new CodeTypeReference(typeof(int));
            ii.InitExpression      = new CodePrimitiveExpression(0);
            cis.InitStatement      = ii;
            cis.TestExpression     = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, sl);
            cis.IncrementStatement = new CodeSnippetStatement("i++");
            CodeAssignStatement as1 = new CodeAssignStatement();

            as1.Left  = new CodeArrayIndexerExpression(new CodeVariableReferenceExpression(formBKName), new CodeVariableReferenceExpression("i"));
            as1.Right = new CodeObjectCreateExpression(BackGroundType, new CodeExpression[] { });
            cis.Statements.Add(as1);
            //
            CodeMethodInvokeExpression miv = new CodeMethodInvokeExpression();

            miv.Method = new CodeMethodReferenceExpression(as1.Left, "SetAllScreens");
            miv.Parameters.Add(new CodeVariableReferenceExpression(formBKName));
            cis.Statements.Add(new CodeExpressionStatement(miv));
            //
            CodeExpressionStatement cs;

            cs = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(typeof(Application)), "Run",
                    as1.Left));
            cis.Statements.Add(cs);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        if (!(provider is JScriptCodeProvider)) {
            // GENERATES (C#):
            //
            //  #region Compile Unit Region
            //  
            //  namespace Namespace1 {
            //      
            //      
            //      #region Outer Type Region
            //      // Outer Type Comment
            //      public class Class1 {
            //          
            //          // Field 1 Comment
            //          private string field1;
            //          
            //          public void Method1() {
            //              this.Event1(this, System.EventArgs.Empty);
            //          }
            //          
            //          #region Constructor Region
            //          public Class1() {
            //              #region Statements Region
            //              this.field1 = "value1";
            //              this.field2 = "value2";
            //              #endregion
            //          }
            //          #endregion
            //          
            //          public string Property1 {
            //              get {
            //                  return this.field1;
            //              }
            //          }
            //          
            //          public static void Main() {
            //          }
            //          
            //          public event System.EventHandler Event1;
            //          
            //          public class NestedClass1 {
            //          }
            //          
            //          public delegate void nestedDelegate1(object sender, System.EventArgs e);
            //          
            //  
            //          
            //          #region Field Region
            //          private string field2;
            //          #endregion
            //          
            //          #region Method Region
            //          // Method 2 Comment
            //          
            //          #line 500 "MethodLinePragma.txt"
            //          public void Method2() {
            //              this.Event2(this, System.EventArgs.Empty);
            //          }
            //          
            //          #line default
            //          #line hidden
            //          #endregion
            //          
            //          public Class1(string value1, string value2) {
            //          }
            //          
            //          #region Property Region
            //          public string Property2 {
            //              get {
            //                  return this.field2;
            //              }
            //          }
            //          #endregion
            //          
            //          #region Type Constructor Region
            //          static Class1() {
            //          }
            //          #endregion
            //          
            //          #region Event Region
            //          public event System.EventHandler Event2;
            //          #endregion
            //          
            //          #region Nested Type Region
            //          // Nested Type Comment
            //          
            //          #line 400 "NestedTypeLinePragma.txt"
            //          public class NestedClass2 {
            //          }
            //          
            //          #line default
            //          #line hidden
            //          #endregion
            //          
            //          #region Delegate Region
            //          public delegate void nestedDelegate2(object sender, System.EventArgs e);
            //          #endregion
            //          
            //          #region Snippet Region
            //  
            //          #endregion
            //      }
            //      #endregion
            //  }
            //  #endregion

            CodeNamespace ns = new CodeNamespace ("Namespace1");

            cu.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Compile Unit Region"));
            cu.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            cu.Namespaces.Add (ns);

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

            cd.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Outer Type Region"));
            cd.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            cd.Comments.Add (new CodeCommentStatement ("Outer Type Comment"));

            CodeMemberField field1 = new CodeMemberField (typeof (String), "field1");
            CodeMemberField field2 = new CodeMemberField (typeof (String), "field2");
            field1.Comments.Add (new CodeCommentStatement ("Field 1 Comment"));
            field2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Field Region"));
            field2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            CodeMemberEvent evt1 = new CodeMemberEvent ();
            evt1.Name = "Event1";
            evt1.Type = new CodeTypeReference (typeof (System.EventHandler));
            evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            CodeMemberEvent evt2 = new CodeMemberEvent ();
            evt2.Name = "Event2";
            evt2.Type = new CodeTypeReference (typeof (System.EventHandler));
            evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;

            evt2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Event Region"));
            evt2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeMemberMethod method1 = new CodeMemberMethod ();
            method1.Name = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            if (provider.Supports (GeneratorSupport.DeclareEvents)) {
                method1.Statements.Add (
                    new CodeDelegateInvokeExpression (
                        new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event1"),
                        new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            }


            CodeMemberMethod method2 = new CodeMemberMethod ();
            method2.Name = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            if (provider.Supports (GeneratorSupport.DeclareEvents)) {
                method2.Statements.Add (
                    new CodeDelegateInvokeExpression (
                        new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "Event2"),
                        new CodeExpression[] {
                        new CodeThisReferenceExpression(),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
                    }));
            }
            method2.LinePragma = new CodeLinePragma ("MethodLinePragma.txt", 500);
            method2.Comments.Add (new CodeCommentStatement ("Method 2 Comment"));

            method2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Method Region"));
            method2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeMemberProperty property1 = new CodeMemberProperty ();
            property1.Name = "Property1";
            property1.Type = new CodeTypeReference (typeof (string));
            property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property1.GetStatements.Add (
                new CodeMethodReturnStatement (
                    new CodeFieldReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "field1")));

            CodeMemberProperty property2 = new CodeMemberProperty ();
            property2.Name = "Property2";
            property2.Type = new CodeTypeReference (typeof (string));
            property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add (
                new CodeMethodReturnStatement (
                    new CodeFieldReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "field2")));

            property2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Property Region"));
            property2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeConstructor constructor1 = new CodeConstructor ();
            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement conState1 = new CodeAssignStatement (
                                        new CodeFieldReferenceExpression (
                                            new CodeThisReferenceExpression (),
                                            "field1"),
                                        new CodePrimitiveExpression ("value1"));
            conState1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Statements Region"));
            constructor1.Statements.Add (conState1);
            CodeStatement conState2 = new CodeAssignStatement (
                                        new CodeFieldReferenceExpression (
                                            new CodeThisReferenceExpression (),
                                            "field2"),
                                        new CodePrimitiveExpression ("value2"));
            conState2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));
            constructor1.Statements.Add (conState2);

            constructor1.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Constructor Region"));
            constructor1.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));

            CodeConstructor constructor2 = new CodeConstructor ();
            constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value1"));
            constructor2.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "value2"));

            CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor ();

            typeConstructor2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Type Constructor Region"));
            typeConstructor2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeEntryPointMethod methodMain = new CodeEntryPointMethod ();

            CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration ("NestedClass1");
            CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration ("NestedClass2");
            nestedClass2.LinePragma = new CodeLinePragma ("NestedTypeLinePragma.txt", 400);
            nestedClass2.Comments.Add (new CodeCommentStatement ("Nested Type Comment"));

            nestedClass2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Nested Type Region"));
            nestedClass2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));



            CodeTypeDelegate delegate1 = new CodeTypeDelegate ();
            delegate1.Name = "nestedDelegate1";
            delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender"));
            delegate1.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e"));

            CodeTypeDelegate delegate2 = new CodeTypeDelegate ();
            delegate2.Name = "nestedDelegate2";
            delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.Object"), "sender"));
            delegate2.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference ("System.EventArgs"), "e"));

            delegate2.StartDirectives.Add (new CodeRegionDirective (CodeRegionMode.Start, "Delegate Region"));
            delegate2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            CodeSnippetTypeMember snippet1 = new CodeSnippetTypeMember ();
            CodeSnippetTypeMember snippet2 = new CodeSnippetTypeMember ();

            CodeRegionDirective regionStart = new CodeRegionDirective (CodeRegionMode.End, "");
            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet2.StartDirectives.Add (regionStart);
            snippet2.EndDirectives.Add (new CodeRegionDirective (CodeRegionMode.End, string.Empty));


            cd.Members.Add (field1);
            cd.Members.Add (method1);
            cd.Members.Add (constructor1);
            cd.Members.Add (property1);
            cd.Members.Add (methodMain);

            if (Supports (provider, GeneratorSupport.DeclareEvents)) {
                cd.Members.Add (evt1);
            }

            if (Supports (provider, GeneratorSupport.NestedTypes)) {
                cd.Members.Add (nestedClass1);
                if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
                    cd.Members.Add (delegate1);
                }
            }

            cd.Members.Add (snippet1);

            cd.Members.Add (field2);
            cd.Members.Add (method2);
            cd.Members.Add (constructor2);
            cd.Members.Add (property2);


            if (Supports (provider, GeneratorSupport.StaticConstructors)) {
                cd.Members.Add (typeConstructor2);
            }

            if (Supports (provider, GeneratorSupport.DeclareEvents)) {
                cd.Members.Add (evt2);
            }
            if (Supports (provider, GeneratorSupport.NestedTypes)) {
                cd.Members.Add (nestedClass2);
                if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
                    cd.Members.Add (delegate2);
                }
            }
            cd.Members.Add (snippet2);
        }
#endif
    }
	protected override void GenerateField(CodeMemberField e)
			{
				// Bail out if not a class, struct, or enum.
				if(!IsCurrentClass && !IsCurrentStruct && !IsCurrentEnum)
				{
					return;
				}

				// Generate information about the field.
				if(!IsCurrentEnum)
				{
					OutputAttributeDeclarations(e.CustomAttributes);
					OutputMemberAccessModifier(e.Attributes);
					OutputFieldScopeModifier(e.Attributes);
					OutputTypeNamePair(e.Type, e.Name);
					if(e.InitExpression != null)
					{
						Output.Write(" = ");
						GenerateExpression(e.InitExpression);
					}
					Output.WriteLine(";");
				}
				else
				{
					OutputAttributeDeclarations(e.CustomAttributes);
					OutputIdentifier(e.Name);
					if(e.InitExpression != null)
					{
						Output.Write(" = ");
						GenerateExpression(e.InitExpression);
					}
					Output.WriteLine(",");
				}
			}