Example #1
0
 /// <summary>
 /// 有参
 /// </summary>
 /// <param name="inPars"></param>
 public ItemConstruct(List<string> inPars)
 {
     construct = new CodeConstructor();
     for (int i = 0; i < inPars.Count; i++)
     {
         construct.Parameters.Add(new CodeParameterDeclarationExpression(inPars[i], "inArg" + i));
     }
     construct.Attributes = MemberAttributes.Public;
 }
Example #2
0
 protected override void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
 {
 }
        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");
        }
Example #4
0
 protected abstract void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c);
    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 override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        CodeNamespace ns = new CodeNamespace("Namespace1");

        cu.Namespaces.Add(ns);

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

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

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

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

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

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


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

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

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


        CodeConstructor constructor1 = new CodeConstructor();
        constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
        constructor1.Statements.Add(
            new CodeAssignStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(),
                    "field1"),
                new CodePrimitiveExpression("value1")));
        constructor1.Statements.Add(
            new CodeAssignStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(),
                    "field2"),
                new CodePrimitiveExpression("value2")));

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

        CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();

        CodeEntryPointMethod methodMain =  new CodeEntryPointMethod();

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


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

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



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

        if (Supports (provider, GeneratorSupport.EntryPointMethod))
            cd.Members.Add(methodMain);

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

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

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

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

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

        if (Supports(provider, GeneratorSupport.NestedTypes)) {
            cd.Members.Add(nestedClass2);
            if (Supports(provider, GeneratorSupport.DeclareDelegates)) {
                cd.Members.Add(delegate2);
            }
        }
#endif
    }
        public void RegionsSnippetsAndLinePragmas()
        {
            var cu = new CodeCompileUnit();
            CodeNamespace ns = new CodeNamespace("Namespace1");

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

            cu.Namespaces.Add(ns);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();

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

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

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

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

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

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

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

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

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

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

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

            cd.Members.Add(snippet1);

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

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

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

                  namespace Namespace1 {


                      #region Outer Type Region
                      // Outer Type Comment
                      public class Class1 {

                          // Field 1 Comment
                          private string field1;

                          #region Field Region
                          private string field2;
                          #endregion


                          #region Snippet Region
                  #endregion


                          #region Type Constructor Region
                          static Class1() {
                          }
                          #endregion

                          #region Constructor Region
                          public Class1() {
                              #region Statements Region
                              this.field1 = ""value1"";
                              this.field2 = ""value2"";
                #endregion
                        }
                #endregion

                        public Class1(string value1, string value2)
                        {
                        }

                        public string Property1
                        {
                            get
                            {
                                return this.field1;
                            }
                        }

                        #region Property Region
                        public string Property2
                        {
                            get
                            {
                                return this.field2;
                            }
                        }
                        #endregion

                        public event System.EventHandler Event1;

                        #region Event Region
                        public event System.EventHandler Event2;
                        #endregion

                        public void Method1()
                        {
                            this.Event1(this, System.EventArgs.Empty);
                        }

                        public static void Main()
                        {
                        }

                        #region Method Region
                        // Method 2 Comment

                #line 500 ""MethodLinePragma.txt""
                        public void Method2()
                        {
                            this.Event2(this, System.EventArgs.Empty);
                        }

                #line default
                #line hidden
                        #endregion

                        public class NestedClass1
                        {
                        }

                        public delegate void nestedDelegate1(object sender, System.EventArgs e);

                        #region Nested Type Region
                        // Nested Type Comment

                #line 400 ""NestedTypeLinePragma.txt""
                        public class NestedClass2
                        {
                        }

                #line default
                #line hidden
                        #endregion

                        #region Delegate Region
                        public delegate void nestedDelegate2(object sender, System.EventArgs e);
                        #endregion
                    }
                #endregion
                }
                  #endregion");
        }
 void IServiceContractGenerationExtension.GenerateContract(ServiceContractGenerationContext context)
 {
     CodeTypeDeclaration clientType = context.TypeFactory.CreateClassType();
     clientType.Name = NamingHelper.GetUniqueName(GetClientClassName(context.ContractType.Name), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMethodNameExist), context.Operations);
     CodeTypeReference contractTypeReference = context.ContractTypeReference;
     if (context.DuplexCallbackType == null)
     {
         clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ClientBase<>)).BaseType, new CodeTypeReference[] { context.ContractTypeReference }));
     }
     else
     {
         clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(DuplexClientBase<>)).BaseType, new CodeTypeReference[] { context.ContractTypeReference }));
     }
     clientType.BaseTypes.Add(context.ContractTypeReference);
     if (ClientCtorParamNames.Length != ClientCtorParamTypes.Length)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization", new object[0])));
     }
     for (int i = 0; i < ClientCtorParamNames.Length; i++)
     {
         if (ClientCtorParamNames[i].Length != ClientCtorParamTypes[i].Length)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization", new object[0])));
         }
         CodeConstructor constructor = new CodeConstructor();
         constructor.Attributes = MemberAttributes.Public;
         if (context.DuplexCallbackType != null)
         {
             constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(InstanceContext), inputInstanceName));
             constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(inputInstanceName));
         }
         for (int j = 0; j < ClientCtorParamNames[i].Length; j++)
         {
             constructor.Parameters.Add(new CodeParameterDeclarationExpression(ClientCtorParamTypes[i][j], ClientCtorParamNames[i][j]));
             constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(ClientCtorParamNames[i][j]));
         }
         clientType.Members.Add(constructor);
     }
     foreach (OperationContractGenerationContext context2 in context.Operations)
     {
         if (!context2.Operation.IsServerInitiated())
         {
             CodeTypeReference declaringTypeReference = context2.DeclaringTypeReference;
             GenerateClientClassMethod(clientType, contractTypeReference, context2.SyncMethod, this.tryAddHelperMethod, declaringTypeReference);
             if (context2.IsAsync)
             {
                 CodeMemberMethod beginMethod = GenerateClientClassMethod(clientType, contractTypeReference, context2.BeginMethod, this.tryAddHelperMethod, declaringTypeReference);
                 CodeMemberMethod endMethod = GenerateClientClassMethod(clientType, contractTypeReference, context2.EndMethod, this.tryAddHelperMethod, declaringTypeReference);
                 if (this.generateEventAsyncMethods)
                 {
                     GenerateEventAsyncMethods(context, clientType, context2.SyncMethod.Name, beginMethod, endMethod);
                 }
             }
         }
     }
     context.Namespace.Types.Add(clientType);
     context.ClientType = clientType;
     context.ClientTypeReference = ServiceContractGenerator.NamespaceHelper.GetCodeTypeReference(context.Namespace, clientType);
 }
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic)
        {
            const String tmpVarName = "temp";
            String       resMgrCtorParam;

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

            var suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)));

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

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

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

            // Emit _resMgr field.
            var ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            var field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName)
            {
                Attributes = MemberAttributes.Private
            };

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

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

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

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

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

            // Mark the ResMgr property as advanced
            var editorBrowsableStateTypeRef =
                new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };

            var editorBrowsableStateAdvanced     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced"));
            var editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", editorBrowsableStateAdvanced);

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

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

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

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

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

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

            var isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, field_resMgr, new CodePrimitiveExpression(null));

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

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

            var init = new CodeStatement[2];

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

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

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

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

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

            var newCulture = new CodePropertySetValueReferenceExpression();

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

            // Add a doc comment to Culture property
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true));
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
        }
Example #10
0
        public CodeCompileUnit GetCompleteCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit          = codeGenerationHelper.GetCodeCompileUnit(nameSpace, className);

            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;
            var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                PrefixRemovalList = appPrefs.FieldPrefixRemovalList
            };

            newType.BaseTypes.Add(string.Format("EntityTypeConfiguration<{0}{1}>", appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(Table.Name)));

            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.Add(new CodeSnippetStatement(TABS + "ToTable(\"" + Table.Name + "\");"));
            if (appPrefs.UseLazy)
            {
                constructor.Statements.Add(new CodeSnippetStatement(TABS + "LazyLoad();"));
            }

            if (UsesSequence)
            {
                var fieldName = FixPropertyWithSameClassName(Table.PrimaryKey.Columns[0].Name, Table.Name);
                constructor.Statements.Add(new CodeSnippetStatement(String.Format(TABS + "Id(x => x.{0}).Column(x => x.{1}).GeneratedBy.Sequence(\"{2}\")", Formatter.FormatText(fieldName), fieldName, appPrefs.Sequence)));
            }
            else if (Table.PrimaryKey != null && Table.PrimaryKey.Type == PrimaryKeyType.PrimaryKey)
            {
                var fieldName = FixPropertyWithSameClassName(Table.PrimaryKey.Columns[0].Name, Table.Name);
                constructor.Statements.Add(GetIdMapCodeSnippetStatement(appPrefs, Table, Table.PrimaryKey.Columns[0].Name, fieldName, Table.PrimaryKey.Columns[0].DataType, Formatter));
            }
            else if (Table.PrimaryKey != null)
            {
                constructor.Statements.Add(GetIdMapCodeSnippetStatement(Table.PrimaryKey, Table, Formatter));
            }

            // Many To One Mapping
            foreach (var fk in Table.ForeignKeys.Where(fk => fk.Columns.First().IsForeignKey&& appPrefs.IncludeForeignKeys))
            {
                var propertyName = appPrefs.NameFkAsForeignTable ? fk.UniquePropertyName : fk.Columns.First().Name;
                propertyName = Formatter.FormatSingular(propertyName);
                var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name);

                var propertyMapType = "HasRequired";
                if (fk.IsNullable)
                {
                    propertyMapType = "HasOptional";
                }

                var codeSnippet = string.Format(TABS + "{0}(x => x.{1}).WithMany(t => t.{2}).HasForeignKey(d => d.{3});", propertyMapType, fieldName, fk.Columns.First().ForeignKeyTableName, fk.Columns.First().ForeignKeyColumnName);
                constructor.Statements.Add(new CodeSnippetStatement(codeSnippet));
            }

            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var propertyName  = Formatter.FormatText(column.Name);
                var fieldName     = FixPropertyWithSameClassName(propertyName, Table.Name);
                var columnMapping = new DBColumnMapper().Map(column, fieldName, Formatter, appPrefs.IncludeLengthAndScale);
                constructor.Statements.Add(new CodeSnippetStatement(TABS + columnMapping));
            }

            if (appPrefs.IncludeHasMany)
            {
                Table.HasManyRelationships.ToList().ForEach(x => constructor.Statements.Add(new EFOneToMany(Formatter, pascalCaseTextFormatter).Create(x)));
            }

            newType.Members.Add(constructor);
            return(compileUnit);
        }
Example #11
0
        private static Type CreateClientImplementation(Type interfaceType)
        {
            Type clientType = null;

            if (!clientImplementations.TryGetValue(interfaceType, out clientType))
            {
                Type callbackType = interfaceType.FindInterfaces(
                    (t, o) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDuplexNodeEndpointClient <>),
                    null
                    )
                                    .FirstOrDefault();

                CodeDomProvider codedomProvider = CodeDomProvider.CreateProvider("CSharp");
                string          namespaceName   = "NodeService.StringTypedNodeEndpointClientAutoGeneratedClients";
                string          typeName        = "ImplementationOf" + interfaceType.Name;

                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                {
                    CodeNamespace codeNamespace = new CodeNamespace(namespaceName);
                    codeCompileUnit.Namespaces.Add(codeNamespace);

                    CodeTypeDeclaration clientDeclaration = new CodeTypeDeclaration(typeName);
                    if (callbackType == null)
                    {
                        clientDeclaration.BaseTypes.Add(typeof(StrongTypedNodeEndpointClient));
                    }
                    else
                    {
                        clientDeclaration.BaseTypes.Add(typeof(StrongTypedNodeEndpointClient <>).MakeGenericType(callbackType.GetGenericArguments()[0]));
                    }
                    clientDeclaration.BaseTypes.Add(interfaceType);
                    codeNamespace.Types.Add(clientDeclaration);

                    CodeConstructor clientConstructor = new CodeConstructor();
                    clientDeclaration.Members.Add(clientConstructor);
                    clientConstructor.Attributes = MemberAttributes.Public;
                    clientConstructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(INodeEndpointClientProvider), "provider"));
                    clientConstructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("provider"));
                    clientConstructor.Statements.Add(
                        new CodeExpressionStatement(
                            new CodeMethodInvokeExpression(
                                new CodeThisReferenceExpression(),
                                "Initialize",
                                new CodeTypeOfExpression(interfaceType)
                                )
                            )
                        );

                    var methodInfos = GetMethodInfos(interfaceType);

                    foreach (var methodInfo in methodInfos)
                    {
                        CodeMemberMethod clientMethod = new CodeMemberMethod();
                        clientDeclaration.Members.Add(clientMethod);
                        clientMethod.Attributes = MemberAttributes.Public;
                        clientMethod.Name       = methodInfo.Name;
                        clientMethod.ImplementationTypes.Add(methodInfo.DeclaringType);
                        clientMethod.ReturnType = new CodeTypeReference(methodInfo.ReturnType);
                        foreach (var parameterInfo in methodInfo.GetParameters())
                        {
                            clientMethod.Parameters.Add(new CodeParameterDeclarationExpression(parameterInfo.ParameterType, parameterInfo.Name));
                        }


                        if (methodInfo.ReturnType == typeof(void))
                        {
                            clientMethod.Statements.Add(
                                new CodeExpressionStatement(
                                    InvokeExecute(methodInfo)
                                    )
                                );
                        }
                        else if (methodInfo.ReturnType == typeof(Task))
                        {
                            clientMethod.Statements.Add(
                                new CodeMethodReturnStatement(
                                    InvokeExecuteTask(methodInfo)
                                    )
                                );
                        }
                        else if (methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
                        {
                            clientMethod.Statements.Add(
                                new CodeMethodReturnStatement(
                                    InvokeExecuteTask(methodInfo)
                                    )
                                );
                        }
                        else
                        {
                            clientMethod.Statements.Add(
                                new CodeMethodReturnStatement(
                                    new CodeCastExpression(
                                        methodInfo.ReturnType,
                                        InvokeExecute(methodInfo)
                                        )
                                    )
                                );
                        }
                    }
                }

                List <Type> interfaceTypes = new List <Type>();
                CollectType(interfaceType, interfaceTypes);

                string[] assemblies = new string[] { typeof(StrongTypedNodeEndpointClient).Assembly.Location }
                .Concat(typeof(StrongTypedNodeEndpointClient).Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n).Location))
                .Concat(typeof(XElement).Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n).Location))
                .Concat(interfaceTypes.Select(t => t.Assembly.Location))
                .Concat(interfaceTypes.SelectMany(t => t.Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n).Location)))
                .Where(s => s != null)
                .Distinct()
                .ToArray();

                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable      = false;
                options.GenerateInMemory        = true;
                options.IncludeDebugInformation = false;
                options.ReferencedAssemblies.AddRange(assemblies);

                CompilerResults result = codedomProvider.CompileAssemblyFromDom(options, codeCompileUnit);
                codedomProvider.Dispose();
                clientType = result.CompiledAssembly.GetType(namespaceName + "." + typeName);
                clientImplementations.Add(interfaceType, clientType);
            }
            return(clientType);
        }
Example #12
0
        public void Constructor0()
        {
            CodeConstructor cc = new CodeConstructor();

            Assert.AreEqual(MemberAttributes.Private | MemberAttributes.Final,
                            cc.Attributes, "#1");

            Assert.IsNotNull(cc.Comments, "#2");
            Assert.AreEqual(0, cc.Comments.Count, "#3");

            Assert.IsNotNull(cc.CustomAttributes, "#4");
            Assert.AreEqual(0, cc.CustomAttributes.Count, "#5");

            Assert.IsNotNull(cc.StartDirectives, "#6");
            Assert.AreEqual(0, cc.StartDirectives.Count, "#7");

            Assert.IsNotNull(cc.EndDirectives, "#8");
            Assert.AreEqual(0, cc.EndDirectives.Count, "#9");

            Assert.IsNotNull(cc.TypeParameters, "#10");
            Assert.AreEqual(0, cc.TypeParameters.Count, "#11");

            Assert.IsNull(cc.LinePragma, "#12");

            Assert.IsNotNull(cc.Name, "#13");
            Assert.AreEqual(".ctor", cc.Name, "#14");

            Assert.IsNotNull(cc.UserData, "#15");
            Assert.AreEqual(typeof(ListDictionary), cc.UserData.GetType(), "#16");
            Assert.AreEqual(0, cc.UserData.Count, "#17");

            Assert.IsNotNull(cc.ImplementationTypes, "#18");
            Assert.AreEqual(0, cc.ImplementationTypes.Count, "#19");

            Assert.IsNotNull(cc.Parameters, "#20");
            Assert.AreEqual(0, cc.Parameters.Count, "#21");

            Assert.IsNull(cc.PrivateImplementationType, "#22");

            Assert.IsNotNull(cc.ReturnType, "#23");
            Assert.AreEqual(typeof(void).FullName, cc.ReturnType.BaseType, "#24");

            Assert.IsNotNull(cc.ReturnTypeCustomAttributes, "#25");
            Assert.AreEqual(0, cc.ReturnTypeCustomAttributes.Count, "#26");

            Assert.IsNotNull(cc.Statements, "#27");
            Assert.AreEqual(0, cc.Statements.Count, "#28");

            string name = "mono";

            cc.Name = name;
            Assert.IsNotNull(cc.Name, "#29");
            Assert.AreSame(name, cc.Name, "#30");

            cc.Name = null;
            Assert.IsNotNull(cc.Name, "#31");
            Assert.AreEqual(string.Empty, cc.Name, "#32");

            CodeLinePragma clp = new CodeLinePragma("mono", 10);

            cc.LinePragma = clp;
            Assert.IsNotNull(cc.LinePragma, "#33");
            Assert.AreSame(clp, cc.LinePragma, "#34");

            cc.LinePragma = null;
            Assert.IsNull(cc.LinePragma, "#35");

            Assert.IsNotNull(cc.BaseConstructorArgs, "#36");
            Assert.AreEqual(0, cc.BaseConstructorArgs.Count, "#37");

            Assert.IsNotNull(cc.ChainedConstructorArgs, "#38");
            Assert.AreEqual(0, cc.ChainedConstructorArgs.Count, "#37");
        }
Example #13
0
        /// <summary>
        /// Generates the proxy class events.
        /// </summary>
        /// <param name="genClass">The generated class.</param>
        /// <param name="constructor">The generated class constructor.</param>
        /// <param name="interfaceType">Type of the interface.</param>
        /// <param name="sourceType">Type of the source.</param>
        static void GenerateProxyClassEvents(CodeTypeDeclaration genClass, CodeConstructor constructor, Type interfaceType, Type sourceType)
        {
            List <string> processed = new List <string>();

            foreach (Type type in GetInterfaceTypes(interfaceType)) //zos
            {
                foreach (EventInfo eventInfo in type.GetEvents())
                {
                    if (processed.Contains(eventInfo.Name))
                    {
                        continue;
                    }

                    processed.Add(eventInfo.Name);

                    // Event Definition
                    CodeMemberEvent genEvent = new CodeMemberEvent();
                    genEvent.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    genEvent.Name       = eventInfo.Name;
                    genEvent.Type       = new CodeTypeReference(eventInfo.EventHandlerType);

                    genClass.Members.Add(genEvent);

                    // Create event handler
                    CodeMemberMethod genMethod = new CodeMemberMethod();
                    genMethod.Name       = "On" + eventInfo.Name;
                    genMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final;
                    genMethod.ReturnType = new CodeTypeReference(typeof(void));

                    CodeDelegateInvokeExpression genEventDalegate = new CodeDelegateInvokeExpression(new CodeVariableReferenceExpression("eventDelegate"));

                    foreach (ParameterInfo paramInfo in eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters())
                    {
                        FieldDirection dir = FieldDirection.In;
                        Type           paramType;
                        if (paramInfo.ParameterType.IsByRef)
                        {
                            paramType = paramInfo.ParameterType.GetElementType();
                            if (paramInfo.IsOut)
                            {
                                dir = FieldDirection.Out;
                            }
                            else
                            {
                                dir = FieldDirection.Ref;
                            }
                        }
                        else
                        {
                            paramType = paramInfo.ParameterType;
                        }

                        genMethod.Parameters.Add(new CodeParameterDeclarationExpression(paramType, paramInfo.Name)
                        {
                            Direction = dir
                        });

                        if (paramInfo.ParameterType == typeof(object) && paramInfo.Name == "sender" && !paramInfo.ParameterType.IsByRef)
                        {
                            genEventDalegate.Parameters.Add(new CodeThisReferenceExpression());
                        }
                        else
                        {
                            genEventDalegate.Parameters.Add(new CodeDirectionExpression(dir, new CodeArgumentReferenceExpression(paramInfo.Name)));
                        }
                    }

                    genMethod.Statements.Add(new CodeVariableDeclarationStatement(eventInfo.EventHandlerType,
                                                                                  "eventDelegate",
                                                                                  new CodeVariableReferenceExpression(eventInfo.Name)));

                    genMethod.Statements.Add(new CodeConditionStatement(
                                                 new CodeBinaryOperatorExpression(
                                                     new CodeVariableReferenceExpression("eventDelegate"),
                                                     CodeBinaryOperatorType.IdentityInequality,
                                                     new CodePrimitiveExpression(null)
                                                     ),
                                                 new CodeExpressionStatement(genEventDalegate)
                                                 ));

                    genClass.Members.Add(genMethod);

                    // Subscribe to source event
                    constructor.Statements.Add(
                        new CodeAttachEventStatement(
                            new CodeEventReferenceExpression(
                                new CodeVariableReferenceExpression("_obj"),
                                eventInfo.Name),
                            new CodeMethodReferenceExpression(
                                new CodeThisReferenceExpression(),
                                genMethod.Name
                                )));
                }
            }
        }
Example #14
0
        static CodeCompileUnit GenerateProxyClass(Type interfaceType, Type sourceType, bool injectNamespace, out string typeFuleName)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Namespace
            //CodeNamespace ns = new CodeNamespace("Rubenhak.Utils.Gen");

            //Oleg Shilo: move "usings" into global namespace as Roslyn doesn't handle namespaces
            CodeNamespace global = new CodeNamespace();

            compileUnit.Namespaces.Add(global);
            global.Imports.Add(new CodeNamespaceImport("System"));

            CodeNamespace ns = global;

            if (injectNamespace)
            {
                ns = new CodeNamespace("CSScriptLibrary.DynamicTypes");
                compileUnit.Namespaces.Add(ns);
            }

            // Class
            string className = sourceType.Name;

            //className = className.Replace("`", "").Replace(">", "").Replace("<", ""); //zos future sanitizing for generic types
            className += "To" + interfaceType.Name + "Proxy";

            if (injectNamespace)
            {
                typeFuleName = ns.Name + "." + className;
            }
            else
            {
                typeFuleName = className;
            }

            CodeTypeDeclaration genClass = new CodeTypeDeclaration(className);

            // genClass.BaseTypes.Add(new CodeTypeReference(typeof(MarshalByRefObject))); // zos
            genClass.BaseTypes.Add(new CodeTypeReference(typeof(MarshalByRefObjectWithInfiniteLifetime)));
            genClass.BaseTypes.Add(new CodeTypeReference(interfaceType));
            ns.Types.Add(genClass);

            // Constructor
            CodeConstructor constructor = new CodeConstructor();

            genClass.Members.Add(constructor);
            constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(sourceType), "obj"));
            constructor.Statements.Add(new CodeAssignStatement(
                                           new CodeVariableReferenceExpression("_obj"),
                                           new CodeVariableReferenceExpression("obj")
                                           ));

            // Members
            genClass.Members.Add(new CodeMemberField(new CodeTypeReference(sourceType), "_obj")
            {
                Attributes = MemberAttributes.Public
            });

            // Properties
            GenerateProxyClassProperties(genClass, interfaceType, sourceType);

            // Methods
            GenerateProxyClassMethods(genClass, interfaceType, sourceType);

            // Events
            GenerateProxyClassEvents(genClass, constructor, interfaceType, sourceType);

            return(compileUnit);
        }
        public CodeCompileUnit GetCompleteCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit          = codeGenerationHelper.GetCodeCompileUnit(nameSpace, className);

            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;
            var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                PrefixRemovalList = appPrefs.FieldPrefixRemovalList
            };

            newType.BaseTypes.Add(string.Format("ClassMap<{0}{1}>", appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(Table.Name)));

            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.Add(new CodeSnippetStatement(TABS + "Table(\"" + Table.Name + "\");"));
            if (appPrefs.UseLazy)
            {
                constructor.Statements.Add(new CodeSnippetStatement(TABS + "LazyLoad();"));
            }

            if (UsesSequence)
            {
                var fieldName = FixPropertyWithSameClassName(Table.PrimaryKey.Columns[0].Name, Table.Name);
                constructor.Statements.Add(new CodeSnippetStatement(String.Format(TABS + "Id(x => x.{0}).Column(x => x.{1}).GeneratedBy.Sequence(\"{2}\")",
                                                                                  Formatter.FormatText(fieldName), fieldName, appPrefs.Sequence)));
            }
            else if (Table.PrimaryKey != null && Table.PrimaryKey.Type == PrimaryKeyType.PrimaryKey)
            {
                var fieldName = FixPropertyWithSameClassName(Table.PrimaryKey.Columns[0].Name, Table.Name);
                constructor.Statements.Add(GetIdMapCodeSnippetStatement(this.appPrefs, Table, Table.PrimaryKey.Columns[0].Name, fieldName, Table.PrimaryKey.Columns[0].DataType, Formatter));
            }
            else if (Table.PrimaryKey != null)
            {
                constructor.Statements.Add(GetIdMapCodeSnippetStatement(Table.PrimaryKey, Table, Formatter));
            }

            // Many To One Mapping
            foreach (var fk in Table.ForeignKeys.Where(fk => fk.Columns.First().IsForeignKey&& appPrefs.IncludeForeignKeys))
            {
                var    propertyName = appPrefs.NameFkAsForeignTable ? fk.UniquePropertyName : fk.Columns.First().Name;
                string name         = propertyName;
                propertyName = Formatter.FormatSingular(propertyName);
                var fieldName   = FixPropertyWithSameClassName(propertyName, Table.Name);
                var pkAlsoFkQty = (from fks in Table.ForeignKeys.Where(fks => fks.UniquePropertyName == name) select fks).Count();
                if (pkAlsoFkQty > 1)
                {
                    constructor.Statements.Add(new CodeSnippetStatement(string.Format(TABS + "References(x => x.{0}).Column(\"{1}\").ForeignKey(\"{2}\");", fieldName, fk.Columns.First().Name, fk.Columns.First().ConstraintName)));
                }
                else
                {
                    constructor.Statements.Add(new CodeSnippetStatement(string.Format(TABS + "References(x => x.{0}).Column(\"{1}\");", fieldName, fk.Columns.First().Name)));
                }
            }

            // Property Map
            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var propertyName  = Formatter.FormatText(column.Name);
                var fieldName     = FixPropertyWithSameClassName(propertyName, Table.Name);
                var columnMapping = new DBColumnMapper().Map(column, fieldName, Formatter, appPrefs.IncludeLengthAndScale);
                constructor.Statements.Add(new CodeSnippetStatement(TABS + columnMapping));
            }

            // Bag (HasMany in FluentMapping)
            if (appPrefs.IncludeHasMany)
            {
                Table.HasManyRelationships.ToList().ForEach(x => constructor.Statements.Add(new OneToMany(Formatter).Create(x)));
            }

            newType.Members.Add(constructor);
            return(compileUnit);
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

        // Namespace to hold test scenarios
        // GENERATES (C#):
        //        namespace NSPC {
        //            using System;
        //            using System.Drawing;
        //            using System.Windows.Forms;
        //            using System.ComponentModel;
        //            }
        AddScenario ("FindNamespaceComment");
        CodeNamespace nspace = new CodeNamespace ("NSPC");
        nspace.Comments.Add (new CodeCommentStatement (new CodeComment ("Namespace to hold test scenarios")));
        nspace.Imports.Add (new CodeNamespaceImport ("System"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
        cu.Namespaces.Add (nspace);

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

        // GENERATES (C#):    
        //    // Class has a method to test static constructors
        //    public class ClassWithMethod {
        //        // This method is used to test a static constructor
        //        public static int TestStaticConstructor(int a) {
        //            // Testing a line comment
        //            TestClass t = new TestClass();
        //            t.i = a;
        //            return t.i;
        //        }
        //    }
        AddScenario ("FindClassComment");
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ("ClassWithMethod");
        class1.IsClass = true;
        class1.Comments.Add (new CodeCommentStatement ("Class has a method to test static constructors"));
        nspace.Types.Add (class1);

        CodeMemberMethod cmm = new CodeMemberMethod ();
        cmm.Name = "TestStaticConstructor";
        AddScenario ("FindMethodComment");
        cmm.Comments.Add (new CodeCommentStatement (new CodeComment ("This method is used to test a static constructor")));
        cmm.Attributes = MemberAttributes.Public;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        AddScenario ("FindLineComment");
        cmm.Statements.Add (new CodeCommentStatement ("Testing a line comment"));
        CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a");
        cmm.Parameters.Add (param);
        // utilize constructor
        cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestClass", "t", new CodeObjectCreateExpression ("TestClass")));
        // set then get number
        cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i")
            , new CodeArgumentReferenceExpression ("a")));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i")));
        class1.Members.Add (cmm);


        // GENERATES (C#):
        //    public class TestClass {
        //        // This field is an integer counter
        //        private int number;
        //        static TestClass() {
        //        }
        //        // This property allows us to access the integer counter
        //        // We are able to both get and set the value of the counter
        //        public int i {
        //            get {
        //                return number;
        //            }
        //            set {
        //                number = value;
        //            }
        //        }
        //    }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "TestClass";
        class1.IsClass = true;
        nspace.Types.Add (class1);
        AddScenario ("FindFieldComment");
        CodeMemberField mfield = new CodeMemberField (new CodeTypeReference (typeof (int)), "number");
        mfield.Comments.Add (new CodeCommentStatement ("This field is an integer counter"));
        class1.Members.Add (mfield);
        AddScenario ("FindPropertyComment");
        CodeMemberProperty prop = new CodeMemberProperty ();
        prop.Name = "i";
        prop.Comments.Add (new CodeCommentStatement ("This property allows us to access the integer counter"));
        prop.Comments.Add (new CodeCommentStatement ("We are able to both get and set the value of the counter"));
        prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        prop.Type = new CodeTypeReference (typeof (int));
        prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number")));
        prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"),
            new CodePropertySetValueReferenceExpression ()));
        class1.Members.Add (prop);


        CodeTypeConstructor ctc = new CodeTypeConstructor ();
        class1.Members.Add (ctc);

        // ************* code a comment on an event *************
        if (Supports (provider, GeneratorSupport.DeclareEvents)) {

            // GENERATES (C#):
            //    public class Test : Form {
            //        private Button b = new Button();
            //        public Test() {
            //            this.Size = new Size(600, 600);
            //            b.Text = "Test";
            //            b.TabIndex = 0;
            //            b.Location = new Point(400, 525);
            //            this.MyEvent += new EventHandler(this.b_Click);
            //        }
            //        // This is a comment on an event
            //        public event System.EventHandler MyEvent;
            //        private void b_Click(object sender, System.EventArgs e) {
            //        }
            //    }
            class1 = new CodeTypeDeclaration ("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add (new CodeTypeReference ("Form"));
            nspace.Types.Add (class1);

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

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

            AddScenario ("FindEventComment");
            CodeMemberEvent evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.Comments.Add (new CodeCommentStatement ("This is a comment on an event"));
            class1.Members.Add (evt);

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

        if (Supports (provider, GeneratorSupport.DeclareDelegates)) {
            // GENERATES (C#):
            //
            // // This is a delegate comment
            // public delegate void Delegate();

            AddScenario ("FindDelegateComment");
            CodeTypeDelegate del = new CodeTypeDelegate ("Delegate");
            del.Comments.Add (new CodeCommentStatement ("This is a delegate comment"));
            nspace.Types.Add (del);
        }
    }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {

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

        // create a class that will be used to test the constructors of other classes
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Test";
        class1.IsClass = true;
        ns.Types.Add (class1);

        CodeMemberMethod cmm;

        // construct a method to test class with chained public constructors
        // GENERATES (C#):
        //        public static string TestingMethod1() {
        //                Test2 t = new Test2();
        //                return t.accessStringField;
        //            }
        if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) {
            AddScenario ("CheckTestingMethod01");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TestingMethod1";
            cmm.Attributes = MemberAttributes.Public;
            cmm.ReturnType = new CodeTypeReference (typeof (String));
            // utilize constructor
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("t"), "accessStringField")));
            class1.Members.Add (cmm);
        }

        // construct a method to test class with base public constructor
        // GENERATES (C#):
        //        public static string TestingMethod2() {
        //                Test3 t = new Test3();
        //                return t.accessStringField;
        //            }
        AddScenario ("CheckTestingMethod02");
        cmm = new CodeMemberMethod ();
        cmm.Name = "TestingMethod2";
        cmm.Attributes = MemberAttributes.Public;
        cmm.ReturnType = new CodeTypeReference (typeof (String));
        // utilize constructor
        cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test3", "t", new CodeObjectCreateExpression ("Test3")));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
            new CodeVariableReferenceExpression ("t"), "accessStringField")));

        class1.Members.Add (cmm);
        // construct a method to test class with internal constructor
        // GENERATES (C#):
        //        public static int TestInternalConstruct(int a) {
        //                ClassWInternalConstruct t = new ClassWInternalConstruct();
        //                t.i = a;
        //                return t.i;
        //            }

        CodeParameterDeclarationExpression param = null;

#if !WHIDBEY
        // Everett VB compiler doesn't like this construct
        if (!(provider is VBCodeProvider)) {
#endif
            AddScenario ("CheckTestInternalConstruct");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TestInternalConstruct";
            cmm.Attributes = MemberAttributes.Public;
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);
            // utilize constructor
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWInternalConstruct", "t", new CodeObjectCreateExpression ("ClassWInternalConstruct")));
            // set then get number
            cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i")
                , new CodeArgumentReferenceExpression ("a")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("t"), "i")));
            class1.Members.Add (cmm);
#if !WHIDBEY
        }
#endif



        // construct a method to test class with static constructor
        // GENERATES (C#):
        //        public static int TestStaticConstructor(int a) {
        //                Test4 t = new Test4();
        //                t.i = a;
        //                return t.i;
        //            }
        if (Supports (provider, GeneratorSupport.StaticConstructors)) {
            AddScenario ("CheckTestStaticConstructor");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TestStaticConstructor";
            cmm.Attributes = MemberAttributes.Public;
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);
            // utilize constructor
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4")));
            // set then get number
            cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i")
                , new CodeArgumentReferenceExpression ("a")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("t"), "i")));
            class1.Members.Add (cmm);
        }


        //  *** second class, tests chained, public constructors ***
        // GENERATES (C#):
        //        public class Test2 { 
        //            private string stringField;
        //            public Test2() : 
        //                    this("testingString", null, null) {
        //            }
        //            public Test2(String p1, String p2, String p3) {
        //                this.stringField = p1;
        //            }
        //            public string accessStringField {
        //                get {
        //                    return this.stringField;
        //                }
        //                set {
        //                    this.stringField = value;
        //                }
        //            }
        //        } 
        class1 = new CodeTypeDeclaration ();
        class1.Name = "Test2";
        class1.IsClass = true;
        ns.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;
        if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) {
            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 ("String", "p1"));
        cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p2"));
        cc.Parameters.Add (new CodeParameterDeclarationExpression ("String", "p3"));
        cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression ()
            , "stringField"), new CodeArgumentReferenceExpression ("p1")));
        class1.Members.Add (cc);


        // **** third class tests base constructors ****
        // GENERATES (C#):
        //    public class Test3 : Test2 {
        //            public Test3() : 
        //                    base("testingString", null, null) {
        //            }
        //        }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "Test3";
        class1.IsClass = true;
        class1.BaseTypes.Add (new CodeTypeReference ("Test2"));
        ns.Types.Add (class1);

        cctor = new CodeConstructor ();
        cctor.Attributes = MemberAttributes.Public;
        cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression ("testingString"));
        cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null));
        cctor.BaseConstructorArgs.Add (new CodePrimitiveExpression (null));
        class1.Members.Add (cctor);


        if (Supports (provider, GeneratorSupport.StaticConstructors)) {
            // *** fourth class tests static constructors ****
            // GENERATES (C#):
            //    public class Test4 {
            //            private int number;
            //            static Test4() {
            //            }
            //            public int i {
            //                get {
            //                    return number;
            //                }
            //                set {
            //                    number = value;
            //                }
            //            }
            //        }
            class1 = new CodeTypeDeclaration ();
            class1.Name = "Test4";
            class1.IsClass = true;
            ns.Types.Add (class1);

            class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number"));
            prop = new CodeMemberProperty ();
            prop.Name = "i";
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            prop.Type = new CodeTypeReference (typeof (int));
            prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number")));
            prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"),
                new CodePropertySetValueReferenceExpression ()));
            class1.Members.Add (prop);


            CodeTypeConstructor ctc = new CodeTypeConstructor ();
            class1.Members.Add (ctc);
        }

        // *******  class tests internal constructors **********
        // GENERATES (C#):
        //    public class ClassWInternalConstruct {
        //            private int number;
        //            /*FamANDAssem*/ internal ClassWInternalConstruct() {
        //            }
        //            public int i {
        //                get {
        //                    return number;
        //                }
        //                set {
        //                    number = value;
        //                }
        //            }
        //        }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "ClassWInternalConstruct";
        class1.IsClass = true;
        ns.Types.Add (class1);

        class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number"));
        prop = new CodeMemberProperty ();
        prop.Name = "i";
        prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        prop.Type = new CodeTypeReference (typeof (int));
        prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number")));
        prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"),
            new CodePropertySetValueReferenceExpression ()));
        class1.Members.Add (prop);

        if (!(provider is JScriptCodeProvider)) {
            cctor = new CodeConstructor ();
            cctor.Attributes = MemberAttributes.FamilyOrAssembly;
            class1.Members.Add (cctor);
        }

        // ******** class tests private constructors **********
        // GENERATES (C#):
        //    public class ClassWPrivateConstruct {
        //            static int number;
        //            private ClassWPrivateConstruct() {
        //            }
        //        }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "ClassWPrivateConstruct";
        class1.IsClass = true;
        ns.Types.Add (class1);

        cctor = new CodeConstructor ();
        cctor.Attributes = MemberAttributes.Private;
        class1.Members.Add (cctor);


        // ******* class tests protected constructors **************
        // GENERATES (C#):
        //    public class ClassWProtectedConstruct {
        //            protected ClassWProtectedConstruct() {
        //            }
        //        }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "ClassWProtectedConstruct";
        class1.IsClass = true;
        ns.Types.Add (class1);

        cctor = new CodeConstructor ();
        cctor.Attributes = MemberAttributes.Family;
        class1.Members.Add (cctor);

        // class that inherits protected constructor
        // GENERATES (C#):
        //    public class InheritsProtectedConstruct : ClassWProtectedConstruct {
        //    }
        class1 = new CodeTypeDeclaration ();
        class1.Name = "InheritsProtectedConstruct";
        class1.IsClass = true;
        class1.BaseTypes.Add (new CodeTypeReference ("ClassWProtectedConstruct"));
        ns.Types.Add (class1);


    }
Example #18
0
        public static IEnumerable <CodeTypeDeclaration> CreateSafeHandle(string name, ModuleGenerator generator)
        {
            CodeTypeDeclaration safeHandle = new CodeTypeDeclaration(name + "Handle");

#if !NETSTANDARD1_5
            safeHandle.CustomAttributes.Add(SecurityPermissionDeclaration(SecurityAction.InheritanceDemand, true));
            safeHandle.CustomAttributes.Add(SecurityPermissionDeclaration(SecurityAction.Demand, true));
#endif
            safeHandle.IsPartial  = true;
            safeHandle.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            safeHandle.BaseTypes.Add(typeof(SafeHandleZeroOrMinusOneIsInvalid));

            // Add a field which stores the stack used to create this object. Useful for troubleshooting issues
            // that may occur when a plist object is being disposed of.
            CodeMemberField stackTraceField = new CodeMemberField();
            stackTraceField.Name       = "creationStackTrace";
            stackTraceField.Type       = new CodeTypeReference(typeof(string));
            stackTraceField.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            safeHandle.Members.Add(stackTraceField);

            var setCreationStackTrace =
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        "creationStackTrace"),
                    new CodePropertyReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(Environment)),
                        "StackTrace"));

            CodeConstructor constructor = new CodeConstructor();
            constructor.Attributes = MemberAttributes.Family;
            constructor.BaseConstructorArgs.Add(new CodePrimitiveExpression(true));
            constructor.Statements.Add(setCreationStackTrace);
            constructor.Comments.Add(new CodeCommentStatement($@"<summary>
Initializes a new instance of the <see cref=""{safeHandle.Name}""/> class.
</summary>"));
            safeHandle.Members.Add(constructor);

            CodeConstructor ownsHandleConstructor = new CodeConstructor();
            ownsHandleConstructor.Attributes = MemberAttributes.Family;
            ownsHandleConstructor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(bool)), "ownsHandle"));
            ownsHandleConstructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("ownsHandle"));
            ownsHandleConstructor.Statements.Add(setCreationStackTrace);
            ownsHandleConstructor.Comments.Add(new CodeCommentStatement($@"<summary>
Initializes a new instance of the <see cref=""{safeHandle.Name}""/> class, specifying whether the handle is to be reliably released.
</summary>
<param name=""ownsHandle"">
<see langword=""true""/> to reliably release the handle during the finalization phase; <see langword=""false""/> to prevent reliable release (not recommended).
</param>"));
            safeHandle.Members.Add(ownsHandleConstructor);

            CodeMemberMethod releaseHandle = new CodeMemberMethod();
            releaseHandle.Name       = "ReleaseHandle";
            releaseHandle.Attributes = MemberAttributes.Override | MemberAttributes.Family;
            releaseHandle.ReturnType = new CodeTypeReference(typeof(bool));
            releaseHandle.CustomAttributes.Add(ReliabilityContractDeclaration(Consistency.WillNotCorruptState, Cer.MayFail));
            releaseHandle.Comments.Add(new CodeCommentStatement("<inheritdoc/>"));

            releaseHandle.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(true)));
            safeHandle.Members.Add(releaseHandle);

            // Add an "Api" property which provides a reference to the instance of the API which was used to
            // create this handle - and which will also be used to destroy this handle.
            CodeMemberField apiField = new CodeMemberField();
            apiField.Name       = "api";
            apiField.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            apiField.Type       = new CodeTypeReference("ILibiMobileDevice");
            safeHandle.Members.Add(apiField);

            CodeMemberProperty apiProperty = new CodeMemberProperty();
            apiProperty.Name       = "Api";
            apiProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            apiProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        apiField.Name)));
            apiProperty.SetStatements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(),
                        apiField.Name),
                    new CodeVariableReferenceExpression("value")));
            apiProperty.Type = new CodeTypeReference("ILibiMobileDevice");
            apiProperty.Comments.Add(new CodeCommentStatement(@"<summary>
Gets or sets the API to use
</summary>"));
            safeHandle.Members.Add(apiProperty);

            // Add a "DangeousCreate" method which creates a new safe handle from an IntPtr
            CodeMemberMethod dangerousCreate = new CodeMemberMethod();
            dangerousCreate.Name       = "DangerousCreate";
            dangerousCreate.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            dangerousCreate.ReturnType = new CodeTypeReference(safeHandle.Name);
            dangerousCreate.Comments.Add(new CodeCommentStatement($@"<summary>
Creates a new <see cref=""{safeHandle.Name}""/> from a <see cref=""IntPtr""/>.
</summary>
<param name=""unsafeHandle"">
The underlying <see cref=""IntPtr""/>
</param>
<param name=""ownsHandle"">
<see langword=""true""/> to reliably release the handle during the finalization phase; <see langword=""false""/> to prevent reliable release (not recommended).
</param>
<returns>
</returns>"));

            dangerousCreate.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(IntPtr)),
                    "unsafeHandle"));

            dangerousCreate.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(bool)),
                    "ownsHandle"));

            dangerousCreate.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(safeHandle.Name),
                    "safeHandle"));

            dangerousCreate.Statements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("safeHandle"),
                    new CodeObjectCreateExpression(
                        new CodeTypeReference(safeHandle.Name),
                        new CodeArgumentReferenceExpression("ownsHandle"))));

            dangerousCreate.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeVariableReferenceExpression("safeHandle"),
                        "SetHandle"),
                    new CodeArgumentReferenceExpression("unsafeHandle")));

            dangerousCreate.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeVariableReferenceExpression("safeHandle")));

            safeHandle.Members.Add(dangerousCreate);

            // Add a "DangeousCreate" method which creates a new safe handle from an IntPtr
            CodeMemberMethod simpleDangerousCreate = new CodeMemberMethod();
            simpleDangerousCreate.Name       = "DangerousCreate";
            simpleDangerousCreate.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            simpleDangerousCreate.ReturnType = new CodeTypeReference(safeHandle.Name);
            simpleDangerousCreate.Comments.Add(new CodeCommentStatement($@"<summary>
Creates a new <see cref=""{safeHandle.Name}""/> from a <see cref=""IntPtr""/>.
</summary>
<param name=""unsafeHandle"">
The underlying <see cref=""IntPtr""/>
</param>
<returns>
</returns>"));

            simpleDangerousCreate.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(IntPtr)),
                    "unsafeHandle"));

            simpleDangerousCreate.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeTypeReferenceExpression(safeHandle.Name),
                            "DangerousCreate"),
                        new CodeArgumentReferenceExpression("unsafeHandle"),
                        new CodePrimitiveExpression(true))));

            safeHandle.Members.Add(simpleDangerousCreate);

            // Add a "Zero" property which returns an invalid handle
            CodeMemberProperty zeroProperty = new CodeMemberProperty();
            zeroProperty.Name       = "Zero";
            zeroProperty.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            zeroProperty.Type       = new CodeTypeReference(safeHandle.Name);
            zeroProperty.Comments.Add(new CodeCommentStatement(@"<summary>
Gets a value which represents a pointer or handle that has been initialized to zero.
</summary>"));

            zeroProperty.HasGet = true;

            zeroProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeTypeReferenceExpression(safeHandle.Name),
                            dangerousCreate.Name),
                        new CodePropertyReferenceExpression(
                            new CodeTypeReferenceExpression(typeof(IntPtr)),
                            nameof(IntPtr.Zero)))));

            safeHandle.Members.Add(zeroProperty);

            // Create the ToString method which returns:
            // {handle} ({type})
            CodeMemberMethod toStringMethod = new CodeMemberMethod();
            toStringMethod.Name       = "ToString";
            toStringMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            toStringMethod.ReturnType = new CodeTypeReference(typeof(string));
            toStringMethod.Comments.Add(new CodeCommentStatement("<inheritdoc/>"));
            toStringMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(string)),
                        "Format",
                        new CodePrimitiveExpression("{0} ({1})"),
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "handle"),
                        new CodePrimitiveExpression(safeHandle.Name))));
            safeHandle.Members.Add(toStringMethod);

            // Create the Equals method:
            //
            // if (!(obj is AfcClientHandle))
            // {
            //    return false;
            // }
            //
            // return ((AfcClientHandle)obj).handle.Equals(this.handle);
            CodeMemberMethod equalsMethod = new CodeMemberMethod();
            equalsMethod.Name       = "Equals";
            equalsMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            equalsMethod.ReturnType = new CodeTypeReference(typeof(bool));
            equalsMethod.Comments.Add(new CodeCommentStatement("<inheritdoc/>"));
            equalsMethod.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(object)),
                    "obj"));

            equalsMethod.Statements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeBinaryOperatorExpression(
                            new CodeArgumentReferenceExpression("obj"),
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null)),
                        CodeBinaryOperatorType.BooleanAnd,
                        new CodeBinaryOperatorExpression(
                            new CodeMethodInvokeExpression(
                                new CodeArgumentReferenceExpression("obj"),
                                "GetType"),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodeTypeOfExpression(safeHandle.Name))),
                    new CodeStatement[]
            {
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(
                            new CodeCastExpression(
                                new CodeTypeReference(safeHandle.Name),
                                new CodeArgumentReferenceExpression("obj")),
                            "handle"),
                        "Equals",
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            "handle")))
            },
                    new CodeStatement[]
            {
                new CodeMethodReturnStatement(
                    new CodePrimitiveExpression(false))
            }));

            safeHandle.Members.Add(equalsMethod);

            // Override the operators
            safeHandle.Members.Add(new CodeSnippetTypeMember($@"/// <summary>
/// Determines whether two specified instances of <see cref=""{safeHandle.Name}""/> are equal.
/// </summary>
/// <param name=""value1"">
/// The first pointer or handle to compare.
/// </param>
/// <param name=""value2"">
/// The second pointer or handle to compare.
/// </param>
/// <returns>
/// <see langword=""true""/> if <paramref name=""value1""/> equals <paramref name=""value2""/>; otherwise, <see langword=""false""/>.
/// </returns>
public static bool operator == ({safeHandle.Name} value1, {safeHandle.Name} value2) 
{{
    if (object.Equals(value1, null) && object.Equals(value2, null))
    {{
        return true;
    }}

    if (object.Equals(value1, null) || object.Equals(value2, null))
    {{
        return false;
    }}

    return value1.handle == value2.handle;
}}"));

            safeHandle.Members.Add(new CodeSnippetTypeMember($@"/// <summary>
/// Determines whether two specified instances of <see cref=""{safeHandle.Name}""/> are not equal.
/// </summary>
/// <param name=""value1"">
/// The first pointer or handle to compare.
/// </param>
/// <param name=""value2"">
/// The second pointer or handle to compare.
/// </param>
/// <returns>
/// <see langword=""true""/> if <paramref name=""value1""/> does not equal <paramref name=""value2""/>; otherwise, <see langword=""false""/>.
/// </returns>
public static bool operator != ({safeHandle.Name} value1, {safeHandle.Name} value2) 
{{
    if (object.Equals(value1, null) && object.Equals(value2, null))
    {{
        return false;
    }}

    if (object.Equals(value1, null) || object.Equals(value2, null))
    {{
        return true;
    }}

    return value1.handle != value2.handle;
}}"));

            // Create the GetHashCode method
            // return this.handle.GetHashCode();
            CodeMemberMethod getHashCodeMethod = new CodeMemberMethod();
            getHashCodeMethod.Name       = "GetHashCode";
            getHashCodeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            getHashCodeMethod.ReturnType = new CodeTypeReference(typeof(int));
            getHashCodeMethod.Comments.Add(new CodeCommentStatement("<inheritdoc/>"));
            getHashCodeMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            "handle"),
                        "GetHashCode")));
            safeHandle.Members.Add(getHashCodeMethod);

            yield return(safeHandle);

            // Create the marshaler type
            CodeTypeDeclaration safeHandleMarshaler = new CodeTypeDeclaration();
            safeHandleMarshaler.Name       = name + "HandleDelegateMarshaler";
            safeHandleMarshaler.IsPartial  = true;
            safeHandleMarshaler.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            safeHandleMarshaler.BaseTypes.Add(typeof(ICustomMarshaler));

            // Create the GetInstance method
            CodeMemberMethod getInstanceMethod = new CodeMemberMethod();
            getInstanceMethod.Name       = "GetInstance";
            getInstanceMethod.ReturnType = new CodeTypeReference(typeof(ICustomMarshaler));
            getInstanceMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
            getInstanceMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "cookie"));
            getInstanceMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeObjectCreateExpression(safeHandleMarshaler.Name)));
            safeHandleMarshaler.Members.Add(getInstanceMethod);

            // Create the CleanUpManagedData method
            CodeMemberMethod cleanUpManagedData = new CodeMemberMethod();
            cleanUpManagedData.Name       = "CleanUpManagedData";
            cleanUpManagedData.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cleanUpManagedData.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "managedObject"));
            safeHandleMarshaler.Members.Add(cleanUpManagedData);

            // Create the CleanUpNativeData method
            CodeMemberMethod cleanUpNativeDataMethod = new CodeMemberMethod();
            cleanUpNativeDataMethod.Name       = "CleanUpNativeData";
            cleanUpNativeDataMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cleanUpNativeDataMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IntPtr), "nativeData"));
            safeHandleMarshaler.Members.Add(cleanUpNativeDataMethod);

            // Create the GetNativeDataSize method
            CodeMemberMethod getNativeDataSizeMethod = new CodeMemberMethod();
            getNativeDataSizeMethod.Name       = "GetNativeDataSize";
            getNativeDataSizeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            getNativeDataSizeMethod.ReturnType = new CodeTypeReference(typeof(int));
            getNativeDataSizeMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodePrimitiveExpression(-1)));
            safeHandleMarshaler.Members.Add(getNativeDataSizeMethod);

            // Create the MarshalManagedToNative method
            CodeMemberMethod marshalManagedToNativeMethod = new CodeMemberMethod();
            marshalManagedToNativeMethod.Name       = "MarshalManagedToNative";
            marshalManagedToNativeMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            marshalManagedToNativeMethod.ReturnType = new CodeTypeReference(typeof(IntPtr));
            marshalManagedToNativeMethod.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(object),
                    "managedObject"));
            marshalManagedToNativeMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodePropertyReferenceExpression(
                        new CodeTypeReferenceExpression(typeof(IntPtr)),
                        nameof(IntPtr.Zero))));
            safeHandleMarshaler.Members.Add(marshalManagedToNativeMethod);

            // Create the MarshalNativeToManaged method
            CodeMemberMethod marshalNativeToManagedMethod = new CodeMemberMethod();
            marshalNativeToManagedMethod.Name       = "MarshalNativeToManaged";
            marshalNativeToManagedMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            marshalNativeToManagedMethod.ReturnType = new CodeTypeReference(typeof(object));
            marshalNativeToManagedMethod.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    typeof(IntPtr),
                    "nativeData"));
            marshalNativeToManagedMethod.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(
                            new CodeTypeReferenceExpression(safeHandle.Name),
                            "DangerousCreate"),
                        new CodeArgumentReferenceExpression("nativeData"),

                        // ownsHandle: false
                        new CodePrimitiveExpression(false))));
            safeHandleMarshaler.Members.Add(marshalNativeToManagedMethod);

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

        // GENERATES (C#):
        //  [assembly: System.CLSCompliantAttribute(false)]
        //  
        //  namespace MyNamespace {
        //      using System;
        //      using System.Drawing;
        //      using System.Windows.Forms;
        //      using System.ComponentModel;
        //      
        //      
        //      public class Test : Form {
        //          
        //          private Button b = new Button();
        //          
        //          public Test() {
        //              this.Size = new Size(600, 600);
        //              b.Text = "Test";
        //              b.TabIndex = 0;
        //              b.Location = new Point(400, 525);
        //              this.MyEvent += new EventHandler(this.b_Click);
        //              this.MyEvent -= new EventHandler(this.b_Click);
        //          }
        //          
        //          [System.CLSCompliantAttribute(false)]
        //          public event System.EventHandler MyEvent;
        //          
        //          private void b_Click(object sender, System.EventArgs e) {
        //          }
        //      }
        //  }
        //  namespace SecondNamespace {
        //      using System;
        //      using System.Drawing;
        //      using System.Windows.Forms;
        //      using System.ComponentModel;
        //      
        //      
        //      public class Test : Form {
        //          
        //          private Button b = new Button();
        //          
        //          public Test() {
        //              this.Size = new Size(600, 600);
        //              b.Text = "Test";
        //              b.TabIndex = 0;
        //              b.Location = new Point(400, 525);
        //              this.MyEvent += new EventHandler(this.b_Click);
        //          }
        //          
        //          private event System.EventHandler MyEvent;
        //          
        //          private void b_Click(object sender, System.EventArgs e) {
        //          }
        //      }
        //  }
        //  namespace ThirdNamespace {
        //      using System;
        //      using System.Drawing;
        //      using System.Windows.Forms;
        //      using System.ComponentModel;
        //      
        //      
        //      public class Test : Form {
        //          
        //          private Button b = new Button();
        //          
        //          public Test() {
        //              this.Size = new Size(600, 600);
        //              b.Text = "Test";
        //              b.TabIndex = 0;
        //              b.Location = new Point(400, 525);
        //              this.MyEvent += new EventHandler(this.b_Click);
        //          }
        //          
        //          [System.CLSCompliantAttribute(false)]
        //          protected event System.EventHandler MyEvent;
        //          
        //          private void b_Click(object sender, System.EventArgs e) {
        //          }
        //      }
        //  }
        //  namespace FourthNamespace {
        //      using System;
        //      using System.Drawing;
        //      using System.Windows.Forms;
        //      using System.ComponentModel;
        //      
        //      
        //      public class Test : Form {
        //          
        //          private Button b = new Button();
        //          
        //          public Test() {
        //              this.Size = new Size(600, 600);
        //              b.Text = "Test";
        //              b.TabIndex = 0;
        //              b.Location = new Point(400, 525);
        //              this.MyEvent += new EventHandler(this.b_Click);
        //          }
        //          
        //          /*FamANDAssem*/ internal event System.EventHandler MyEvent;
        //          
        //          private void b_Click(object sender, System.EventArgs e) {
        //          }
        //      }
        //  }

        if (Supports (provider, GeneratorSupport.DeclareEvents)) {
            // *********************************
            // public
            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.Drawing.dll");
            cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");

            // Assembly Attributes
            if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
                CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
                attrs.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new
                    CodeAttributeArgument (new CodePrimitiveExpression (false))));
            }

            CodeTypeDeclaration 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 CodePropertyReferenceExpression (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")));
            ctor.Statements.Add (new CodeRemoveEventStatement (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);

            // *********************************
            // private
            ns = new CodeNamespace ();
            ns.Name = "SecondNamespace";
            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);

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

            ctor = new CodeConstructor ();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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))));

            CodeAttachEventStatement addevt = new CodeAttachEventStatement (new CodeThisReferenceExpression (),
                    "MyEvent", new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler")
                , new CodeThisReferenceExpression (), "b_Click"));

            ctor.Statements.Add (addevt);

            // remove event statement 
            CodeRemoveEventStatement rem = new CodeRemoveEventStatement (new CodeThisReferenceExpression (), "MyEvent",
                        new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"),
                            new CodeThisReferenceExpression (), "b_Click"));
            ctor.Statements.Add (rem);


            class1.Members.Add (ctor);

            evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Private;
            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);

            // *********************************
            // protected
            ns = new CodeNamespace ();
            ns.Name = "ThirdNamespace";
            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);

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

            ctor = new CodeConstructor ();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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))));

            addevt = new CodeAttachEventStatement ();
            addevt.Event = new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent");
            addevt.Listener = new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"),
                    new CodeThisReferenceExpression (), "b_Click");
            ctor.Statements.Add (addevt);

            // remove event
            rem = new CodeRemoveEventStatement ();
            rem.Event = new CodeEventReferenceExpression (new CodeThisReferenceExpression (), "MyEvent");
            rem.Listener = new CodeDelegateCreateExpression (new CodeTypeReference ("EventHandler"),
                    new CodeThisReferenceExpression (), "b_Click");
            ctor.Statements.Add (rem);

            class1.Members.Add (ctor);

            evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Family;
            evt.CustomAttributes.Add (new CodeAttributeDeclaration ("System.CLSCompliantAttribute", new CodeAttributeArgument (new CodePrimitiveExpression (false))));
            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);

            // *********************************
            // internal
            ns = new CodeNamespace ();
            ns.Name = "FourthNamespace";
            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);

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

            ctor = new CodeConstructor ();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (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);

            evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.FamilyAndAssembly;
            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);
        }
    }
Example #20
0
        private static Type BuildTypeCodeDom(Type baseInterface, string className, string fieldsPrefix, params Type[] types)
        {
            var           compileUnit     = new CodeCompileUnit();
            CodeNamespace globalNamespace = new CodeNamespace();

            globalNamespace.Imports.Add(new CodeNamespaceImport("System"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            globalNamespace.Imports.Add(new CodeNamespaceImport("System.Text"));

            var classNamespace = new CodeNamespace("STS.General.Data");

            var generatedClass = new CodeTypeDeclaration(className);

            generatedClass.IsClass    = true;
            generatedClass.Attributes = MemberAttributes.Public;

            for (int i = 0; i < types.Length; i++)
            {
                generatedClass.TypeParameters.Add(new CodeTypeParameter("T" + fieldsPrefix + i));
            }

            if (baseInterface != null)
            {
                generatedClass.BaseTypes.Add(baseInterface);
            }

            var serializableAttribute = new CodeTypeReference(typeof(System.SerializableAttribute));

            generatedClass.CustomAttributes.Add(new CodeAttributeDeclaration(serializableAttribute));

            classNamespace.Types.Add(generatedClass);

            compileUnit.Namespaces.Add(globalNamespace);
            compileUnit.Namespaces.Add(classNamespace);

            CodeMemberField[] fields = new CodeMemberField[types.Length];

            for (int i = 0; i < fields.Length; i++)
            {
                fields[i]            = new CodeMemberField("T" + fieldsPrefix + i, fieldsPrefix + i);
                fields[i].Attributes = MemberAttributes.Public;
                generatedClass.Members.Add(fields[i]);
            }

            CodeConstructor defaultConstructor = new CodeConstructor();

            defaultConstructor.Attributes = MemberAttributes.Public;

            generatedClass.Members.Add(defaultConstructor);

            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;

            for (int i = 0; i < types.Length; i++)
            {
                CodeTypeReference type = new CodeTypeReference("T" + fieldsPrefix + i);
                constructor.Parameters.Add(new CodeParameterDeclarationExpression(type, fieldsPrefix.ToLower() + i));
            }

            for (int i = 0; i < types.Length; i++)
            {
                CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldsPrefix + i);
                constructor.Statements.Add(new CodeAssignStatement(left, new CodeArgumentReferenceExpression(fieldsPrefix.ToLower() + i)));
            }

            generatedClass.Members.Add(constructor);

            string stsdbAssemblyName = Assembly.GetExecutingAssembly().Location;

            string[] assemblies = { "System.dll", "mscorlib.dll", stsdbAssemblyName };

            CompilerParameters parameters = new CompilerParameters(assemblies);

            CodeDomProvider runTimeProvider = new Microsoft.CSharp.CSharpCodeProvider();

            parameters = new CompilerParameters(assemblies);

            parameters.GenerateExecutable      = false;
            parameters.GenerateInMemory        = true;
            parameters.IncludeDebugInformation = true;
            parameters.CompilerOptions         = "/optimize";

            CompilerResults compilerResults = runTimeProvider.CompileAssemblyFromDom(parameters, compileUnit);
            var             generatedType   = compilerResults.CompiledAssembly.GetTypes()[0];

            return(generatedType.MakeGenericType(types));
        }
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                  [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")]
                  [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")]
                  [assembly: System.CLSCompliantAttribute(false)]

                  namespace MyNamespace
                  {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;
                  
                      [System.Serializable()]
                      [System.Obsolete(""Don\'t use this Class"")]
                      public class MyClass
                      {
                          [System.Xml.Serialization.XmlElementAttribute()]
                          private string myField = ""hi!"";
              
                          [System.Obsolete(""Don\'t use this Constructor"")]
                          private MyClass()
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Property"")]
                          private string MyProperty
                          {
                              get
                              {
                                  return this.myField;
                              }
                          }
              
                          [System.Obsolete(""Don\'t use this Method"")]
                          [System.ComponentModel.Editor(""This"", ""That"")]
                          private void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah, [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] int[] arrayit)
                          {
                          }
              
                          [System.Obsolete(""Don\'t use this Function"")]
                          [return: System.Xml.Serialization.XmlIgnoreAttribute()]
                          [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")]
                          private string MyFunction()
                          {
                              return ""Return"";
                          }
              
                          [global::System.ObsoleteAttribute(""Don\'t use this Function"")]
                          [return: global::System.Xml.Serialization.XmlIgnoreAttribute()]
                          private void GlobalKeywordFunction()
                          {
                          }
              
                          [System.Serializable()]
                          public class NestedClass
                          {
                          }
                      }
              
                      public class Test : Form
                      {
                          private Button b = new Button();
              
                          public Test()
                          {
                              this.Size = new Size(600, 600);
                              b.Text = ""Test"";
                              b.TabIndex = 0;
                              b.Location = new Point(400, 525);
                              this.MyEvent += new EventHandler(this.b_Click);
                          }
              
                          [System.CLSCompliantAttribute(false)]
                          public event System.EventHandler MyEvent;
              
                          private void b_Click(object sender, System.EventArgs e)
                          {
                          }
                      }
                  }");
        }
Example #22
0
        private void AddConstructor(CodeTypeDeclaration declaration)
        {
            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            constructor.Parameters.Add(new CodeParameterDeclarationExpression(
                                           typeof(XElement),
                                           "element"
                                           ));



            foreach (var keyField in _dataTypeDescriptor.KeyFields)
            {
                string propertyFieldName     = MakePropertyFieldName(keyField.Name);
                string attributeVariableName = "attr" + keyField.Name;

                // CODEGEN:
                // XAttribute attr{fieldName} = element.Attribute(_{fieldName}XName);

                constructor.Statements.Add(
                    new CodeVariableDeclarationStatement(
                        typeof(XAttribute), attributeVariableName,
                        new CodeMethodInvokeExpression(
                            new CodeVariableReferenceExpression("element"),
                            "Attribute",
                            new CodeFieldReferenceExpression(null, MakeXNameFieldName(keyField.Name))
                            )));


                // CODEGEN:
                // if(attr{fieldName} == null) {
                //   throw new InvalidOperationException("Missing '{fieldName}' attribute in a data store file.");
                // }

                constructor.Statements.Add(new CodeConditionStatement(
                                               new CodeBinaryOperatorExpression(
                                                   new CodeVariableReferenceExpression(attributeVariableName),
                                                   CodeBinaryOperatorType.IdentityEquality,
                                                   new CodePrimitiveExpression(null)
                                                   ),
                                               new CodeStatement[] {
                    new CodeThrowExceptionStatement(
                        new CodeObjectCreateExpression(
                            typeof(InvalidOperationException),
                            new CodeExpression[] {
                        new CodePrimitiveExpression(
                            string.Format("Missing '{0}' attribute in a data store file.", keyField.Name)
                            )
                    }
                            )
                        )
                }
                                               ));

                // CODEGEN:
                // _propertyId = (Guid) attrId;

                constructor.Statements.Add(new CodeAssignStatement(
                                               new CodeVariableReferenceExpression(propertyFieldName),
                                               new CodeCastExpression(
                                                   keyField.InstanceType,
                                                   new CodeVariableReferenceExpression(attributeVariableName)
                                                   )
                                               ));
            }

            declaration.Members.Add(constructor);
        }
Example #23
0
    private void DefineWrapperClassFieldsAndMethods(Smoke.Class* smokeClass, CodeTypeDeclaration type)
    {
        // define the dummy constructor
        if (smokeClass->size > 0)
        {
            CodeConstructor dummyCtor = new CodeConstructor();
            dummyCtor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Type)), "dummy"));
            if (data.Smoke->inheritanceList[smokeClass->parents] > 0)
            {
                dummyCtor.BaseConstructorArgs.Add(new CodeSnippetExpression("(System.Type) null"));
            }
            dummyCtor.Attributes = MemberAttributes.Family;
            if (SupportingMethodsHooks != null)
            {
                SupportingMethodsHooks(data.Smoke, (Smoke.Method*) 0, dummyCtor, type);
            }
            type.Members.Add(dummyCtor);
        }

        CodeMemberField staticInterceptor = new CodeMemberField("SmokeInvocation", "staticInterceptor");
        staticInterceptor.Attributes = MemberAttributes.Static;
        CodeObjectCreateExpression initExpression = new CodeObjectCreateExpression("SmokeInvocation");
        initExpression.Parameters.Add(new CodeTypeOfExpression(type.Name));
        initExpression.Parameters.Add(new CodePrimitiveExpression(null));
        staticInterceptor.InitExpression = initExpression;
        type.Members.Add(staticInterceptor);

        if (smokeClass->size == 0)
            return;

        // we only need this for real classes
        CodeMemberMethod createProxy = new CodeMemberMethod();
        createProxy.Name = "CreateProxy";
        createProxy.Attributes = MemberAttributes.Public;
        if (data.Smoke->inheritanceList[smokeClass->parents] != 0)
        {
            createProxy.Attributes |= MemberAttributes.Override;
        }
        createProxy.Statements.Add(new CodeAssignStatement(
                                       new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "interceptor"),
                                       // left hand side
                                       new CodeObjectCreateExpression("SmokeInvocation", new CodeTypeOfExpression(type.Name),
                                                                      new CodeThisReferenceExpression()) // right hand side
                                       ));
        type.Members.Add(createProxy);

        if (data.Smoke->inheritanceList[smokeClass->parents] != 0)
            return;
        // The following fields are only necessary for classes without superclasses.

        CodeMemberField interceptor = new CodeMemberField("SmokeInvocation", "interceptor");
        interceptor.Attributes = MemberAttributes.Family;
        type.Members.Add(interceptor);
        CodeMemberField smokeObject = new CodeMemberField(typeof(IntPtr), "smokeObject");
        type.Members.Add(smokeObject);
        type.BaseTypes.Add(new CodeTypeReference("ISmokeObject"));
        CodeMemberProperty propertySmokeObject = new CodeMemberProperty();
        propertySmokeObject.Name = "SmokeObject";
        propertySmokeObject.Type = new CodeTypeReference(typeof(IntPtr));
        propertySmokeObject.Attributes = MemberAttributes.Public;
        CodeFieldReferenceExpression smokeObjectReference = new CodeFieldReferenceExpression(
            new CodeThisReferenceExpression(), smokeObject.Name);
        propertySmokeObject.GetStatements.Add(new CodeMethodReturnStatement(smokeObjectReference));
        propertySmokeObject.SetStatements.Add(new CodeAssignStatement(smokeObjectReference,
                                                                      new CodePropertySetValueReferenceExpression()));
        type.Members.Add(propertySmokeObject);
    }
        void GenerateProxyClass(ContractDescription cd, CodeNamespace cns)
        {
            string name = cd.Name + "Client";

            if (name [0] == 'I')
            {
                name = name.Substring(1);
            }
            name = identifiers.AddUnique(name, null);
            CodeTypeDeclaration type = GetTypeDeclaration(cns, name);

            if (type != null)
            {
                return;                 // already imported
            }
            CodeTypeReference clientBase = new CodeTypeReference(typeof(ClientBase <>));

            clientBase.TypeArguments.Add(new CodeTypeReference(cd.Name));
            type = new CodeTypeDeclaration(name);
            cns.Types.Add(type);
            type.TypeAttributes = TypeAttributes.Public;
            type.BaseTypes.Add(clientBase);
            type.BaseTypes.Add(new CodeTypeReference(cd.Name));

            // .ctor()
            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public;
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName, string remoteAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "remoteAddress"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("remoteAddress"));
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName, EndpointAddress remoteAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(EndpointAddress)), "remoteAddress"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("remoteAddress"));
            type.Members.Add(ctor);

            // .ctor(Binding,EndpointAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(Binding)), "binding"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(EndpointAddress)), "endpoint"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("binding"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpoint"));
            type.Members.Add(ctor);

            // service contract methods
            AddImplementationClientMethods(type, cd);

            if (GenerateEventBasedAsync)
            {
                foreach (var od in cd.Operations)
                {
                    GenerateEventBasedAsyncSupport(type, od, cns);
                }
            }
        }
Example #25
0
        internal CodeConstructor Constructor(IEnumerable<CodeParameterDeclarationExpression> parms, Action body)
        {
            var cons = new CodeConstructor
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };
            cons.Parameters.AddRange(parms.ToArray());
            CurrentType.Members.Add(cons);

            GenerateMethodBody(cons, body);
            return cons;
        }
        void GenerateEventBasedAsyncSupport(CodeTypeDeclaration type, OperationDescription od, CodeNamespace cns)
        {
            var  method      = FindByName(type, od.Name) ?? FindByName(type, "Begin" + od.Name);
            var  endMethod   = method.Name == od.Name ? null : FindByName(type, "End" + od.Name);
            bool methodAsync = method.Name.StartsWith("Begin", StringComparison.Ordinal);
            var  resultType  = endMethod != null ? endMethod.ReturnType : method.ReturnType;

            var thisExpr        = new CodeThisReferenceExpression();
            var baseExpr        = new CodeBaseReferenceExpression();
            var nullExpr        = new CodePrimitiveExpression(null);
            var asyncResultType = new CodeTypeReference(typeof(IAsyncResult));

            // OnBeginXxx() implementation
            var cm = new CodeMemberMethod()
            {
                Name       = "OnBegin" + od.Name,
                Attributes = MemberAttributes.Private | MemberAttributes.Final,
                ReturnType = asyncResultType
            };

            type.Members.Add(cm);

            AddMethodParam(cm, typeof(object []), "args");
            AddMethodParam(cm, typeof(AsyncCallback), "asyncCallback");
            AddMethodParam(cm, typeof(object), "userState");

            var call = new CodeMethodInvokeExpression(
                thisExpr,
                "Begin" + od.Name);

            for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++)
            {
                var p = method.Parameters [idx];
                cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name, new CodeCastExpression(p.Type, new CodeArrayIndexerExpression(new CodeArgumentReferenceExpression("args"), new CodePrimitiveExpression(idx)))));
                call.Parameters.Add(new CodeVariableReferenceExpression(p.Name));
            }
            call.Parameters.Add(new CodeArgumentReferenceExpression("asyncCallback"));
            call.Parameters.Add(new CodeArgumentReferenceExpression("userState"));
            cm.Statements.Add(new CodeMethodReturnStatement(call));

            // OnEndXxx() implementation
            cm = new CodeMemberMethod()
            {
                Name       = "OnEnd" + od.Name,
                Attributes = MemberAttributes.Private | MemberAttributes.Final,
                ReturnType = new CodeTypeReference(typeof(object []))
            };
            type.Members.Add(cm);

            AddMethodParam(cm, typeof(IAsyncResult), "result");

            var outArgRefs = new List <CodeVariableReferenceExpression> ();

            for (int idx = 0; idx < method.Parameters.Count; idx++)
            {
                var p = method.Parameters [idx];
                if (p.Direction != FieldDirection.In)
                {
                    cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name));
                    outArgRefs.Add(new CodeVariableReferenceExpression(p.Name));                       // FIXME: should this work? They need "out" or "ref" modifiers.
                }
            }

            call = new CodeMethodInvokeExpression(
                thisExpr,
                "End" + od.Name,
                new CodeArgumentReferenceExpression("result"));
            call.Parameters.AddRange(outArgRefs.Cast <CodeExpression> ().ToArray());              // questionable

            var retCreate = new CodeArrayCreateExpression(typeof(object));

            if (resultType.BaseType == "System.Void")
            {
                cm.Statements.Add(call);
            }
            else
            {
                cm.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "__ret", call));
                retCreate.Initializers.Add(new CodeVariableReferenceExpression("__ret"));
            }
            foreach (var outArgRef in outArgRefs)
            {
                retCreate.Initializers.Add(new CodeVariableReferenceExpression(outArgRef.VariableName));
            }

            cm.Statements.Add(new CodeMethodReturnStatement(retCreate));

            // OnXxxCompleted() implementation
            cm = new CodeMemberMethod()
            {
                Name       = "On" + od.Name + "Completed",
                Attributes = MemberAttributes.Private | MemberAttributes.Final
            };
            type.Members.Add(cm);

            AddMethodParam(cm, typeof(object), "state");

            string argsname        = identifiers.AddUnique(od.Name + "CompletedEventArgs", null);
            var    iaargs          = new CodeTypeReference("InvokeAsyncCompletedEventArgs");  // avoid messy System.Type instance for generic nested type :|
            var    iaref           = new CodeVariableReferenceExpression("args");
            var    methodEventArgs = new CodeObjectCreateExpression(new CodeTypeReference(argsname),
                                                                    new CodePropertyReferenceExpression(iaref, "Results"),
                                                                    new CodePropertyReferenceExpression(iaref, "Error"),
                                                                    new CodePropertyReferenceExpression(iaref, "Cancelled"),
                                                                    new CodePropertyReferenceExpression(iaref, "UserState"));

            cm.Statements.Add(new CodeConditionStatement(
                                  new CodeBinaryOperatorExpression(
                                      new CodeEventReferenceExpression(thisExpr, od.Name + "Completed"), CodeBinaryOperatorType.IdentityInequality, nullExpr),
                                  new CodeVariableDeclarationStatement(iaargs, "args", new CodeCastExpression(iaargs, new CodeArgumentReferenceExpression("state"))),
                                  new CodeExpressionStatement(new CodeMethodInvokeExpression(thisExpr, od.Name + "Completed", thisExpr, methodEventArgs))));

            // delegate fields
            type.Members.Add(new CodeMemberField(new CodeTypeReference("BeginOperationDelegate"), "onBegin" + od.Name + "Delegate"));
            type.Members.Add(new CodeMemberField(new CodeTypeReference("EndOperationDelegate"), "onEnd" + od.Name + "Delegate"));
            type.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(SendOrPostCallback)), "on" + od.Name + "CompletedDelegate"));

            // XxxCompletedEventArgs class
            var argsType = new CodeTypeDeclaration(argsname);

            argsType.BaseTypes.Add(new CodeTypeReference(typeof(AsyncCompletedEventArgs)));
            cns.Types.Add(argsType);

            var argsCtor = new CodeConstructor()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object []), "results"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Exception), "error"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("error"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("cancelled"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("userState"));
            var resultsField = new CodeFieldReferenceExpression(thisExpr, "results");

            argsCtor.Statements.Add(new CodeAssignStatement(resultsField, new CodeArgumentReferenceExpression("results")));
            argsType.Members.Add(argsCtor);

            argsType.Members.Add(new CodeMemberField(typeof(object []), "results"));

            if (resultType.BaseType != "System.Void")
            {
                var resultProp = new CodeMemberProperty {
                    Name       = "Result",
                    Type       = resultType,
                    Attributes = MemberAttributes.Public | MemberAttributes.Final
                };
                resultProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(resultProp.Type, new CodeArrayIndexerExpression(resultsField, new CodePrimitiveExpression(0)))));
                argsType.Members.Add(resultProp);
            }

            // event field
            var handlerType = new CodeTypeReference(typeof(EventHandler <>));

            handlerType.TypeArguments.Add(new CodeTypeReference(argsType.Name));
            type.Members.Add(new CodeMemberEvent()
            {
                Name       = od.Name + "Completed",
                Type       = handlerType,
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            });

            // XxxAsync() implementations
            bool hasAsync = false;

            foreach (int __x in Enumerable.Range(0, 2))
            {
                cm = new CodeMemberMethod();
                type.Members.Add(cm);
                cm.Name       = od.Name + "Async";
                cm.Attributes = MemberAttributes.Public
                                | MemberAttributes.Final;

                var inArgs = new List <CodeParameterDeclarationExpression> ();

                for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++)
                {
                    var pd = method.Parameters [idx];
                    inArgs.Add(pd);
                    cm.Parameters.Add(pd);
                }

                // First one is overload without asyncState arg.
                if (!hasAsync)
                {
                    call = new CodeMethodInvokeExpression(thisExpr, cm.Name, inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray());
                    call.Parameters.Add(nullExpr);
                    cm.Statements.Add(new CodeExpressionStatement(call));
                    hasAsync = true;
                    continue;
                }

                // Second one is the primary one.

                cm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));

                // if (onBeginBarOperDelegate == null) onBeginBarOperDelegate = new BeginOperationDelegate (OnBeginBarOper);
                // if (onEndBarOperDelegate == null) onEndBarOperDelegate = new EndOperationDelegate (OnEndBarOper);
                // if (onBarOperCompletedDelegate == null) onBarOperCompletedDelegate = new BeginOperationDelegate (OnBarOperCompleted);
                var beginOperDelegateRef     = new CodeFieldReferenceExpression(thisExpr, "onBegin" + od.Name + "Delegate");
                var endOperDelegateRef       = new CodeFieldReferenceExpression(thisExpr, "onEnd" + od.Name + "Delegate");
                var operCompletedDelegateRef = new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate");

                var ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(beginOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(beginOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("BeginOperationDelegate"), thisExpr, "OnBegin" + od.Name)));
                cm.Statements.Add(ifstmt);
                ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(endOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(endOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("EndOperationDelegate"), thisExpr, "OnEnd" + od.Name)));
                cm.Statements.Add(ifstmt);
                ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(operCompletedDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(operCompletedDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SendOrPostCallback)), thisExpr, "On" + od.Name + "Completed")));
                cm.Statements.Add(ifstmt);

                // InvokeAsync (onBeginBarOperDelegate, inValues, onEndBarOperDelegate, onBarOperCompletedDelegate, userState);

                inArgs.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));

                var args = new List <CodeExpression> ();
                args.Add(beginOperDelegateRef);
                args.Add(new CodeArrayCreateExpression(typeof(object), inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray()));
                args.Add(endOperDelegateRef);
                args.Add(new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate"));
                args.Add(new CodeArgumentReferenceExpression("userState"));
                call = new CodeMethodInvokeExpression(baseExpr, "InvokeAsync", args.ToArray());
                cm.Statements.Add(new CodeExpressionStatement(call));
            }
        }
        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");
        }
Example #28
0
        public void AddStruct(string cfClassName)
        {
            ctst          = new CodeTypeDeclaration("struct_" + cfClassName);
            ctst.IsStruct = true;
            ctst.CustomAttributes.Add(new CodeAttributeDeclaration(
                                          new CodeTypeReference(typeof(StructLayoutAttribute))
                                          , new CodeAttributeArgument(

                                              new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(LayoutKind)),
                                                                               LayoutKind.Sequential.ToString())

                                              )
                                          , new CodeAttributeArgument("CharSet",
                                                                      new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(CharSet)),
                                                                                                       CharSet.Ansi.ToString()))


                                          , new CodeAttributeArgument("Pack", new CodePrimitiveExpression(1))

                                          ));

            cns.Types.Add(ctst);
            cmf_var = new CodeMemberField(ctst.Name, "var_" + ctst.Name);
            ctd.Members.Add(cmf_var);
            CodeConstructor cc1 = new CodeConstructor();

            cc1.Attributes = (cc1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cc1.Comments.Add(new CodeCommentStatement("<summary>使用空字符串初始化对象</summary>", true));
            cc1.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "s", new CodePrimitiveExpression("")));

            cc1.Statements.Add(
                new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), cmf_var.Name)

                                        , new CodeCastExpression(ctst.Name,

                                                                 new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Keel.DB.Common)), "StringToStruct"
                                                                                                , new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("s"), "PadRight",
                                                                                                                                 new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetLenght"), new CodePrimitiveExpression(' '))
                                                                                                , new CodeTypeOfExpression(ctst.Name))


                                                                 )));
            ctd.Members.Add(cc1);//添加默认初始化函数
            CodeConstructor cc = new CodeConstructor();

            cc.Comments.Add(new CodeCommentStatement("<summary>使用指定的字符串初始化对象</summary>", true));
            cc.Name = ctd.Name;
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "s"));
            cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            cc.Statements.Add(

                new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), cmf_var.Name)

                                        , new CodeCastExpression(ctst.Name,

                                                                 new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(Keel.DB.Common)), "StringToStruct"
                                                                                                , new CodeVariableReferenceExpression("s")
                                                                                                , new CodeTypeOfExpression(ctst.Name))


                                                                 )));

            ctd.Members.Add(cc);//添加带字符串参数的初始化函数

            CodeMemberMethod cmmToString = new CodeMemberMethod();

            cmmToString.Name = "ToString";

            cmmToString.ReturnType = new CodeTypeReference(typeof(string));
            cmmToString.Attributes = (cmmToString.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public | MemberAttributes.New;
            cmmToString.Statements.Add(new CodeMethodReturnStatement(
                                           new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(
                                                                              new CodeTypeReferenceExpression(typeof(Keel.DB.Common))
                                                                              , "StructToString"), new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), cmf_var.Name))));
            cmmToString.Comments.Add(new CodeCommentStatement("<summary>将结构转换为字符串</summary>", true));
            ctd.Members.Add(cmmToString);
        }
Example #29
0
 /// <summary>
 /// 无参
 /// </summary>
 public ItemConstruct()
 {
     construct = new CodeConstructor();
     construct.Attributes = MemberAttributes.Public;
 }
Example #30
0
        void GenerateCode()
        {
            //Create the target directory if required
            Directory.CreateDirectory(IOPath.GetDirectoryName(OutputFile));

            var ccu = new CodeCompileUnit();

            ccu.AssemblyCustomAttributes.Add(
                new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(XamlResourceIdAttribute).FullName}"),
                                             new CodeAttributeArgument(new CodePrimitiveExpression(ResourceId)),
                                             new CodeAttributeArgument(new CodePrimitiveExpression(TargetPath.Replace('\\', '/'))),                                             //use forward slashes, paths are uris-like
                                             new CodeAttributeArgument(RootType == null ? (CodeExpression) new CodePrimitiveExpression(null) : new CodeTypeOfExpression($"global::{RootClrNamespace}.{RootType}"))
                                             ));
            if (XamlResourceIdOnly)
            {
                goto writeAndExit;
            }

            if (RootType == null)
            {
                throw new Exception("Something went wrong while executing XamlG");
            }

            var declNs = new CodeNamespace(RootClrNamespace);

            ccu.Namespaces.Add(declNs);

            var declType = new CodeTypeDeclaration(RootType)
            {
                IsPartial        = true,
                CustomAttributes =
                {
                    new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(XamlFilePathAttribute).FullName}"),
                                                 new CodeAttributeArgument(new CodePrimitiveExpression(XamlFile))),
                }
            };

            if (AddXamlCompilationAttribute)
            {
                declType.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(XamlCompilationAttribute).FullName}"),
                                                 new CodeAttributeArgument(new CodeSnippetExpression($"global::{typeof(XamlCompilationOptions).FullName}.Compile"))));
            }
            if (HideFromIntellisense)
            {
                declType.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference($"global::{typeof(System.ComponentModel.EditorBrowsableAttribute).FullName}"),
                                                 new CodeAttributeArgument(new CodeSnippetExpression($"global::{typeof(System.ComponentModel.EditorBrowsableState).FullName}.{nameof(System.ComponentModel.EditorBrowsableState.Never)}"))));
            }

            declType.BaseTypes.Add(BaseType);

            declNs.Types.Add(declType);

            //Create a default ctor calling InitializeComponent
            if (GenerateDefaultCtor)
            {
                var ctor = new CodeConstructor
                {
                    Attributes       = MemberAttributes.Public,
                    CustomAttributes = { GeneratedCodeAttrDecl },
                    Statements       =
                    {
                        new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitializeComponent")
                    }
                };

                declType.Members.Add(ctor);
            }

            //Create InitializeComponent()
            var initcomp = new CodeMemberMethod
            {
                Name             = "InitializeComponent",
                CustomAttributes = { GeneratedCodeAttrDecl }
            };

            declType.Members.Add(initcomp);

            //Create and initialize fields
            initcomp.Statements.Add(new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(new CodeTypeReference($"global::{typeof(Extensions).FullName}")),
                                        "LoadFromXaml", new CodeThisReferenceExpression(), new CodeTypeOfExpression(declType.Name)));

            foreach (var namedField in NamedFields)
            {
                declType.Members.Add(namedField);

                var find_invoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeTypeReferenceExpression(new CodeTypeReference($"global::{typeof(NameScopeExtensions).FullName}")),
                        "FindByName", namedField.Type),
                    new CodeThisReferenceExpression(), new CodePrimitiveExpression(namedField.Name));

                CodeAssignStatement assign = new CodeAssignStatement(
                    new CodeVariableReferenceExpression(namedField.Name), find_invoke);

                initcomp.Statements.Add(assign);
            }

writeAndExit:
            //write the result
            using (var writer = new StreamWriter(OutputFile))
                Provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions());
        }
Example #31
0
		private static void AddDerivedConstructor(CodeTypeDeclaration decl, ConstructorInfo ci)
		{
			CodeConstructor cc = new CodeConstructor();
			cc.Attributes = MemberAttributes.Public;
			foreach (var pi in ci.GetParameters())
			{
				cc.Parameters.Add(new CodeParameterDeclarationExpression() { Name = pi.Name, Type = new CodeTypeReference(pi.ParameterType), Direction = ToDirection(pi) });
				cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(pi.Name));
			}

			decl.Members.Add(cc);
		}
Example #32
0
        static void Main(string[] args)
        {
            // Create a compile unit
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Define a Namespace
            //CodeNamespace automobileNamespace = new CodeNamespace("Automobile");
            CodeNamespace automobileNamespace1 = new CodeNamespace();

            // Import Namespaces
            automobileNamespace1.Imports.Add(new CodeNamespaceImport("System"));

            compileUnit.Namespaces.Add(automobileNamespace1);
            CodeNamespace automobileNamespace = new CodeNamespace("Automobile");

            compileUnit.Namespaces.Add(automobileNamespace);
            // Define a class
            CodeTypeDeclaration focusClass = new CodeTypeDeclaration("Focus");

            // Inherit a type
            focusClass.BaseTypes.Add("Car");

            automobileNamespace.Types.Add(focusClass);


            // Set custom attribute
            CodeAttributeDeclaration codeAttribute = new CodeAttributeDeclaration("System.Serializable");

            focusClass.CustomAttributes.Add(codeAttribute);
            // Set class attribute
            focusClass.IsClass        = true;
            focusClass.TypeAttributes = TypeAttributes.Public;

            // Declare a class member field
            CodeMemberField speedField = new CodeMemberField();

            speedField.Attributes = MemberAttributes.Private;
            speedField.Name       = "_Speed";
            speedField.Type       = new CodeTypeReference(typeof(int));

            focusClass.Members.Add(speedField);


            // Define a property
            CodeMemberProperty speedProperty = new CodeMemberProperty();

            speedProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            speedProperty.Name       = "Speed";
            speedProperty.HasGet     = true;
            speedProperty.Type       = new CodeTypeReference(typeof(int));

            speedProperty.GetStatements.Add(new CodeMethodReturnStatement(
                                                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Speed")));

            focusClass.Members.Add(speedProperty);


            // Declare a method
            CodeMemberMethod accelerateMethod = new CodeMemberMethod();

            accelerateMethod.Attributes = MemberAttributes.Public;
            accelerateMethod.Name       = "Accelerate";

            CodeFieldReferenceExpression speedFieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_Speed");

            CodeBinaryOperatorExpression addExpression = new CodeBinaryOperatorExpression(
                speedFieldReference, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10));

            CodeAssignStatement assignStatement = new CodeAssignStatement(speedFieldReference, addExpression);

            accelerateMethod.Statements.Add(assignStatement);
            focusClass.Members.Add(accelerateMethod);



            // Declare the constructor
            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            // Add a parameter
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "speed"));
            // Add field initialization logic
            constructor.Statements.Add(new CodeAssignStatement(speedFieldReference, new CodeArgumentReferenceExpression("speed")));

            focusClass.Members.Add(constructor);


            // Define the entry point
            CodeEntryPointMethod       entryPointMethod  = new CodeEntryPointMethod();
            CodeObjectCreateExpression focusObjectCreate = new CodeObjectCreateExpression(
                new CodeTypeReference("Focus"), new CodePrimitiveExpression(0));

            // Add the statement: "Focus focus = new Focus(0);"
            entryPointMethod.Statements.Add(new CodeVariableDeclarationStatement(
                                                new CodeTypeReference("Focus"), "focus", focusObjectCreate));
            // Create the expression: "focus.Accelerate()"
            CodeMethodInvokeExpression accelerateInvoke = new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("focus"), "Accelerate");

            entryPointMethod.Statements.Add(accelerateInvoke);
            focusClass.Members.Add(entryPointMethod);

            // Generate C# source code
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            using (StreamWriter sourceWriter = new StreamWriter("D:\\DSC.dev\\Source-VS11\\SQL2Class\\SQL2Class\\test\\Focus.cs"))
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, sourceWriter, options);
            }
        }
        private void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c)
        {
            if (!(IsCurrentClass)) return;

            if (e.CustomAttributes.Count > 0)
            {
                GenerateAttributes(e.CustomAttributes);
            }

            OutputMemberAccessModifier(e.Attributes);
            OutputIdentifier(CurrentTypeName);
            Output.Write("(");
            OutputParameters(e.Parameters);
            Output.Write(")");

            CodeExpressionCollection baseArgs = e.BaseConstructorArgs;
            CodeExpressionCollection thisArgs = e.ChainedConstructorArgs;

            if (baseArgs.Count > 0)
            {
                Output.WriteLine(" : ");
                Indent++;
                Indent++;
                Output.Write("base(");
                OutputExpressionList(baseArgs);
                Output.Write(")");
                Indent--;
                Indent--;
            }

            if (thisArgs.Count > 0)
            {
                Output.WriteLine(" : ");
                Indent++;
                Indent++;
                Output.Write("this(");
                OutputExpressionList(thisArgs);
                Output.Write(")");
                Indent--;
                Indent--;
            }

            OutputStartingBrace();
            Indent++;
            GenerateStatements(e.Statements);
            Indent--;
            Output.WriteLine("}");
        }
Example #34
0
        void AddAsyncMembers(string messageName, CodeMemberMethod method)
        {
            CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
            CodePrimitiveExpression     enull = new CodePrimitiveExpression(null);

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

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

            // Event arguments class

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

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

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

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

            int ind = 0;

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

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

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

            // Event delegate type

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

            // Event member

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

            // Async method (without user state param)

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

            // On...Completed method

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

            CodeConditionStatement anIf = new CodeConditionStatement();

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

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

            onCompleted.Statements.Add(anIf);

            // Async method

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

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

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

            // Assign parameters

            CodeIdentifiers paramsIds = new CodeIdentifiers();

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


            inv.Parameters.Add(enull);

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

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

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

            asyncTypes.Add(delegateType);
        }
 private static CodeTypeDeclaration CreateOperationCompletedEventArgsType(ServiceContractGenerationContext context, string syncMethodName, CodeMemberMethod endMethod)
 {
     if ((endMethod.Parameters.Count == 1) && (endMethod.ReturnType.BaseType == voidTypeRef.BaseType))
     {
         return null;
     }
     CodeTypeDeclaration ownerTypeDecl = context.TypeFactory.CreateClassType();
     ownerTypeDecl.BaseTypes.Add(new CodeTypeReference(asyncCompletedEventArgsType));
     CodeMemberField field = new CodeMemberField();
     field.Type = new CodeTypeReference(objectArrayType);
     CodeFieldReferenceExpression left = new CodeFieldReferenceExpression();
     left.TargetObject = new CodeThisReferenceExpression();
     CodeConstructor constructor = new CodeConstructor();
     constructor.Attributes = MemberAttributes.Public;
     for (int i = 0; i < EventArgsCtorParamTypes.Length; i++)
     {
         constructor.Parameters.Add(new CodeParameterDeclarationExpression(EventArgsCtorParamTypes[i], EventArgsCtorParamNames[i]));
         if (i > 0)
         {
             constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(EventArgsCtorParamNames[i]));
         }
     }
     ownerTypeDecl.Members.Add(constructor);
     constructor.Statements.Add(new CodeAssignStatement(left, new CodeVariableReferenceExpression(EventArgsCtorParamNames[0])));
     int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
     int num3 = 0;
     for (int j = 0; j < endMethod.Parameters.Count; j++)
     {
         if (j != asyncResultParamIndex)
         {
             CreateEventAsyncCompletedArgsTypeProperty(ownerTypeDecl, endMethod.Parameters[j].Type, endMethod.Parameters[j].Name, new CodeArrayIndexerExpression(left, new CodeExpression[] { new CodePrimitiveExpression(num3++) }));
         }
     }
     if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
     {
         CreateEventAsyncCompletedArgsTypeProperty(ownerTypeDecl, endMethod.ReturnType, NamingHelper.GetUniqueName("Result", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMemberNameExist), ownerTypeDecl), new CodeArrayIndexerExpression(left, new CodeExpression[] { new CodePrimitiveExpression(num3) }));
     }
     field.Name = NamingHelper.GetUniqueName("results", new NamingHelper.DoesNameExist(ClientClassGenerator.DoesMemberNameExist), ownerTypeDecl);
     left.FieldName = field.Name;
     ownerTypeDecl.Members.Add(field);
     ownerTypeDecl.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventArgsTypeName(syncMethodName), new NamingHelper.DoesNameExist(ClientClassGenerator.DoesTypeAndMemberNameExist), new object[] { context.Namespace.Types, ownerTypeDecl });
     context.Namespace.Types.Add(ownerTypeDecl);
     return ownerTypeDecl;
 }
Example #36
0
        static IType CreateClass(Project project, Stetic.ActionGroupComponent group, string name, string namspace, string folder)
        {
            string fullName = namspace.Length > 0 ? namspace + "." + name : name;

            CodeRefactorer gen = new CodeRefactorer(project.ParentSolution);

            CodeTypeDeclaration type = new CodeTypeDeclaration();

            type.Name    = name;
            type.IsClass = true;
            type.BaseTypes.Add(new CodeTypeReference("Gtk.ActionGroup"));

            // Generate the constructor. It contains the call that builds the widget.

            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(fullName));

            CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(
                    new CodeTypeReferenceExpression("Stetic.Gui"),
                    "Build"
                    ),
                new CodeThisReferenceExpression(),
                new CodeTypeOfExpression(fullName)
                );

            ctor.Statements.Add(call);
            type.Members.Add(ctor);

            // Add signal handlers

            foreach (Stetic.ActionComponent action in group.GetActions())
            {
                foreach (Stetic.Signal signal in action.GetSignals())
                {
                    CodeMemberMethod met = new CodeMemberMethod();
                    met.Name       = signal.Handler;
                    met.Attributes = MemberAttributes.Family;
                    met.ReturnType = new CodeTypeReference(signal.SignalDescriptor.HandlerReturnTypeName);

                    foreach (Stetic.ParameterDescriptor pinfo in signal.SignalDescriptor.HandlerParameters)
                    {
                        met.Parameters.Add(new CodeParameterDeclarationExpression(pinfo.TypeName, pinfo.Name));
                    }

                    type.Members.Add(met);
                }
            }

            // Create the class

            IType cls = null;

            cls = gen.CreateClass(project, ((DotNetProject)project).LanguageName, folder, namspace, type);
            if (cls == null)
            {
                throw new UserException("Could not create class " + fullName);
            }

            project.AddFile(cls.CompilationUnit.FileName, BuildAction.Compile);
            IdeApp.ProjectOperations.Save(project);

            // Make sure the database is up-to-date
            ProjectDomService.Parse(project, cls.CompilationUnit.FileName);
            return(cls);
        }
Example #37
0
			// CodeTypeMember
			
			public void Visit(CodeConstructor o)
			{
				g.GenerateConstructor(o, g.CurrentClass);
			}
 protected virtual void AddStatementsToConstructor(CodeConstructor ctor)
 {
 }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        // GENERATES (C#):
        //
        //  namespace NSPC {
        //      
        //      public class ClassWithMethod {
        //          
        //          public int Method() {
        //              return 4;
        //          }
        //      }
        //      
        //      public class ClassToTest {
        //          
        //          public int TestMethod() {
        //              ClassWithMethod tmp = new ClassWithMethod(2);
        //              ClassWithMethod temp = new ClassWithMethod();
        //              return temp.Method();
        //          }
        //          
        //          public int SecondTestMethod() {
        //              int a = 3;
        //              int b;
        //              b = 87;
        //              return (b - a);
        //          }
        //      }
        //  }

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

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ("ClassWithMethod");
        class1.IsClass = true;
        nspace.Types.Add (class1);

        // parameterless constructor
        CodeConstructor cons = new CodeConstructor ();
        cons.Attributes = MemberAttributes.Public;
        class1.Members.Add (cons);

        // parameterful constructor
        cons = new CodeConstructor ();
        cons.Attributes = MemberAttributes.Public;
        cons.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "myParameter"));
        cons.Statements.Add (new CodeVariableDeclarationStatement (
                    typeof (int), "noUse",
                    new CodeArgumentReferenceExpression ("myParameter")));
        class1.Members.Add (cons);

        CodeMemberMethod cmm = new CodeMemberMethod ();
        cmm.Name = "Method";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (4)));
        class1.Members.Add (cmm);

        class1 = new CodeTypeDeclaration ("ClassToTest");
        class1.IsClass = true;
        nspace.Types.Add (class1);

        AddScenario ("CheckTestMethod", "Check the return value of TestMethod.");
        cmm = new CodeMemberMethod ();
        cmm.Name = "TestMethod";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        cmm.ReturnType = new CodeTypeReference (typeof (int));

        // create a new class with the parameter
        cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("ClassWithMethod"),
            "tmp", new CodeObjectCreateExpression (new CodeTypeReference ("ClassWithMethod"),
                new CodePrimitiveExpression (2))));

        cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("ClassWithMethod"),
            "temp", new CodeObjectCreateExpression (new CodeTypeReference ("ClassWithMethod"))));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (
            new CodeVariableReferenceExpression ("temp"), "Method")));
        class1.Members.Add (cmm);

        AddScenario ("CheckSecondTestMethod", "Check the return value of SecondTestMethod.");
        cmm = new CodeMemberMethod ();
        cmm.Name = "SecondTestMethod";
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
        cmm.ReturnType = new CodeTypeReference (typeof (int));
        cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference (typeof (int)), "a", new CodePrimitiveExpression (3)));
        cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference (typeof (int)), "b"));
        cmm.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("b"), new CodePrimitiveExpression (87)));
        cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new
            CodeVariableReferenceExpression ("b"), CodeBinaryOperatorType.Subtract,
            new CodeVariableReferenceExpression ("a"))));
        class1.Members.Add (cmm);


    }
        public CodeTypeDelegateExample()
        {
            //<Snippet2>

            // Declares a type to contain the delegate and constructor method.
            CodeTypeDeclaration type1 = new CodeTypeDeclaration("DelegateTest");

            // Declares an event that accepts a custom delegate type of "TestDelegate".
            CodeMemberEvent event1 = new CodeMemberEvent();

            event1.Name = "TestEvent";
            event1.Type = new CodeTypeReference("DelegateTest.TestDelegate");
            type1.Members.Add(event1);

            //<Snippet3>
            // Declares a delegate type called TestDelegate with an EventArgs parameter.
            CodeTypeDelegate delegate1 = new CodeTypeDelegate("TestDelegate");

            delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender"));
            delegate1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e"));

            // A C# code generator produces the following source code for the preceeding example code:

            //     public delegate void TestDelegate(object sender, System.EventArgs e);
            //</Snippet3>
            type1.Members.Add(delegate1);

            // Declares a method that matches the "TestDelegate" method signature.
            CodeMemberMethod method1 = new CodeMemberMethod();

            method1.Name = "TestMethod";
            method1.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "sender"));
            method1.Parameters.Add(new CodeParameterDeclarationExpression("System.EventArgs", "e"));
            type1.Members.Add(method1);

            // Defines a constructor that attaches a TestDelegate delegate pointing to the TestMethod method
            // to the TestEvent event.
            CodeConstructor constructor1 = new CodeConstructor();

            constructor1.Attributes = MemberAttributes.Public;
            CodeDelegateCreateExpression createDelegate1 = new CodeDelegateCreateExpression(
                new CodeTypeReference("DelegateTest.TestDelegate"), new CodeThisReferenceExpression(), "TestMethod");
            CodeAttachEventStatement attachStatement1 = new CodeAttachEventStatement(new CodeThisReferenceExpression(), "TestEvent", createDelegate1);

            constructor1.Statements.Add(attachStatement1);
            type1.Members.Add(constructor1);

            // A C# code generator produces the following source code for the preceeding example code:

            //    public class DelegateTest
            //    {
            //
            //        public DelegateTest()
            //        {
            //            this.TestEvent += new DelegateTest.TestDelegate(this.TestMethod);
            //        }
            //
            //        private event DelegateTest.TestDelegate TestEvent;
            //
            //        private void TestMethod(object sender, System.EventArgs e)
            //        {
            //        }
            //
            //        public delegate void TestDelegate(object sender, System.EventArgs e);
            //    }

            //</Snippet2>
        }
        public void ProviderSupports()
        {
            CodeDomProvider provider = GetProvider();

            var cu = new CodeCompileUnit();
            var nspace = new CodeNamespace("NSPC");
            nspace.Imports.Add(new CodeNamespaceImport("System"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(nspace);

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

            // Arrays of Arrays
            var cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfArrays";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            if (provider.Supports(GeneratorSupport.ArraysOfArrays))
            {
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
                    "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
                    new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
                    new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                    new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
                    , new CodePrimitiveExpression(1))));
            }
            else
            {
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));
            }
            cd.Members.Add(cmm);

            // assembly attributes
            if (provider.Supports(GeneratorSupport.AssemblyAttributes))
            {
                CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
                    CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
                    CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            }

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
            {
                class1.Name = "Test2";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "accessStringField";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(String));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                    "stringField")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
                    CodeThisReferenceExpression(), "stringField"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);

                CodeConstructor cctor = new CodeConstructor();
                cctor.Attributes = MemberAttributes.Public;
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                class1.Members.Add(cctor);

                CodeConstructor cc = new CodeConstructor();
                cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
                cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                    , "stringField"), new CodeVariableReferenceExpression("p1")));
                class1.Members.Add(cc);
                // verify chained constructors work
                cmm = new CodeMemberMethod();
                cmm.Name = "ChainedConstructorUse";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(String));
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "accessStringField")));
                cd.Members.Add(cmm);
            }

            // complex expressions
            if (provider.Supports(GeneratorSupport.ComplexExpressions))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "ComplexExpressions";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(3)))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareEnums))
            {
                CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
                ce.IsEnum = true;
                nspace.Types.Add(ce);

                // things to enumerate
                for (int k = 0; k < 5; k++)
                {
                    CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
                    Field.InitExpression = new CodePrimitiveExpression(k);
                    ce.Members.Add(Field);
                }
                cmm = new CodeMemberMethod();
                cmm.Name = "OutputDecimalEnumVal";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
                    new CodePrimitiveExpression(3));
                CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
                    new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
                CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

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

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

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

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

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

            if (provider.Supports(GeneratorSupport.DeclareInterfaces))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestSingleInterface";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
                CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
                    , "InterfaceMethod");
                methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("InterfaceA");
                class1.IsInterface = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.Attributes = MemberAttributes.Public;
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                class1.Members.Add(cmm);

                if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
                {
                    CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
                    classDecl.IsInterface = true;
                    nspace.Types.Add(classDecl);
                    cmm = new CodeMemberMethod();
                    cmm.Name = "InterfaceMethod";
                    cmm.Attributes = MemberAttributes.Public;
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    classDecl.Members.Add(cmm);

                    CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
                    class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                    class2.IsClass = true;
                    nspace.Types.Add(class2);
                    cmm = new CodeMemberMethod();
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
                    cmm.Name = "InterfaceMethod";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                    class2.Members.Add(cmm);

                    cmm = new CodeMemberMethod();
                    cmm.Name = "TestMultipleInterfaces";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
                        new CodeVariableReferenceExpression("t"))));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
                        new CodeVariableReferenceExpression("t"))));
                    methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
                        , "InterfaceMethod");
                    methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
                        , "InterfaceMethod");
                    methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                        methodinvoke,
                        CodeBinaryOperatorType.Subtract, methodinvoke2)));
                    cd.Members.Add(cmm);
                }

                class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
                class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
                class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                class1.IsClass = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                class1.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareValueTypes))
            {
                CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
                structA.IsStruct = true;

                CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
                structB.Attributes = MemberAttributes.Public;
                structB.IsStruct = true;

                CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
                firstInt.Attributes = MemberAttributes.Public;
                structB.Members.Add(firstInt);

                CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
                innerStruct.Attributes = MemberAttributes.Public;

                structA.Members.Add(structB);
                structA.Members.Add(innerStruct);
                nspace.Types.Add(structA);

                CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
                nestedStructMethod.Name = "NestedStructMethod";
                nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
                nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
                nestedStructMethod.Statements.Add(varStructA);
                nestedStructMethod.Statements.Add
                    (
                    new CodeAssignStatement
                    (
                    /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
                    /* Expression1 */ new CodePrimitiveExpression(3)
                    )
                    );
                nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
                cd.Members.Add(nestedStructMethod);
            }
            if (provider.Supports(GeneratorSupport.EntryPointMethod))
            {
                CodeEntryPointMethod cep = new CodeEntryPointMethod();
                cd.Members.Add(cep);
            }
            // goto statements
            if (provider.Supports(GeneratorSupport.GotoStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "GoToMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
                    new CodeGotoStatement("comehere"));
                cmm.Statements.Add(condstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
                cmm.Statements.Add(new CodeLabeledStatement("comehere",
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
                cd.Members.Add(cmm);
            }
            if (provider.Supports(GeneratorSupport.NestedTypes))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "CallingPublicNestedScenario";
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
                    new CodeObjectCreateExpression(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
                    "publicNestedClassesMethod",
                    new CodeVariableReferenceExpression("i"))));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("PublicNestedClassA");
                class1.IsClass = true;
                nspace.Types.Add(class1);
                CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
                nestedClass.IsClass = true;
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                class1.Members.Add(nestedClass);
                nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                nestedClass.IsClass = true;
                class1.Members.Add(nestedClass);
                CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
                innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                innerNestedClass.IsClass = true;
                nestedClass.Members.Add(innerNestedClass);
                cmm = new CodeMemberMethod();
                cmm.Name = "publicNestedClassesMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                innerNestedClass.Members.Add(cmm);
            }
            // Parameter Attributes
            if (provider.Supports(GeneratorSupport.ParameterAttributes))
            {
                CodeMemberMethod method1 = new CodeMemberMethod();
                method1.Name = "MyMethod";
                method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
                param1.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                    "System.Xml.Serialization.XmlElementAttribute",
                    new CodeAttributeArgument(
                    "Form",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                    new CodeAttributeArgument(
                    "IsNullable",
                    new CodePrimitiveExpression(false))));
                method1.Parameters.Add(param1);
                cd.Members.Add(method1);
            }
            // public static members
            if (provider.Supports(GeneratorSupport.PublicStaticMembers))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "PublicStaticMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
                cd.Members.Add(cmm);
            }
            // reference parameters
            if (provider.Supports(GeneratorSupport.ReferenceParameters))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "Work";
                cmm.ReturnType = new CodeTypeReference("System.void");
                cmm.Attributes = MemberAttributes.Static;
                // add parameter with ref direction
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                param.Direction = FieldDirection.Ref;
                cmm.Parameters.Add(param);
                // add parameter with out direction
                param = new CodeParameterDeclarationExpression(typeof(int), "j");
                param.Direction = FieldDirection.Out;
                cmm.Parameters.Add(param);
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
                    CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
                    new CodePrimitiveExpression(5)));
                cd.Members.Add(cmm);

                cmm = new CodeMemberMethod();
                cmm.Name = "CallingWork";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(parames);
                cmm.ReturnType = new CodeTypeReference("System.int32");
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                    new CodePrimitiveExpression(10)));
                cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
                // invoke the method called "work"
                CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
                    (new CodeTypeReferenceExpression("TEST"), "Work"));
                // add parameter with ref direction
                CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
                    new CodeVariableReferenceExpression("a"));
                methodinvoked.Parameters.Add(parameter);
                // add parameter with out direction
                parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
                methodinvoked.Parameters.Add(parameter);
                cmm.Statements.Add(methodinvoked);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
                    (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
                cd.Members.Add(cmm);
            }
            if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
            {
                CodeMemberMethod function1 = new CodeMemberMethod();
                function1.Name = "MyFunction";
                function1.ReturnType = new CodeTypeReference(typeof(string));
                function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                function1.ReturnTypeCustomAttributes.Add(new
                    CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
                function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                    CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                    CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
                function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
                cd.Members.Add(function1);
            }
            if (provider.Supports(GeneratorSupport.StaticConstructors))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestStaticConstructor";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
                // set then get number
                cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
                    , new CodeVariableReferenceExpression("a")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "i")));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration();
                class1.Name = "Test4";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "i";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(int));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);
                CodeTypeConstructor ctc = new CodeTypeConstructor();
                class1.Members.Add(ctc);
            }
            if (provider.Supports(GeneratorSupport.TryCatchStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TryCatchMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);

                CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
                tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
                    CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(5))));
                cmm.Statements.Add(tcfstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                cd.Members.Add(cmm);
            }
            if (provider.Supports(GeneratorSupport.DeclareEvents))
            {
                CodeNamespace ns = new CodeNamespace();
                ns.Name = "MyNamespace";
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
                ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
                ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
                cu.Namespaces.Add(ns);
                class1 = new CodeTypeDeclaration("Test");
                class1.IsClass = true;
                class1.BaseTypes.Add(new CodeTypeReference("Form"));
                ns.Types.Add(class1);

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

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

                CodeMemberEvent evt = new CodeMemberEvent();
                evt.Name = "MyEvent";
                evt.Type = new CodeTypeReference("System.EventHandler");
                evt.Attributes = MemberAttributes.Public;
                class1.Members.Add(evt);

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

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

                  [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")]
                  [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")]

                  namespace NSPC {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;

                      public class TEST {

                          public int ArraysOfArrays() {
                              int[][] arrayOfArrays = new int[][] {
                                      new int[] { 3, 4},
                                      new int[] { 1}};
                              return arrayOfArrays[0][1];
                          }

                          public static string ChainedConstructorUse() {
                              Test2 t = new Test2();
                              return t.accessStringField;
                          }

                          public int ComplexExpressions(int i) {
                              i = (i * (i + 3));
                              return i;
                          }

                          public static int OutputDecimalEnumVal(int i) {
                              if ((i == 3)) {
                                  return ((int)(DecimalEnum.Num3));
                              }
                              if ((i == 4)) {
                                  return ((int)(DecimalEnum.Num4));
                              }
                              if ((i == 2)) {
                                  return ((int)(DecimalEnum.Num2));
                              }
                              if ((i == 1)) {
                                  return ((int)(DecimalEnum.Num1));
                              }
                              if ((i == 0)) {
                                  return ((int)(DecimalEnum.Num0));
                              }
                              return (i + 10);
                          }

                          public static int TestSingleInterface(int i) {
                              TestSingleInterfaceImp t = new TestSingleInterfaceImp();
                              return t.InterfaceMethod(i);
                          }

                          public static int TestMultipleInterfaces(int i) {
                              TestMultipleInterfaceImp t = new TestMultipleInterfaceImp();
                              InterfaceA interfaceAobject = ((InterfaceA)(t));
                              InterfaceB interfaceBobject = ((InterfaceB)(t));
                              return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i));
                          }

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

                          public static void Main() { }

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

                          public static int CallingPublicNestedScenario(int i) {
                              PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC t = new PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC();
                              return t.publicNestedClassesMethod(i);
                          }

                          public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah) {
                          }

                          public static int PublicStaticMethod() {
                              return 16;
                          }

                          static void Work(ref int i, out int j) {
                              i = (i + 4);
                              j = 5;
                          }

                          public static int CallingWork(int a) {
                              a = 10;
                              int b;
                              TEST.Work(ref a, out b);
                              return (a + b);
                          }

                          [return: System.Xml.Serialization.XmlIgnoreAttribute()]
                          [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")]
                          public string MyFunction() {
                              return ""Return"";
                          }

                          public static int TestStaticConstructor(int a) {
                              Test4 t = new Test4();
                              t.i = a;
                              return t.i;
                          }

                          public static int TryCatchMethod(int a) {
                              try {
                              }
                              finally {
                                  a = (a + 5);
                              }
                              return a;
                          }
                      }

                      public class Test2 {

                          private string stringField;

                          public Test2() :
                                  this(""testingString"", null, null) {
                          }

                          public Test2(string p1, string p2, string p3) {
                              this.stringField = p1;
                          }

                          public string accessStringField {
                              get {
                                  return this.stringField;
                              }
                              set {
                                  this.stringField = value;
                              }
                          }
                      }

                      public enum DecimalEnum {
                          Num0 = 0,
                          Num1 = 1,
                          Num2 = 2,
                          Num3 = 3,
                          Num4 = 4,
                      }

                      public interface InterfaceA {
                          int InterfaceMethod(int a);
                      }

                      public interface InterfaceB {
                          int InterfaceMethod(int a);
                      }

                      public class TestMultipleInterfaceImp : object, InterfaceB, InterfaceA {
                          public int InterfaceMethod(int a) {
                              return a;
                          }
                      }

                      public class TestSingleInterfaceImp : object, InterfaceA {
                          public virtual int InterfaceMethod(int a) {
                              return a;
                          }
                      }

                      public struct structA {
                          public structB innerStruct;

                          public struct structB {
                              public int int1;
                          }
                      }

                      public class PublicNestedClassA {

                          public class PublicNestedClassB1 { }

                          public class PublicNestedClassB2 {
                              public class PublicNestedClassC {
                                  public int publicNestedClassesMethod(int a) {
                                      return a;
                                  }
                              }
                          }
                      }

                      public class Test4 {

                          private int number;

                          static Test4() {
                          }

                          public int i {
                              get {
                                  return number;
                              }
                              set {
                                  number = value;
                              }
                          }
                      }
                  }
                  namespace MyNamespace {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;

                      public class Test : Form {
                          private Button b = new Button();

                          public Test() {
                              this.Size = new Size(600, 600);
                              b.Text = ""Test"";
                              b.TabIndex = 0;
                              b.Location = new Point(400, 525);
                              this.MyEvent += new EventHandler(this.b_Click);
                          }

                          public event System.EventHandler MyEvent;

                          private void b_Click(object sender, System.EventArgs e) {
                          }
                      }
                  }");
        }
Example #42
0
        /// <summary>
        /// Processes an XmlSchemaComplexType into corresponding types.
        /// </summary>
        /// <param name="typeName">Name to use for the type being output.</param>
        /// <param name="elementNamespace">Namespace of the xml element.</param>
        /// <param name="documentation">Documentation for the element.</param>
        /// <param name="complexType">XmlSchemaComplexType to be processed.</param>
        /// <param name="codeNamespace">CodeNamespace to be used when outputting code.</param>
        private static void ProcessComplexType(string typeName, string elementNamespace, XmlSchemaComplexType complexType, string documentation, CodeNamespace codeNamespace)
        {
            CodeMemberMethod outputXmlMethod = new CodeMemberMethod();

            outputXmlMethod.Attributes = MemberAttributes.Public;
            outputXmlMethod.ImplementationTypes.Add("ISchemaElement");
            outputXmlMethod.Name = "OutputXml";
            outputXmlMethod.Parameters.Add(new CodeParameterDeclarationExpression("XmlTextWriter", "writer"));
            outputXmlMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteStartElement", new CodeSnippetExpression(String.Concat("\"", typeName, "\"")), new CodeSnippetExpression(String.Concat("\"", elementNamespace, "\""))));
            GenerateSummaryComment(outputXmlMethod.Comments, outputXmlComment);

            if (complexType.ContentModel == null)
            {
                CodeTypeDeclaration typeDeclaration = new CodeTypeDeclaration(typeName);
                typeDeclaration.Attributes = MemberAttributes.Public;
                typeDeclaration.IsClass    = true;
                CodeIterationStatement childEnumStatement = null;

                if (documentation != null)
                {
                    GenerateSummaryComment(typeDeclaration.Comments, documentation);
                }

                if (complexType.Particle != null)
                {
                    CodeMemberField childrenField = new CodeMemberField("ElementCollection", "children");
                    typeDeclaration.Members.Add(childrenField);

                    CodeMemberProperty childrenProperty = new CodeMemberProperty();
                    childrenProperty.Attributes = MemberAttributes.Public;
                    childrenProperty.Name       = "Children";
                    childrenProperty.Type       = new CodeTypeReference("IEnumerable");
                    childrenProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children")));
                    typeDeclaration.Members.Add(childrenProperty);

                    CodeMemberProperty filterChildrenProperty = new CodeMemberProperty();
                    filterChildrenProperty.Attributes = MemberAttributes.Public;
                    filterChildrenProperty.Name       = "Item";
                    filterChildrenProperty.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "childType"));
                    filterChildrenProperty.Type = new CodeTypeReference("IEnumerable");
                    filterChildrenProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children"), "Filter", new CodeVariableReferenceExpression("childType"))));
                    typeDeclaration.Members.Add(filterChildrenProperty);

                    CodeMemberMethod addChildMethod = new CodeMemberMethod();
                    addChildMethod.Attributes = MemberAttributes.Public;
                    addChildMethod.Name       = "AddChild";
                    addChildMethod.Parameters.Add(new CodeParameterDeclarationExpression("ISchemaElement", "child"));
                    CodeExpressionStatement addChildStatement = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children"), "AddElement", new CodeVariableReferenceExpression("child")));
                    addChildMethod.Statements.Add(addChildStatement);
                    typeDeclaration.Members.Add(addChildMethod);

                    CodeMemberMethod removeChildMethod = new CodeMemberMethod();
                    removeChildMethod.Attributes = MemberAttributes.Public;
                    removeChildMethod.Name       = "RemoveChild";
                    removeChildMethod.Parameters.Add(new CodeParameterDeclarationExpression("ISchemaElement", "child"));
                    CodeExpressionStatement removeChildStatement = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children"), "RemoveElement", new CodeVariableReferenceExpression("child")));
                    removeChildMethod.Statements.Add(removeChildStatement);
                    typeDeclaration.Members.Add(removeChildMethod);

                    CodeConstructor typeConstructor = new CodeConstructor();
                    typeConstructor.Attributes = MemberAttributes.Public;

                    CodeVariableReferenceExpression collectionVariable = null;

                    XmlSchemaChoice schemaChoice = complexType.Particle as XmlSchemaChoice;
                    if (schemaChoice != null)
                    {
                        collectionVariable = ProcessSchemaGroup(schemaChoice, typeConstructor);
                    }
                    else
                    {
                        XmlSchemaSequence schemaSequence = complexType.Particle as XmlSchemaSequence;
                        if (schemaSequence != null)
                        {
                            collectionVariable = ProcessSchemaGroup(schemaSequence, typeConstructor);
                        }
                    }

                    typeConstructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children"), collectionVariable));
                    typeDeclaration.Members.Add(typeConstructor);

                    childEnumStatement = new CodeIterationStatement();
                    childEnumStatement.InitStatement  = new CodeVariableDeclarationStatement("IEnumerator", "enumerator", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "children"), "GetEnumerator"));
                    childEnumStatement.TestExpression = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("enumerator"), "MoveNext");
                    childEnumStatement.Statements.Add(new CodeVariableDeclarationStatement("ISchemaElement", "childElement", new CodeCastExpression("ISchemaElement", new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("enumerator"), "Current"))));
                    childEnumStatement.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("childElement"), "OutputXml", new CodeVariableReferenceExpression("writer")));
                    childEnumStatement.IncrementStatement = new CodeExpressionStatement(new CodeSnippetExpression(""));
                }

                // TODO: Handle xs:anyAttribute here.
                foreach (XmlSchemaAttribute schemaAttribute in complexType.Attributes)
                {
                    ProcessAttribute(schemaAttribute, typeDeclaration, outputXmlMethod);
                }

                if (childEnumStatement != null)
                {
                    outputXmlMethod.Statements.Add(childEnumStatement);
                }

                typeDeclaration.BaseTypes.Add(new CodeTypeReference("ISchemaElement"));
                typeDeclaration.Members.Add(outputXmlMethod);
                codeNamespace.Types.Add(typeDeclaration);
            }
            else
            {
                ProcessSimpleContent(typeName, (XmlSchemaSimpleContentExtension)complexType.ContentModel.Content, documentation, codeNamespace, outputXmlMethod, false);
            }

            outputXmlMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("writer"), "WriteEndElement"));
        }
Example #43
0
    public CodeMemberMethod GenerateBasicMethodDefinition(Smoke* smoke, Smoke.Method* method, string cppSignature,
	                                                      CodeTypeReference iface)
    {
        // do we actually want that method?
        string className = ByteArrayManager.GetString(smokeClass->className);
        string completeSignature = className + "::" + cppSignature;
        if (translator.ExcludedMethods.Any(regex => regex.IsMatch(completeSignature)))
        {
            return null;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // add the parameters
        foreach (CodeParameterDeclarationExpression exp in args)
        {
            cmm.Parameters.Add(exp);
        }
        this.DocumentMemberFromInterface(iface, cmm);
        this.DistributeMethod(cmm);
        if (PostMethodDefinitionHooks != null)
        {
            PostMethodDefinitionHooks(smoke, method, cmm, this.type);
        }
        this.CorrectParameterNames(cmm);
        return cmm;
    }
Example #44
0
 /// <summary>
 /// Processes an XmlSchemaGroupBase element.
 /// </summary>
 /// <param name="schemaGroup">Element group to process.</param>
 /// <param name="constructor">Constructor to which statements should be added.</param>
 /// <returns>A reference to the local variable containing the collection.</returns>
 private static CodeVariableReferenceExpression ProcessSchemaGroup(XmlSchemaGroupBase schemaGroup, CodeConstructor constructor)
 {
     return(ProcessSchemaGroup(schemaGroup, constructor, 0));
 }
Example #45
0
    /*
     * Create a .NET class from a smoke class.
     * A class Namespace::Foo is mapped to Namespace.Foo. Classes that are not in any namespace go into the default namespace.
     * For namespaces that contain functions, a Namespace.Global class is created which holds the functions as methods.
     */
    private void DefineClass(short classId)
    {
        Smoke.Class* smokeClass = data.Smoke->classes + classId;
        string smokeName = ByteArrayManager.GetString(smokeClass->className);
        string mapName = smokeName;
        string name;
        string prefix = string.Empty;
        if (smokeClass->size == 0 && !translator.NamespacesAsClasses.Contains(smokeName))
        {
            if (smokeName == "QGlobalSpace")
            {
                // global space
                name = data.GlobalSpaceClassName;
                mapName = name;
            }
            else
            {
                // namespace
                prefix = smokeName;
                name = "Global";
                mapName = prefix + "::Global";
            }
        }
        else
        {
            int colon = smokeName.LastIndexOf("::", StringComparison.Ordinal);
            prefix = (colon != -1) ? smokeName.Substring(0, colon) : string.Empty;
            name = (colon != -1) ? smokeName.Substring(colon + 2) : smokeName;
        }

        // define the .NET class
        CodeTypeDeclaration type;
        bool alreadyDefined;
        if (!(alreadyDefined = data.CSharpTypeMap.TryGetValue(mapName, out type)))
        {
            type = new CodeTypeDeclaration(name);
            CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeClass",
                                                                         new CodeAttributeArgument(
                                                                             new CodePrimitiveExpression(smokeName)));
            type.CustomAttributes.Add(attr);
            type.IsPartial = true;
        }
        else
        {
            int toBeRemoved = -1;

            for (int i = 0; i < type.CustomAttributes.Count; i++)
            {
                CodeAttributeDeclaration attr = type.CustomAttributes[i];
                if (attr.Name == "SmokeClass" && attr.Arguments.Count == 1 &&
                    ((string) ((CodePrimitiveExpression) attr.Arguments[0].Value).Value) == "QGlobalSpace")
                {
                    toBeRemoved = i;
                    break;
                }
            }

            if (toBeRemoved > -1)
            {
                type.CustomAttributes.RemoveAt(toBeRemoved);
                CodeAttributeDeclaration attr = new CodeAttributeDeclaration("SmokeClass",
                                                                             new CodeAttributeArgument(
                                                                                 new CodePrimitiveExpression(smokeName)));
                type.CustomAttributes.Add(attr);
            }
        }

        if (smokeClass->parents != 0)
        {
            short* parent = data.Smoke->inheritanceList + smokeClass->parents;
            if (*parent > 0)
            {
                type.BaseTypes.Add(
                    new CodeTypeReference(ByteArrayManager.GetString((data.Smoke->classes + *parent)->className).Replace("::", ".")));
            }
        }

        if (Util.IsClassAbstract(data.Smoke, classId))
        {
            type.TypeAttributes |= TypeAttributes.Abstract;
        }

        if (PreMembersHooks != null)
        {
            PreMembersHooks(data.Smoke, smokeClass, type);
        }

        if (!alreadyDefined)
        {
            DefineWrapperClassFieldsAndMethods(smokeClass, type);
            data.CSharpTypeMap[mapName] = type;
            IList collection = data.GetTypeCollection(prefix);
            collection.Add(type);
            type.UserData.Add("parent", prefix);

            // add the internal implementation type for abstract classes
            if ((type.TypeAttributes & TypeAttributes.Abstract) == TypeAttributes.Abstract)
            {
                CodeTypeDeclaration implType = new CodeTypeDeclaration();
                implType.Name = type.Name + "Internal";
                implType.BaseTypes.Add(new CodeTypeReference(type.Name));
                implType.IsPartial = true;
                implType.TypeAttributes = TypeAttributes.NotPublic;

                CodeConstructor dummyCtor = new CodeConstructor();
                dummyCtor.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(Type)), "dummy"));
                dummyCtor.BaseConstructorArgs.Add(new CodeSnippetExpression("(System.Type) null"));
                dummyCtor.Attributes = MemberAttributes.Family;
                implType.Members.Add(dummyCtor);

                data.InternalTypeMap[type] = implType;

                collection.Add(implType);
            }
        }

        data.SmokeTypeMap[(IntPtr) smokeClass] = type;
    }
Example #46
0
        /// <summary>
        /// Processes an XmlSchemaGroupBase element.
        /// </summary>
        /// <param name="schemaGroup">Element group to process.</param>
        /// <param name="constructor">Constructor to which statements should be added.</param>
        /// <param name="depth">Depth to which this collection is nested.</param>
        /// <returns>A reference to the local variable containing the collection.</returns>
        private static CodeVariableReferenceExpression ProcessSchemaGroup(XmlSchemaGroupBase schemaGroup, CodeConstructor constructor, int depth)
        {
            string collectionName = String.Format("childCollection{0}", depth);
            CodeVariableReferenceExpression  collectionVariableReference = new CodeVariableReferenceExpression(collectionName);
            CodeVariableDeclarationStatement collectionStatement         = new CodeVariableDeclarationStatement("ElementCollection", collectionName);

            if (schemaGroup is XmlSchemaChoice)
            {
                int min = (int)schemaGroup.MinOccurs;

                int max;
                if (schemaGroup.MaxOccursString == "unbounded")
                {
                    max = -1;
                }
                else
                {
                    max = (int)schemaGroup.MaxOccurs;
                }

                collectionStatement.InitExpression = new CodeObjectCreateExpression("ElementCollection", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("ElementCollection.CollectionType"), "Choice"), new CodeSnippetExpression(min.ToString()), new CodeSnippetExpression(max.ToString()));
            }
            else
            {
                collectionStatement.InitExpression = new CodeObjectCreateExpression("ElementCollection", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("ElementCollection.CollectionType"), "Sequence"));
            }
            constructor.Statements.Add(collectionStatement);

            foreach (XmlSchemaObject obj in schemaGroup.Items)
            {
                XmlSchemaElement schemaElement = obj as XmlSchemaElement;
                if (schemaElement != null)
                {
                    if (schemaGroup is XmlSchemaChoice)
                    {
                        CodeMethodInvokeExpression addItemInvoke = new CodeMethodInvokeExpression(collectionVariableReference, "AddItem", new CodeObjectCreateExpression("ElementCollection.ChoiceItem", new CodeTypeOfExpression(schemaElement.RefName.Name)));
                        constructor.Statements.Add(addItemInvoke);
                    }
                    else
                    {
                        int min = (int)schemaElement.MinOccurs;

                        int max;
                        if (schemaElement.MaxOccursString == "unbounded")
                        {
                            max = -1;
                        }
                        else
                        {
                            max = (int)schemaElement.MaxOccurs;
                        }

                        CodeMethodInvokeExpression addItemInvoke = new CodeMethodInvokeExpression(collectionVariableReference, "AddItem", new CodeObjectCreateExpression("ElementCollection.SequenceItem", new CodeTypeOfExpression(schemaElement.RefName.Name), new CodeSnippetExpression(min.ToString()), new CodeSnippetExpression(max.ToString())));
                        constructor.Statements.Add(addItemInvoke);
                    }

                    continue;
                }

                XmlSchemaAny schemaAny = obj as XmlSchemaAny;
                if (schemaAny != null)
                {
                    if (schemaGroup is XmlSchemaChoice)
                    {
                        CodeMethodInvokeExpression addItemInvoke = new CodeMethodInvokeExpression(collectionVariableReference, "AddItem", new CodeObjectCreateExpression("ElementCollection.ChoiceItem", new CodeTypeOfExpression("ISchemaElement")));
                        constructor.Statements.Add(addItemInvoke);
                    }
                    else
                    {
                        CodeMethodInvokeExpression addItemInvoke = new CodeMethodInvokeExpression(collectionVariableReference, "AddItem", new CodeObjectCreateExpression("ElementCollection.SequenceItem", new CodeTypeOfExpression("ISchemaElement"), new CodeSnippetExpression("0"), new CodeSnippetExpression("-1")));
                        constructor.Statements.Add(addItemInvoke);
                    }

                    continue;
                }

                XmlSchemaGroupBase schemaGroupBase = obj as XmlSchemaGroupBase;
                if (schemaGroupBase != null)
                {
                    CodeVariableReferenceExpression nestedCollectionReference = ProcessSchemaGroup(schemaGroupBase, constructor, depth + 1);
                    CodeMethodInvokeExpression      addCollectionInvoke       = new CodeMethodInvokeExpression(collectionVariableReference, "AddCollection", nestedCollectionReference);
                    constructor.Statements.Add(addCollectionInvoke);

                    continue;
                }
            }

            return(collectionVariableReference);
        }
	protected override void GenerateConstructor
				(CodeConstructor e, CodeTypeDeclaration c)
			{
				// Bail out if not a class or struct.
				if(!IsCurrentClass && !IsCurrentStruct)
				{
					return;
				}

				// Output the attributes and constructor signature.
				OutputAttributeDeclarations(e.CustomAttributes);
				OutputMemberAccessModifier(e.Attributes);
				OutputIdentifier(CurrentTypeName);
				Output.Write("(");
				OutputParameters(e.Parameters);
				Output.Write(")");

				// Output the ": base" or ": this" expressions.
				if(e.BaseConstructorArgs.Count > 0)
				{
					Output.WriteLine(" : ");
					Indent += 2;
					Output.Write("base(");
					OutputExpressionList(e.BaseConstructorArgs);
					Output.Write(")");
					Indent -= 2;
				}
				if(e.ChainedConstructorArgs.Count > 0)
				{
					Output.WriteLine(" : ");
					Indent += 2;
					Output.Write("base(");
					OutputExpressionList(e.ChainedConstructorArgs);
					Output.Write(")");
					Indent -= 2;
				}

				// Output the body of the constructor.
				StartBlock();
				GenerateStatements(e.Statements);
				EndBlock();
			}
Example #48
0
        /// <summary>
        /// Generate the message files.
        /// </summary>
        /// <param name="messagesDoc">Input Xml document containing message definitions.</param>
        /// <param name="codeCompileUnit">CodeDom container.</param>
        /// <param name="resourceWriter">Writer for default resource file.</param>
        public static void Generate(XmlDocument messagesDoc, CodeCompileUnit codeCompileUnit, ResourceWriter resourceWriter)
        {
            Hashtable usedNumbers = new Hashtable();

            if (null == messagesDoc)
            {
                throw new ArgumentNullException("messagesDoc");
            }

            if (null == codeCompileUnit)
            {
                throw new ArgumentNullException("codeCompileUnit");
            }

            if (null == resourceWriter)
            {
                throw new ArgumentNullException("resourceWriter");
            }

            string namespaceAttr = messagesDoc.DocumentElement.GetAttribute("Namespace");
            string resourcesAttr = messagesDoc.DocumentElement.GetAttribute("Resources");

            // namespace
            CodeNamespace messagesNamespace = new CodeNamespace(namespaceAttr);

            codeCompileUnit.Namespaces.Add(messagesNamespace);

            // imports
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System"));
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System.Resources"));
            if (namespaceAttr != "Microsoft.Tools.WindowsInstallerXml")
            {
                messagesNamespace.Imports.Add(new CodeNamespaceImport("Microsoft.Tools.WindowsInstallerXml"));
            }

            foreach (XmlElement classElement in messagesDoc.DocumentElement.ChildNodes)
            {
                string className         = classElement.GetAttribute("Name");
                string baseContainerName = classElement.GetAttribute("BaseContainerName");
                string containerName     = classElement.GetAttribute("ContainerName");

                // message container class
                messagesNamespace.Types.Add(CreateContainer(namespaceAttr, baseContainerName, containerName, resourcesAttr));

                // class
                CodeTypeDeclaration messagesClass = new CodeTypeDeclaration(className);
                messagesClass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
                messagesNamespace.Types.Add(messagesClass);

                // private constructor (needed since all methods in this class are static)
                CodeConstructor constructor = new CodeConstructor();
                constructor.Attributes = MemberAttributes.Private;
                constructor.ReturnType = null;
                messagesClass.Members.Add(constructor);

                // messages
                foreach (XmlElement messageElement in classElement.ChildNodes)
                {
                    int    number;
                    string id                = messageElement.GetAttribute("Id");
                    string numberString      = messageElement.GetAttribute("Number");
                    bool   sourceLineNumbers = true;

                    // determine the message number (and ensure it was set properly)
                    if (0 < numberString.Length)
                    {
                        number = Convert.ToInt32(numberString, CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        throw new ApplicationException(String.Format("Message number must be assigned for {0} '{1}'.", containerName, id));
                    }

                    // check for message number collisions
                    if (usedNumbers.Contains(number))
                    {
                        throw new ApplicationException(String.Format("Collision detected between two or more messages with number '{0}'.", number));
                    }

                    usedNumbers.Add(number, null);

                    if ("no" == messageElement.GetAttribute("SourceLineNumbers"))
                    {
                        sourceLineNumbers = false;
                    }

                    int instanceCount = 0;
                    foreach (XmlElement instanceElement in messageElement.ChildNodes)
                    {
                        string formatString = instanceElement.InnerText.Trim();
                        string resourceName = String.Concat(className, "_", id, "_", (++instanceCount).ToString());

                        // create a resource
                        resourceWriter.AddResource(resourceName, formatString);

                        // create method
                        CodeMemberMethod method = new CodeMemberMethod();
                        method.ReturnType = new CodeTypeReference(containerName);
                        method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                        messagesClass.Members.Add(method);

                        // method name
                        method.Name = id;

                        // return statement
                        CodeMethodReturnStatement stmt = new CodeMethodReturnStatement();
                        method.Statements.Add(stmt);

                        // return statement expression
                        CodeObjectCreateExpression expr = new CodeObjectCreateExpression();
                        stmt.Expression = expr;

                        // new struct
                        expr.CreateType = new CodeTypeReference(containerName);

                        // optionally have sourceLineNumbers as the first parameter
                        if (sourceLineNumbers)
                        {
                            // sourceLineNumbers parameter
                            expr.Parameters.Add(new CodeArgumentReferenceExpression("sourceLineNumbers"));
                        }
                        else
                        {
                            expr.Parameters.Add(new CodePrimitiveExpression(null));
                        }

                        // message number parameter
                        expr.Parameters.Add(new CodePrimitiveExpression(number));

                        // resource name parameter
                        expr.Parameters.Add(new CodePrimitiveExpression(resourceName));

                        // optionally have sourceLineNumbers as the first parameter
                        if (sourceLineNumbers)
                        {
                            method.Parameters.Add(new CodeParameterDeclarationExpression("SourceLineNumberCollection", "sourceLineNumbers"));
                        }

                        foreach (XmlNode parameterNode in instanceElement.ChildNodes)
                        {
                            XmlElement parameterElement;

                            if (null != (parameterElement = parameterNode as XmlElement))
                            {
                                string type = parameterElement.GetAttribute("Type");
                                string name = parameterElement.GetAttribute("Name");

                                // method parameter
                                method.Parameters.Add(new CodeParameterDeclarationExpression(type, name));

                                // String.Format parameter
                                expr.Parameters.Add(new CodeArgumentReferenceExpression(name));
                            }
                        }
                    }
                }
            }
        }
    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);
        }

    }
Example #50
0
        /// <summary>
        /// Main driving routine for building a class
        /// </summary>
        public static void BuildClass(string expression)
        {
            // need a string to put the code into
            _source = new StringBuilder();
            StringWriter sw = new StringWriter(_source);

            //Declare your provider and generator
            CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
            ICodeGenerator       generator    = codeProvider.CreateGenerator(sw);
            CodeGeneratorOptions codeOpts     = new CodeGeneratorOptions();

            CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator");

            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            myNamespace.Imports.Add(new CodeNamespaceImport("MissionPlanner.Utilities"));
            myNamespace.Imports.Add(new CodeNamespaceImport("MissionPlanner"));

            //Build the class declaration and member variables
            CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration();

            classDeclaration.IsClass    = true;
            classDeclaration.Name       = "Calculator";
            classDeclaration.Attributes = MemberAttributes.Public;
            classDeclaration.Members.Add(FieldVariable("answer", typeof(object), MemberAttributes.Private));

            //default constructor
            CodeConstructor defaultConstructor = new CodeConstructor();

            defaultConstructor.Attributes = MemberAttributes.Public;
            defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));
            defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));

            classDeclaration.Members.Add(defaultConstructor);


            //property
            classDeclaration.Members.Add(MakeProperty("Answer", "answer", typeof(object)));

            //Our Calculate Method

            /*
             * CodeMemberMethod myMethod = new CodeMemberMethod();
             * myMethod.Name = "Calculate";
             * myMethod.ReturnType = new CodeTypeReference(typeof(object));
             * myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));
             * myMethod.Attributes = MemberAttributes.Public;
             * myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Object obj"), new CodeSnippetExpression(expression)));
             * //myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression("obj.ToString()")));
             * myMethod.Statements.Add(
             *             new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer")));
             * classDeclaration.Members.Add(myMethod);
             */

            classDeclaration.Members.Add(FieldVariable("customforusenumber", typeof(double), MemberAttributes.Public));
            classDeclaration.Members.Add(FieldVariable("customforuseobject", typeof(object), MemberAttributes.Public));

            CodeSnippetTypeMember myMethod = new CodeSnippetTypeMember();

            myMethod.Text = expression;

            classDeclaration.Members.Add(myMethod);

            //write code
            myNamespace.Types.Add(classDeclaration);
            generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);
            sw.Flush();
            sw.Close();

            Console.Write(sw.ToString());
        }
Example #51
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 static string GenerateWrapper(WrapperClass wrapperClass, Language language)
        {
            // Namespace
            CodeNamespace _namespace = new CodeNamespace(wrapperClass.Namespace);

            // Comments
            string comment =
                @"------------------------------------------------------------------------------" + Environment.NewLine +
                @" <auto-generated>" + Environment.NewLine +
                @"     This code was generated by '.NET Wrapper Class Generator'" + Environment.NewLine +
                @"     Product Version:" + Assembly.GetExecutingAssembly().GetName().Version + Environment.NewLine + Environment.NewLine +
                @"     Changes to this file may cause incorrect behavior and will be lost if" + Environment.NewLine +
                @"     the code is regenerated." + Environment.NewLine +
                @" </auto-generated>" + Environment.NewLine +
                @" ------------------------------------------------------------------------------";

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

            // Class
            CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration(wrapperClass.ClassName);

            classDeclaration.IsPartial = wrapperClass.Partial;
            if (wrapperClass.Sealed)
            {
                classDeclaration.TypeAttributes |= TypeAttributes.Sealed;
            }
            _namespace.Types.Add(classDeclaration);

            // Initialization
            CodeParameterDeclarationExpressionCollection initializationParameters = null;
            CodeStatementCollection initiazationStatements = null;

            if (wrapperClass.Partial)
            {
                // Initialization method
                CodeMemberMethod initializer = new CodeMemberMethod();
                classDeclaration.Members.Add(initializer);
                initializer.Name       = "InitializeWrapper";
                initializer.Attributes = MemberAttributes.Private;
                {
                    comment =
                        @"***************************************************************" + Environment.NewLine +
                        @" This method should be called by the user-provided constructor!" + Environment.NewLine +
                        @"***************************************************************";
                    initializer.Comments.Add(new CodeCommentStatement(comment));
                }
                initializationParameters = initializer.Parameters;
                initiazationStatements   = initializer.Statements;
            }
            else
            {
                // Constructor
                CodeConstructor constructor = new CodeConstructor();
                classDeclaration.Members.Add(constructor);
                constructor.Attributes   = MemberAttributes.Public;
                initializationParameters = constructor.Parameters;
                initiazationStatements   = constructor.Statements;
            }

            // Iterate over the wrapped types
            foreach (WrappedType wrappedType in wrapperClass.WrappedTypes)
            {
                // Fields
                CodeMemberField field = new CodeMemberField(wrappedType.Type, wrappedType.FieldName);
                if (wrappedType.Acquisition != Acquisition.UserManaged)
                {
                    classDeclaration.Members.Add(field);
                }
                string memberPrefix = string.Empty;
                if (wrappedType.PrefixMembers)
                {
                    memberPrefix = wrappedType.FieldName;
                    memberPrefix = memberPrefix.Substring(0, 1).ToUpper() + memberPrefix.Substring(1);
                }


                CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), wrappedType.FieldName);
                if (wrappedType.Acquisition == Acquisition.Construct)
                {
                    // Instantiation
                    CodeObjectCreateExpression instantiation      = new CodeObjectCreateExpression(wrappedType.Type);
                    CodeAssignStatement        instanceAssignment = new CodeAssignStatement(fieldReference, instantiation);
                    initiazationStatements.Add(instanceAssignment);
                }
                else if (wrappedType.Acquisition == Acquisition.Parameter)
                {
                    // Pass as parameter
                    initializationParameters.Add(new CodeParameterDeclarationExpression(wrappedType.Type, wrappedType.FieldName));
                    initiazationStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression(wrappedType.FieldName)));
                }
                else if (wrappedType.Acquisition == Acquisition.Property)
                {
                    // Set as property
                    CodeMemberProperty property = new CodeMemberProperty();
                    property.Attributes = MemberAttributes.Public;
                    property.HasGet     = property.HasSet = true;
                    property.Type       = new CodeTypeReference(wrappedType.Type);
                    property.Name       = wrappedType.Type.Name;
                    property.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    property.SetStatements.Add(new CodeAssignStatement(fieldReference, new CodeVariableReferenceExpression("value")));
                    classDeclaration.Members.Add(property);
                }

                // Methods
                foreach (WrappedMethod wrappedMethod in wrappedType.WrappedMethods)
                {
                    // Method
                    CodeMemberMethod method = new CodeMemberMethod();
                    classDeclaration.Members.Add(method);
                    method.Name       = memberPrefix + wrappedMethod.Method.Name;
                    method.ReturnType = new CodeTypeReference(wrappedMethod.Method.ReturnType);

                    Generator.SetMember(method, wrappedMethod);

                    if (!string.IsNullOrEmpty(wrappedMethod.Interface))
                    {
                        method.PrivateImplementationType = new CodeTypeReference(wrappedMethod.Interface);
                    }

                    // Parameters
                    List <CodeExpression> arguments = Generator.SetParameters(method, wrappedMethod.Method.GetParameters());

                    // Statement
                    CodeMethodInvokeExpression invocation = null;
                    if (!wrappedMethod.Method.IsStatic)
                    {
                        invocation = new CodeMethodInvokeExpression(fieldReference, wrappedMethod.Method.Name, arguments.ToArray());
                    }
                    else
                    {
                        invocation         = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(wrappedType.Type), wrappedMethod.Method.Name, arguments.ToArray());
                        method.Attributes |= MemberAttributes.Static;
                    }

                    if (wrappedMethod.Method.ReturnType == typeof(void))
                    {
                        method.Statements.Add(invocation);
                    }
                    else
                    {
                        method.Statements.Add(new CodeMethodReturnStatement(invocation));
                    }
                }

                // Properties
                foreach (WrappedProperty wrappedProperty in wrappedType.WrappedProperties)
                {
                    // Property
                    CodeMemberProperty property = new CodeMemberProperty();
                    classDeclaration.Members.Add(property);
                    property.Name = memberPrefix + wrappedProperty.Property.Name;
                    property.Type = new CodeTypeReference(wrappedProperty.Property.PropertyType);

                    Generator.SetMember(property, wrappedProperty);

                    if (!string.IsNullOrEmpty(wrappedProperty.Interface))
                    {
                        property.PrivateImplementationType = new CodeTypeReference(wrappedProperty.Interface);
                    }

                    CodePropertyReferenceExpression invocation = null;
                    if (true)                     // TODO: check if property is static
                    {
                        invocation = new CodePropertyReferenceExpression(fieldReference, wrappedProperty.Property.Name);
                    }
                    else
                    {
                    }

                    // Get statement
                    if (wrappedProperty.Get)
                    {
                        property.GetStatements.Add(new CodeMethodReturnStatement(invocation));
                    }

                    // Set statement
                    if (wrappedProperty.Set)
                    {
                        property.SetStatements.Add(new CodeAssignStatement(invocation, new CodeVariableReferenceExpression("value")));
                    }
                }

                // Events
                foreach (WrappedEvent wrappedEvent in wrappedType.WrappedEvents)
                {
                    // Event
                    MethodInfo eventDelegate = wrappedEvent.Event.EventHandlerType.GetMethod("Invoke");

                    CodeMemberEvent _event = new CodeMemberEvent();
                    classDeclaration.Members.Add(_event);
                    _event.Name = memberPrefix + wrappedEvent.Event.Name;
                    _event.Type = new CodeTypeReference(wrappedEvent.Event.EventHandlerType);

                    Generator.SetMember(_event, wrappedEvent);

                    if (!string.IsNullOrEmpty(wrappedEvent.Interface))
                    {
                        _event.PrivateImplementationType = new CodeTypeReference(wrappedEvent.Interface);
                    }

                    // Event handler/raiser
                    CodeMemberMethod eventHandler = new CodeMemberMethod();
                    classDeclaration.Members.Add(eventHandler);
                    eventHandler.Name       = string.Format("On{0}", _event.Name);
                    eventHandler.ReturnType = new CodeTypeReference(eventDelegate.ReturnType);
                    eventHandler.Attributes = MemberAttributes.Private;

                    List <CodeExpression> arguments = Generator.SetParameters(eventHandler, eventDelegate.GetParameters());

                    CodeEventReferenceExpression eventReference = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), _event.Name);
                    CodeConditionStatement       conditional    = new CodeConditionStatement();
                    eventHandler.Statements.Add(conditional);
                    conditional.Condition = new CodeBinaryOperatorExpression(eventReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));

                    CodeDelegateInvokeExpression eventInvocation = new CodeDelegateInvokeExpression(eventReference, arguments.ToArray());
                    if (eventDelegate.ReturnType == typeof(void))
                    {
                        conditional.TrueStatements.Add(eventInvocation);
                    }
                    else
                    {
                        conditional.TrueStatements.Add(new CodeMethodReturnStatement(eventInvocation));
                    }

                    // Event registration
                    CodeEventReferenceExpression  wrappedEventReference = new CodeEventReferenceExpression(fieldReference, wrappedEvent.Event.Name);
                    CodeMethodReferenceExpression eventRaiserReference  = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), eventHandler.Name);
                    CodeAttachEventStatement      eventRegistration     = new CodeAttachEventStatement(wrappedEventReference, eventRaiserReference);
                    initiazationStatements.Add(eventRegistration);
                }
            }

            // Generate the code
            StringWriter    stringWriter = new StringWriter();
            CodeDomProvider codeProvider = null;

            if (language == Language.CSharp)
            {
                codeProvider = new CSharpCodeProvider();
            }
            else if (language == Language.VBNet)
            {
                codeProvider = new VBCodeProvider();
            }
            else
            {
                throw new ArgumentException("Specified language is not supported: " + language);
            }
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            codeProvider.GenerateCodeFromNamespace(_namespace, stringWriter, options);
            return(stringWriter.ToString());
        }
Example #53
0
 private CodeConstructor EnsureClassConstructor()
 {
     if (this.classConstructor == null)
     {
         this.classConstructor = new CodeConstructor
         {
             Attributes = MemberAttributes.Static,
         };
         gen.CurrentType.Members.Add(classConstructor);
     }
     return this.classConstructor;
 }
Example #54
0
        private void GenerateClient(string name, CodeNamespace ns, int complex_type_count)
        {
            CodeTypeDeclaration type = ns.AddType(name);

            type.IsClass        = true;
            type.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
            type.BaseTypes.Add(typeof(RpcAlpcClientBase));

            CodeConstructor constructor = type.AddConstructor(MemberAttributes.Public | MemberAttributes.Final);

            constructor.BaseConstructorArgs.Add(CodeGenUtils.GetPrimitive(_server.InterfaceId.ToString()));
            constructor.BaseConstructorArgs.Add(CodeGenUtils.GetPrimitive(_server.InterfaceVersion.Major));
            constructor.BaseConstructorArgs.Add(CodeGenUtils.GetPrimitive(_server.InterfaceVersion.Minor));

            foreach (var proc in _server.Procedures)
            {
                string proc_name = proc.Name;
                if (!_proc_names.Add(proc_name))
                {
                    proc_name = $"{proc_name}_{proc.ProcNum}";
                    if (!_proc_names.Add(proc_name))
                    {
                        throw new ArgumentException($"Duplicate name {proc.Name}");
                    }
                }

                var method = type.AddMethod(proc_name, MemberAttributes.Public | MemberAttributes.Final);
                RpcTypeDescriptor return_type = GetTypeDescriptor(proc.ReturnValue.Type);
                if (return_type == null)
                {
                    method.ThrowNotImplemented("Return type unsupported.");
                    continue;
                }

                var offset_to_name =
                    proc.Params.Select(p => Tuple.Create(p.Offset, p.Name)).ToList();

                method.ReturnType = return_type.CodeType;
                method.CreateMarshalObject(MARSHAL_NAME);
                foreach (var p in proc.Params)
                {
                    if (p == proc.Handle)
                    {
                        continue;
                    }
                    RpcTypeDescriptor p_type = GetTypeDescriptor(p.Type);

                    List <RpcMarshalArgument> extra_marshal_args = new List <RpcMarshalArgument>();
                    if (p_type.VarianceDescriptor.IsValid)
                    {
                        extra_marshal_args.Add(p_type.VarianceDescriptor.CalculateCorrelationArgument(p.Offset, offset_to_name));
                    }

                    var p_obj = method.AddParam(p_type.GetParameterType(), p.Name);
                    p_obj.Direction = p.GetDirection();
                    if (!p.IsIn)
                    {
                        continue;
                    }
                    if (p_type.Pointer)
                    {
                        if (p_type.PointerType == RpcPointerType.Reference)
                        {
                            method.AddNullCheck(MARSHAL_NAME, p.Name);
                        }
                        else
                        {
                            method.AddWriteReferent(MARSHAL_NAME, p.Name);
                        }
                    }
                    else if (!p_type.ValueType)
                    {
                        method.AddNullCheck(MARSHAL_NAME, p.Name);
                    }
                    method.AddMarshalCall(p_type, MARSHAL_NAME, p.Name, extra_marshal_args.ToArray());
                    // If it's a constructed type then ensure any deferred writes are flushed.
                    if (p_type.Constructed)
                    {
                        method.AddFlushDeferredWrites(MARSHAL_NAME);
                    }
                }

                method.SendReceive(MARSHAL_NAME, UNMARSHAL_NAME, proc.ProcNum);

                foreach (var p in proc.Params.Where(x => x.IsOut))
                {
                    if (p == proc.Handle)
                    {
                        continue;
                    }

                    RpcTypeDescriptor p_type = GetTypeDescriptor(p.Type);
                    if (p_type.Pointer)
                    {
                        method.AddPointerUnmarshalCall(p_type, UNMARSHAL_NAME, p.Name);
                    }
                    else
                    {
                        method.AddUnmarshalCall(p_type, UNMARSHAL_NAME, p.Name);
                    }
                    if (p_type.Constructed)
                    {
                        method.AddPopluateDeferredPointers(UNMARSHAL_NAME);
                    }
                }

                method.AddUnmarshalReturn(return_type, UNMARSHAL_NAME);
            }

            if (complex_type_count > 0 && HasFlag(RpcClientBuilderFlags.GenerateConstructorProperties))
            {
                var constructor_type = new CodeTypeReference(CodeGenUtils.MakeIdentifier(CONSTRUCTOR_STRUCT_NAME));
                var prop             = type.AddProperty("New", constructor_type, MemberAttributes.Public | MemberAttributes.Final,
                                                        new CodeMethodReturnStatement(new CodeObjectCreateExpression(constructor_type)));
                constructor_type = new CodeTypeReference(CodeGenUtils.MakeIdentifier(ARRAY_CONSTRUCTOR_STRUCT_NAME));
                type.AddProperty("NewArray", constructor_type, MemberAttributes.Public | MemberAttributes.Final,
                                 new CodeMethodReturnStatement(new CodeObjectCreateExpression(constructor_type)));
            }
        }
        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");
        }
Example #56
0
        public CodeCompileUnit GetCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit          = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces);

            var mapper  = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;

            CreateProperties(codeGenerationHelper, mapper, newType);

            // Generate GetHashCode() and Equals() methods.
            if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count != 0 && Table.PrimaryKey.Type == PrimaryKeyType.CompositeKey)
            {
                var pkColsList = new List <string>();
                foreach (var pkCol in Table.PrimaryKey.Columns)
                {
                    if (pkCol.IsForeignKey && appPrefs.IncludeForeignKeys)
                    {
                        pkColsList.Add(Formatter.FormatSingular(pkCol.ForeignKeyTableName) + "." + Formatter.FormatText(pkCol.ForeignKeyColumnName));
                    }
                    else
                    {
                        pkColsList.Add(Formatter.FormatText(pkCol.Name));
                    }
                }

                var equalsCode     = CreateCompositeKeyEqualsMethod(pkColsList);
                var getHashKeyCode = CreateCompositeKeyGetHashKeyMethod(pkColsList);

                equalsCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NHibernate Composite Key Requirements"));
                newType.Members.Add(equalsCode);
                newType.Members.Add(getHashKeyCode);
                getHashKeyCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            }

            // Don't create a constructor if there are no relationships.
            if (Table.HasManyRelationships.Count == 0)
            {
                return(compileUnit);
            }

            var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                PrefixRemovalList = appPrefs.FieldPrefixRemovalList
            };
            var constructorStatements = new CodeStatementCollection();

            if (appPrefs.IncludeHasMany)
            {
                foreach (var hasMany in Table.HasManyRelationships)
                {
                    if (appPrefs.Language == Language.CSharp)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(
                                                $"{appPrefs.ForeignEntityCollectionType}<{appPrefs.ClassNamePrefix}{pascalCaseTextFormatter.FormatSingular(hasMany.Reference)}>", Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                        constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                    }
                    else if (appPrefs.Language == Language.VB)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(
                                                $"{appPrefs.ForeignEntityCollectionType}(Of {appPrefs.ClassNamePrefix}{pascalCaseTextFormatter.FormatSingular(hasMany.Reference)})", Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                        constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = New {1}(Of {2}{3})()", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                    }
                }
            }

            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.AddRange(constructorStatements);
            newType.Members.Add(constructor);
            return(compileUnit);
        }
    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
    }
        private static CodeNamespace CreateMimsyNamespace()
        {
            var mimsyNamespace = new CodeNamespace("Mimsy");

            mimsyNamespace.Imports.AddRange(new[]
            {
                new CodeNamespaceImport("System"),
                new CodeNamespaceImport("System.Text"),
                new CodeNamespaceImport("System.Collections")
            });

            var jubjubClass = new CodeTypeDeclaration("Jubjub")
            {
                TypeAttributes = TypeAttributes.Public
            };
            var wabeCountFld = new CodeMemberField(typeof(int), "_wabeCount")
            {
                Attributes = MemberAttributes.Private
            };

            jubjubClass.Members.Add(wabeCountFld);

            var typrefArrayList = new CodeTypeReference("ArrayList");
            var updatesFld      = new CodeMemberField(typrefArrayList, "_updates");

            jubjubClass.Members.Add(updatesFld);
            mimsyNamespace.Types.Add(jubjubClass);
            var jubjubCtor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };
            var jubjubCtorParam = new CodeParameterDeclarationExpression(typeof(int), "wabeCount");

            jubjubCtor.Parameters.Add(jubjubCtorParam);

            var refUpdatesFld = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_updates");
            var newArrayList  = new CodeObjectCreateExpression(typrefArrayList);
            var assignUpdates = new CodeAssignStatement(refUpdatesFld, newArrayList);

            jubjubCtor.Statements.Add(assignUpdates);

            var refWabeCountFld  = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_wabeCount");
            var refWabeCountProp = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "WabeCount");
            var refWabeCountArg  = new CodeArgumentReferenceExpression("wabeCount");
            var assignWabeCount  = new CodeAssignStatement(refWabeCountProp, refWabeCountArg);

            jubjubCtor.Statements.Add(assignWabeCount);
            jubjubClass.Members.Add(jubjubCtor);
            var wabeCountProp = new CodeMemberProperty
            {
                Attributes = (MemberAttributes)24578,
                Type       = new CodeTypeReference(typeof(int)),
                Name       = "WabeCount"
            };

            wabeCountProp.GetStatements.Add(new CodeMethodReturnStatement(refWabeCountFld));
            var suppliedPropertyValue = new CodePropertySetValueReferenceExpression();
            var zero = new CodePrimitiveExpression(0);
            var suppliedPropValIsLessThanZero = new CodeBinaryOperatorExpression(suppliedPropertyValue,
                                                                                 CodeBinaryOperatorType.LessThan, zero);
            var testSuppliedPropValAndAssign = new CodeConditionStatement(suppliedPropValIsLessThanZero,
                                                                          new CodeStatement[] { new CodeAssignStatement(refWabeCountFld, zero) },
                                                                          new CodeStatement[] { new CodeAssignStatement(refWabeCountFld, suppliedPropertyValue) });

            wabeCountProp.SetStatements.Add(testSuppliedPropValAndAssign);
            wabeCountProp.SetStatements.Add(
                new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refUpdatesFld, "Add"), refWabeCountFld));
            jubjubClass.Members.Add(wabeCountProp);
            var methGetWabeCountHistory = new CodeMemberMethod
            {
                Attributes = (MemberAttributes)24578,
                Name       = "GetWabeCountHistory",
                ReturnType = new CodeTypeReference(typeof(string))
            };

            jubjubClass.Members.Add(methGetWabeCountHistory);
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement("StringBuilder", "result"));
            var refResultVar = new CodeVariableReferenceExpression("result");

            methGetWabeCountHistory.Statements.Add(new CodeAssignStatement(refResultVar,
                                                                           new CodeObjectCreateExpression("StringBuilder")));
            methGetWabeCountHistory.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "ndx"));
            var refNdxVar = new CodeVariableReferenceExpression("ndx");

            methGetWabeCountHistory.Statements.Add(
                new CodeIterationStatement(new CodeAssignStatement(refNdxVar, new CodePrimitiveExpression(0)),
                                           new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.LessThan,
                                                                            new CodePropertyReferenceExpression(refUpdatesFld, "Count")),
                                           new CodeAssignStatement(refNdxVar,
                                                                   new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))),
                                           new CodeConditionStatement(
                                               new CodeBinaryOperatorExpression(refNdxVar, CodeBinaryOperatorType.ValueEquality,
                                                                                new CodePrimitiveExpression(0)),
                                               new CodeStatement[]
            {
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                                                   new CodePrimitiveExpression("{0}"), new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)))
            },
                                               new CodeStatement[]
            {
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refResultVar, "AppendFormat"),
                                                   new CodePrimitiveExpression(", {0}"),
                                                   new CodeArrayIndexerExpression(refUpdatesFld, refNdxVar)))
            })));

            methGetWabeCountHistory.Statements.Add(
                new CodeMethodReturnStatement(
                    new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(refResultVar, "ToString"))));

            return(mimsyNamespace);
        }
	protected override void GenerateConstructor
				(CodeConstructor e, CodeTypeDeclaration c)
			{
				// Bail out if not a class or struct.
				if(!IsCurrentClass && !IsCurrentStruct)
				{
					return;
				}

				// Output the attributes and constructor signature.
				OutputAttributeDeclarations(e.CustomAttributes);
				OutputMemberAccessModifier(e.Attributes);
				Output.Write("Sub New ");
				Output.Write("(");
				OutputParameters(e.Parameters);
				Output.WriteLine(")");

				// Output the body of the constructor.
				++Indent;
				GenerateStatements(e.Statements);
				--Indent;
				Output.WriteLine("End Sub");
			}
        /// <summary>
        /// Implements a DataTable.
        /// </summary>
        /// <param name="tableSchema">The table schema that describes the event arguments.</param>
        public TypedChangeEventArgsClass(TableSchema tableSchema)
        {
            // The row change arguments are designed for this table.
            this.tableSchema = tableSchema;

            // Construct the type names for the table and rows within the table.
            string tableTypeName   = string.Format("{0}DataTable", tableSchema.Name);
            string rowTypeName     = string.Format("{0}Row", tableSchema.Name);
            string eventTypeName   = string.Format("{0}ChangeEvent", rowTypeName);
            string rowVariableName = string.Format("{0}Row", tableSchema.Name[0].ToString().ToLower() + tableSchema.Name.Remove(0, 1));

            //		/// <summary>
            //		/// Arguments for the event that indicates a change in a Department table row.
            //		/// </summary>
            //		[System.Diagnostics.DebuggerStepThrough()]
            //		public class DepartmentRowChangeEvent : EventArgs
            //		{
            CodeTypeDeclaration tableClass = new CodeTypeDeclaration();

            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Arguments for the event that indicates a change in a {0} table row.", this.tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.CustomAttributes.Add(new CodeAttributeDeclaration("System.Diagnostics.DebuggerStepThrough"));
            this.TypeAttributes = TypeAttributes.Public;
            this.IsClass        = true;
            this.Name           = eventTypeName;
            this.BaseTypes.Add("EventArgs");

            //			/// <summary>
            //			/// The Department row that has been changed.
            //			/// </summary>
            //			private DepartmentRow departmentRow;
            CodeMemberField tableRowField = new CodeMemberField(new CodeTypeReference(rowTypeName), rowVariableName);

            tableRowField.Attributes = MemberAttributes.Private;
            tableRowField.Comments.Add(new CodeCommentStatement("<summary>", true));
            tableRowField.Comments.Add(new CodeCommentStatement(string.Format("The {0} row that has been changed.", this.tableSchema.Name), true));
            tableRowField.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Members.Add(tableRowField);

            //			/// <summary>
            //			/// The action that caused the change to the row.
            //			/// </summary>
            //			private DataRowAction dataRowAction;
            CodeMemberField dataRowActionField = new CodeMemberField(new CodeTypeReference("DataRowAction"), "dataRowAction");

            dataRowActionField.Comments.Add(new CodeCommentStatement("<summary>", true));
            dataRowActionField.Comments.Add(new CodeCommentStatement("The action that caused the change to the row.", true));
            dataRowActionField.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Members.Add(dataRowActionField);

            //			/// <summary>
            //			/// Create the arguments for a changing Department row event.
            //			/// </summary>
            //			/// <param name="departmentRow">The Department row that has changed.</param>
            //			/// <param name="dataRowAction">The action that caused the change.</param>
            //			public DepartmentRowChangeEvent(DepartmentRow departmentRow, DataRowAction dataRowAction)
            //			{
            //				// Initialize the object.
            //				this.departmentRow = departmentRow;
            //				this.dataRowAction = dataRowAction;
            //			}
            CodeConstructor constructor = new CodeConstructor();

            this.Members.Add(constructor);
            constructor.Comments.Add(new CodeCommentStatement("<summary>", true));
            constructor.Comments.Add(new CodeCommentStatement(string.Format("Create the arguments for a changing {0} row event.", this.tableSchema.Name), true));
            constructor.Comments.Add(new CodeCommentStatement("</summary>", true));
            constructor.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} row that has changed.</param>", rowVariableName, this.tableSchema.Name), true));
            constructor.Comments.Add(new CodeCommentStatement("<param name=\"dataRowAction\">The action that caused the change.</param>", true));
            constructor.Attributes = MemberAttributes.Public;
            constructor.Parameters.Add(new CodeParameterDeclarationExpression(rowTypeName, rowVariableName));
            constructor.Parameters.Add(new CodeParameterDeclarationExpression("DataRowAction", "dataRowAction"));
            constructor.Statements.Add(new CodeCommentStatement("Initialize the object."));
            constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), rowVariableName), new CodeArgumentReferenceExpression(rowVariableName)));
            constructor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataRowAction"), new CodeArgumentReferenceExpression("dataRowAction")));

            //			/// <summary>
            //			/// Gets the Department row that has been changed.
            //			/// </summary>
            //			public DepartmentRow DepartmentRow
            //			{
            //				get
            //				{
            //					return this.departmentRow;
            //				}
            //			}
            CodeMemberProperty tableRowProperty = new CodeMemberProperty();

            tableRowProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            tableRowProperty.Comments.Add(new CodeCommentStatement(string.Format("Gets the {0} row that has been changed.", this.tableSchema.Name), true));
            tableRowProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            tableRowProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            tableRowProperty.Type       = new CodeTypeReference(rowTypeName);
            tableRowProperty.Name       = rowTypeName;
            tableRowProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), rowVariableName)));
            this.Members.Add(tableRowProperty);

            //			/// <summary>
            //			/// Gets the action that caused the change to the row.
            //			/// </summary>
            //			public DataRowAction Action
            //			{
            //				get
            //				{
            //					return this.dataRowAction;
            //				}
            //			}
            CodeMemberProperty actionProperty = new CodeMemberProperty();

            actionProperty.Comments.Add(new CodeCommentStatement("<summary>", true));
            actionProperty.Comments.Add(new CodeCommentStatement("Gets the action that caused the change to the row.", true));
            actionProperty.Comments.Add(new CodeCommentStatement("</summary>", true));
            actionProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            actionProperty.Type       = new CodeTypeReference("DataRowAction");
            actionProperty.Name       = "Action";
            actionProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "dataRowAction")));
            this.Members.Add(actionProperty);

            //		}
        }