Esempio n. 1
0
        public static void CreateUser()
        {
            // create namespace
            NamespaceDeclaration ns = new NamespaceDeclaration("MyFirstNamespace");

            // adding imports

            // creating User class
            ClassDeclaration user = ns.AddClass("User");

            // put some comments
            user.Doc.Summary.AddText("System.Extentions User class");
            user.Doc.Remarks.Add("para");
            user.Doc.Remarks.Into();
            user.Doc.Remarks.AddText("This class was generated by System.Extentions");
            user.Doc.Remarks.OutOf();

            // adding private fields
            FieldDeclaration name     = user.AddField(typeof(string), "name");
            FieldDeclaration lastName = user.AddField(typeof(string), "lastName");

            // adding properties for the fields
            PropertyDeclaration pname     = user.AddProperty(name, true, true, true);
            PropertyDeclaration plastName = user.AddProperty(lastName, true, true, true);

            Output(ns);
        }
Esempio n. 2
0
        public static void Refly()
        {
            // creating the Refly.Demo namespace
            NamespaceDeclaration demo = new NamespaceDeclaration("Refly.Demo");

            // create the user class
            ClassDeclaration user = demo.AddClass("User");

            // add name field
            FieldDeclaration name = user.AddField(typeof(string), "name");

            // add constructor
            ConstructorDeclaration cstr = user.AddConstructor();
            // add name parameter
            ParameterDeclaration pname = cstr.Signature.Parameters.Add(typeof(string), "name", true);

            // this.name = name;
            cstr.Body.AddAssign(
                Expr.This.Field(name),
                Expr.Arg(pname)
                );

            // add property
            user.AddProperty(name, true, false, false);
        }
 /// <summary>
 /// Creates a plain ol' property representing any column that is not a foreign key or primary key.
 /// </summary>
 /// <param name="classDeclaration">The class to which the property is added.</param>
 /// <param name="column">The column the property represents.</param>
 protected override void CreateNonKeyProperty(ClassDeclaration classDeclaration, ColumnSchema column)
 {
     string propertyName = this.NameProvider.GetPropertyName(column);
     string fieldName = this.NameProvider.GetFieldName(column);
     classDeclaration.AddProperty(propertyName, fieldName, column.DataType, column.Nullable)
             .AddAttribute("Castle.ActiveRecord.PropertyAttribute")
             .AddQuotedArgument(column.Name);
 }
 /// <summary>
 /// Creates a property that is a foreign key within the current table that points to a primary key in another table.  These typically have BelongsTo attributes.
 /// </summary>
 /// <param name="classDeclaration">The class to which the property is added.</param>
 /// <param name="foreignKey">The foreign key the property represents.</param>
 /// <returns>The foreign key property that was added.</returns>
 protected override PropertyDeclaration CreateForeignKey(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey)
 {
     string fkname = this.NameProvider.GetPropertyName(foreignKey);
     string fkfieldname = this.NameProvider.GetFieldName(foreignKey);
     string fkdatatype = this.NameProvider.GetClassName(foreignKey.PrimaryKeyTable);
     PropertyDeclaration result = classDeclaration.AddProperty(fkname, fkfieldname, fkdatatype);
     result.AddAttribute("Castle.ActiveRecord.BelongsToAttribute").AddQuotedArgument(foreignKey.Name);
     return result;
 }
        private void AddField(ClassDeclaration c, FieldInfo f)
        {
            if (c == null)
            {
                throw new ArgumentNullException(null);
            }
            if (f == null)
            {
                throw new ArgumentNullException(null);
            }

            var fd = c.AddField(MapType(f.FieldType), f.Name);
            var p  = c.AddProperty(fd, true, true, false);

            // adding attributes
            if (TypeHelper.HasCustomAttribute(f, typeof(XmlAttributeAttribute)))
            {
                var    att      = (XmlAttributeAttribute)TypeHelper.GetFirstCustomAttribute(f, typeof(XmlAttributeAttribute));
                var    attr     = new CodeAttributeDeclaration("XmlAttribute");
                string attrName = att.AttributeName;
                if (att.AttributeName.Length == 0)
                {
                    attrName = f.Name;
                }
                var arg = new CodeAttributeArgument(
                    "AttributeName",
                    new CodePrimitiveExpression(attrName)
                    );
                attr.Arguments.Add(arg);
                p.CustomAttributes.Add(attr);
            }
            else
            {
                if (TypeHelper.HasCustomAttribute(f, typeof(XmlElementAttribute)))
                {
                    AttachXmlElementAttributes(p, f);
                }
                else
                {
                    var attr = new CodeAttributeDeclaration("XmlElement");
                    attr.Arguments.Add(
                        new CodeAttributeArgument(
                            "ElementName",
                            new CodePrimitiveExpression(f.Name)
                            )
                        );
                    p.CustomAttributes.Add(attr);
                }
            }
        }
        /// <summary>
        /// Creates a property that has many children that point to the primary key contained within this class.  Typically these will have HasMany attributes.
        /// </summary>
        /// <param name="classDeclaration">The class to which the property is added.</param>
        /// <param name="foreignKey">The foreign key in the table that references the primary key in this class.</param>
        /// <returns>The property that was added.</returns>
        protected override PropertyDeclaration CreateForeignKeyReference(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey)
        {
            if (foreignKey.Table.PrimaryKey == null)
                return null;

            string propertyName = this.NameProvider.GetListPropertyName(foreignKey);
            string fieldName = this.NameProvider.GetListFieldName(foreignKey);
            string typeParam = this.NameProvider.GetClassName(foreignKey.Table);
            CodeDomTypeReference genericList = new CodeDomTypeReference("System.Collections.Generic.List").AddTypeParameters(typeParam);
            PropertyDeclaration result = classDeclaration.AddProperty(propertyName, fieldName, "System.Collections.Generic.IList");
            result.InitializeField(genericList)
                .AddTypeParameter(typeParam)
                .AddAttribute("Castle.ActiveRecord.HasManyAttribute")
                .AddArgument("typeof(" + this.NameProvider.GetClassName(foreignKey.Table) + ")");

            return result;
        }
Esempio n. 7
0
        private void AddField(ClassDeclaration c, FieldInfo f)
        {
            if (c == null)
            {
                throw new ArgumentNullException("c");
            }
            if (f == null)
            {
                throw new ArgumentNullException("f");
            }

            FieldDeclaration    fd = c.AddField(MapType(f.FieldType), f.Name);
            PropertyDeclaration p  = c.AddProperty(fd, f.Name, true, true, false);

            // adding attributes
            if (TypeHelper.HasCustomAttribute(f, typeof(XmlAttributeAttribute)))
            {
                XmlAttributeAttribute att  = (XmlAttributeAttribute)TypeHelper.GetFirstCustomAttribute(f, typeof(XmlAttributeAttribute));
                AttributeDeclaration  attr = p.CustomAttributes.Add(typeof(XmlAttributeAttribute));
                string attrName            = att.AttributeName;
                if (att.AttributeName.Length == 0)
                {
                    attrName = f.Name;
                }
                AttributeArgument arg = attr.Arguments.Add(
                    "AttributeName",
                    Expr.Prim(attrName)
                    );
            }
            else
            {
                if (TypeHelper.HasCustomAttribute(f, typeof(XmlElementAttribute)))
                {
                    AttachXmlElementAttributes(p, f);
                }
                else
                {
                    AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlElementAttribute));
                    attr.Arguments.Add("ElementName", Expr.Prim(f.Name));
                }
            }
        }
Esempio n. 8
0
        public void Generate(System.Extensions.CodeDom.NamespaceDeclaration ns)
        {
            if (this.Name == null)
            {
                throw new InvalidOperationException("name not set");
            }

            // create class
            ClassDeclaration c = ns.AddClass(DecorateName(this.Name));

            this.Properties = new Hashtable();
            // add fields and properties
            foreach (DictionaryEntry de in this.Fields)
            {
                FieldDeclaration f = c.AddField(de.Value.ToString(), de.Key.ToString());

                PropertyDeclaration p = c.AddProperty(f, true, !ReadOnly, false);
                this.Properties.Add(de, p);
            }
        }
        public override void Generate()
        {
            if (this.Name == null)
            {
                throw new InvalidOperationException("name not set");
            }

            // create class
            ClassDeclaration c = this.NamespaceDeclaration.AddClass(this.DataName);

            this.Properties = new Hashtable();
            // add fields and properties
            foreach (DictionaryEntry de in this.Fields)
            {
                FieldDeclaration f = c.AddField(de.Value.ToString(), de.Key.ToString());

                PropertyDeclaration p = c.AddProperty(f, true, !ReadOnly, false);
                this.Properties.Add(de, p);
            }
            this.Compile();
        }
        protected override void CreateAssociationProperties(ClassDeclaration classDeclaration, TableSchema table)
        {
            if (classDeclaration == null || table == null || table.Associations.Count == 0)
                return;

            foreach (var assocTable in table.Associations)
            {
                Console.WriteLine("assocTable.Name=" + assocTable.Name);
                var otherTable = assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name != table.Name; }).PrimaryKeyTable;

                string propName = Inflector.Pluralize(this.NameProvider.GetPropertyName(otherTable.Name));
                string fieldName = Inflector.Pluralize(this.NameProvider.GetFieldName(otherTable.Name));
                var typeRef = new CodeDomTypeReference(typeof(IList<>).FullName, this.NameProvider.GetClassName(otherTable));
                var prop = classDeclaration.AddProperty(propName, fieldName, typeRef);
                prop.AddAttribute("Castle.ActiveRecord.HasAndBelongsToMany")
                    .AddArgument("typeof(" + this.NameProvider.GetClassName(otherTable) + ")")
                    .AddQuotedArgument("Table", assocTable.Name)
                    .AddQuotedArgument("ColumnKey", assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name == table.Name; }).Name)
                    .AddQuotedArgument("ColumnRef", assocTable.ForeignKeys.Single(fk => { return fk.PrimaryKeyTable.Name != table.Name; }).Name)
                    .AddArgument("Lazy = true");

            }
        }
        /// <summary>
        /// Adds a prrimary key property to the ClassDeclaration.
        /// </summary>
        /// <param name="classDeclaration">The ClassDeclaration instance the property is added to.</param>
        /// <param name="table">The database table the ClassDeclaration represents.</param>
        protected override PropertyDeclaration CreatePrimaryKeyProperty(ClassDeclaration classDeclaration, TableSchema table)
        {
            PrimaryKeyColumnSchema pk = table.PrimaryKey;
            if (pk == null)
                return null;

            string propertyName = "Id";

            string fieldName = this.NameProvider.GetFieldName(pk);
            PropertyDeclaration pkprop = classDeclaration.AddProperty(propertyName, fieldName, pk.DataType);
            AttributeDeclaration pkatrrib = pkprop.AddAttribute("Castle.ActiveRecord.PrimaryKeyAttribute");
            // TODO: Remove this shit code
            if (pk.IsIdentity)
                pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Identity");
            else
                pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Assigned");
            pkatrrib.AddQuotedArgument((pk.Name));
            return pkprop;
        }
 /// <summary>
 /// Creates a plain ol' property representing any column that is not a foreign key or primary key.
 /// </summary>
 /// <param name="classDeclaration">The class to which the property is added.</param>
 /// <param name="column">The column the property represents.</param>
 protected override void CreateNonKeyProperty(ClassDeclaration classDeclaration, ColumnSchema column)
 {
     string propertyName = this.NameProvider.GetPropertyName(column);
     string fieldName = this.NameProvider.GetFieldName(column);
     AttributeDeclaration attrib = classDeclaration.AddProperty(propertyName, fieldName, column.DataType, column.Nullable)
             .AddAttribute("Castle.ActiveRecord.PropertyAttribute")
             .AddQuotedArgument(column.Name);
     if (column.SqlType == System.Data.SqlDbType.Image)
         attrib.AddArgument("ColumnType=\"BinaryBlob\"");
     if (column.SqlType == System.Data.SqlDbType.Xml)
         attrib.AddArgument("ColumnType=\"StringClob\"");
 }
Esempio n. 13
0
        private void AddArrayField(ClassDeclaration c, FieldInfo f)
        {
            // create a collection
            ClassDeclaration col = c.AddClass(conformer.ToSingular(f.Name) + "Collection");

            col.Parent = new TypeTypeDeclaration(typeof(System.Collections.CollectionBase));

            // add serializable attribute
            col.CustomAttributes.Add(typeof(SerializableAttribute));

            // default constructor
            col.AddConstructor();
            // default indexer
            IndexerDeclaration index = col.AddIndexer(
                typeof(Object)
                );
            ParameterDeclaration pindex = index.Signature.Parameters.Add(typeof(int), "index", false);

            // getter
            index.Get.Return(
                Expr.This.Prop("List").Item(Expr.Arg(pindex))
                );
            index.Set.AddAssign(
                Expr.This.Prop("List").Item(Expr.Arg(pindex)),
                Expr.Value
                );

            // add object method
            MethodDeclaration    addObject  = col.AddMethod("Add");
            ParameterDeclaration paraObject = addObject.Signature.Parameters.Add(new TypeTypeDeclaration(typeof(Object)), "o", true);

            addObject.Body.Add(
                Expr.This.Prop("List").Method("Add").Invoke(paraObject)
                );

            // if typed array add methods for type
            if (f.FieldType.GetElementType() != typeof(Object))
            {
                AddCollectionMethods(
                    col,
                    MapType(f.FieldType.GetElementType()),
                    this.conformer.ToCapitalized(f.FieldType.GetElementType().Name),
                    "o"
                    );
            }

            foreach (XmlElementAttribute ea in f.GetCustomAttributes(typeof(XmlElementAttribute), true))
            {
                string name  = this.conformer.ToCapitalized(ea.ElementName);
                string pname = this.conformer.ToCamel(name);

                ITypeDeclaration mappedType = null;
                if (ea.Type != null)
                {
                    mappedType = MapType(ea.Type);
                }

                if (mappedType == null || mappedType == f.FieldType.GetElementType())
                {
                    continue;
                }

                AddCollectionMethods(col, mappedType, name, pname);
            }

            // add field
            FieldDeclaration fd = c.AddField(col, f.Name);

            fd.InitExpression = Expr.New(col);
            PropertyDeclaration p = c.AddProperty(fd, f.Name, true, true, false);

            // setting attributes
            // attach xml text
            if (TypeHelper.HasCustomAttribute(f, typeof(XmlTextAttribute)))
            {
                AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlTextAttribute));

                attr.Arguments.Add("Type", Expr.TypeOf(typeof(string)));

                // adding to string to collection
                MethodDeclaration tostring = col.AddMethod("ToString");
                tostring.Signature.ReturnType = new TypeTypeDeclaration(typeof(String));
                tostring.Attributes           = MemberAttributes.Public | MemberAttributes.Override;

                VariableDeclarationStatement sw = Stm.Var(typeof(StringWriter), "sw");
                sw.InitExpression = Expr.New(typeof(StringWriter));
                tostring.Body.Add(sw);
                ForEachStatement fe = Stm.ForEach(
                    typeof(string), "s", Expr.This.Prop("List"), false);

                fe.Body.Add(
                    Expr.Var(sw).Method("Write").Invoke(fe.Local)
                    );

                tostring.Body.Add(fe);
                tostring.Body.Return(Expr.Var(sw).Method("ToString").Invoke());
            }
            else if (TypeHelper.HasCustomAttribute(f, typeof(XmlArrayItemAttribute)))
            {
                // add xml array attribute
                AttributeDeclaration attr = p.CustomAttributes.Add(typeof(XmlArrayAttribute));
                attr.Arguments.Add("ElementName", Expr.Prim(f.Name));

                // add array item attribute
                XmlArrayItemAttribute arrayItem =
                    (XmlArrayItemAttribute)TypeHelper.GetFirstCustomAttribute(f, typeof(XmlArrayItemAttribute));

                attr = p.CustomAttributes.Add(typeof(XmlArrayItemAttribute));
                attr.Arguments.Add("ElementName", Expr.Prim(arrayItem.ElementName));
                //MMI:attr.Arguments.Add("Type",Expr.Prim(MapType(f.FieldType.GetElementType()).Name));
                attr.Arguments.Add("Type", Expr.TypeOf(MapType(f.FieldType.GetElementType())));

                if (arrayItem.Type != null)
                {
                    attr.Arguments.Add("DataType", Expr.Prim(arrayItem.DataType));
                }
                attr.Arguments.Add("IsNullable", Expr.Prim(arrayItem.IsNullable));
                if (this.Config.KeepNamespaces)
                {
                    attr.Arguments.Add("Namespace", Expr.Prim(arrayItem.Namespace));
                }
            }
            else
            {
                AttachXmlElementAttributes(p, f);
            }
        }
        /// <summary>
        /// Creates the column list.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <param name="classDecl">The class decl.</param>
        protected virtual void CreateColumnList(TableSchema table, ClassDeclaration classDecl)
        {
            ClassDeclaration cols = new ClassDeclaration(classDecl.Name + "Columns");
            var columns = table.Columns
                                            .GroupBy(c => { return c.Name; })
                                            .Select(g => { return g.ElementAt(0); });
            foreach (ColumnSchema column in columns)
            {
                string columnName = column.IsPrimaryKey ? "ID" : column.Name;
                FieldDeclaration field = new FieldDeclaration(columnName, typeof(string))
                                    .IsPublic()
                                    .InitializeTo("\"" + columnName + "\"");
                field.AddComment("This column is of type {0}{1}({2} in .NET) and can{3} be null.",
                    column.SqlType.ToString().ToLower(),
                    column.Length > 0 ? String.Format("({0})", column.Length) : "",
                    column.DataType.Name,
                    column.Nullable ? "" : "NOT");
                cols.AddField(field);

            }
            classDecl.AddClass(cols);

            FieldDeclaration columnsField = new FieldDeclaration("_columns", new CodeDomTypeReference(cols.Name)).IsStatic();
            columnsField.AddInitializer(new CodeDomTypeReference(cols.Name));
            PropertyDeclaration columnsProperty =
                new PropertyDeclaration("Columns", columnsField, new CodeDomTypeReference(cols.Name))
                .IsStatic().IsReadOnly();
            columnsProperty.AddComment("Gets an instance of the {0} class which contains all of the column names for {1}.", cols.Name, classDecl.Name);
            classDecl.AddProperty(columnsProperty);
        }
Esempio n. 15
0
 protected override PropertyDeclaration CreatePrimaryKeyProperty(ClassDeclaration classDeclaration, TableSchema table)
 {
     string propertyName = "ID";
     string fieldName = "_id";
     PropertyDeclaration result = classDeclaration.AddProperty(propertyName, fieldName, table.PrimaryKey.DataType, false);
     return result;
 }
        public ClassDeclaration AddClass(NamespaceDeclaration ns)
        {
            ClassDeclaration col = ns.AddClass(this.CollectionName);

            // set base class as CollectionBase
            col.Parent = new TypeTypeDeclaration(typeof(CollectionBase));

            // default constructor
            col.AddConstructor();

            // add indexer
            if (this.ItemGet || this.ItemSet)
            {
                IndexerDeclaration index = col.AddIndexer(
                    this.Type
                    );
                ParameterDeclaration pindex = index.Signature.Parameters.Add(typeof(int), "index", false);

                // get body
                if (this.ItemGet)
                {
                    index.Get.Return(
                        (Expr.This.Prop("List").Item(Expr.Arg(pindex)).Cast(this.Type)
                        )
                        );
                }
                // set body
                if (this.ItemSet)
                {
                    index.Set.Add(
                        Stm.Assign(
                            Expr.This.Prop("List").Item(Expr.Arg(pindex)),
                            Expr.Value
                            )
                        );
                }
            }

            string pname = ns.Conformer.ToCamel(this.Type.Name);

            // add method
            if (this.Add)
            {
                MethodDeclaration    add  = col.AddMethod("Add");
                ParameterDeclaration para = add.Signature.Parameters.Add(this.Type, pname, true);
                add.Body.Add(
                    Expr.This.Prop("List").Method("Add").Invoke(para)
                    );
            }

            if (this.AddRange)
            {
                MethodDeclaration    add  = col.AddMethod("AddRange");
                ParameterDeclaration para = add.Signature.Parameters.Add(col, pname, true);

                ForEachStatement fe = Stm.ForEach(
                    this.Type,
                    "item",
                    Expr.Arg(para),
                    false
                    );
                fe.Body.Add(
                    Expr.This.Prop("List").Method("Add").Invoke(fe.Local)
                    );

                add.Body.Add(fe);
            }

            // contains method
            if (this.Contains)
            {
                MethodDeclaration contains = col.AddMethod("Contains");
                contains.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
                ParameterDeclaration para = contains.Signature.Parameters.Add(this.Type, pname, true);
                contains.Body.Return(
                    Expr.This.Prop("List").Method("Contains").Invoke(para)
                    );
            }

            // remove method
            if (this.Remove)
            {
                MethodDeclaration    remove = col.AddMethod("Remove");
                ParameterDeclaration para   = remove.Signature.Parameters.Add(this.Type, pname, true);

                remove.Doc.Summary.AddText("Removes the first occurrence of a specific ParameterDeclaration from this ParameterDeclarationCollection.");

                remove.Body.Add(
                    Expr.This.Prop("List").Method("Remove").Invoke(para)
                    );
            }

            // insert
            if (this.Insert)
            {
                MethodDeclaration    insert = col.AddMethod("Insert");
                ParameterDeclaration index  = insert.Signature.Parameters.Add(typeof(int), "index", true);
                ParameterDeclaration para   = insert.Signature.Parameters.Add(this.Type, pname, true);
                insert.Body.Add(
                    Expr.This.Prop("List").Method("Insert").Invoke(index, para)
                    );
            }

            // indexof
            if (this.IndexOf)
            {
                MethodDeclaration    indexof = col.AddMethod("IndexOf");
                ParameterDeclaration para    = indexof.Signature.Parameters.Add(this.Type, pname, true);
                indexof.Signature.ReturnType = new TypeTypeDeclaration(typeof(int));
                indexof.Body.Return(
                    Expr.This.Prop("List").Method("IndexOf").Invoke(para)
                    );
            }

            if (this.Enumerator)
            {
                // create subclass
                ClassDeclaration en = col.AddClass("Enumerator");
                // add wrapped field
                FieldDeclaration wrapped = en.AddField(
                    typeof(IEnumerator), "wrapped"
                    );
                // add IEnumerator
                en.Interfaces.Add(typeof(IEnumerator));

                // add constructor
                ConstructorDeclaration cs         = en.AddConstructor();
                ParameterDeclaration   collection = cs.Signature.Parameters.Add(col, "collection", true);
                cs.Body.Add(
                    Stm.Assign(
                        Expr.This.Field(wrapped),
                        Expr.Arg(collection).Cast(typeof(CollectionBase)).Method("GetEnumerator").Invoke()
                        )
                    );

                // add current
                PropertyDeclaration current = en.AddProperty(this.Type, "Current");
                current.Get.Return(
                    (Expr.This.Field(wrapped).Prop("Current")).Cast(this.Type)
                    );

                // add explicit interface implementation
                PropertyDeclaration currentEn = en.AddProperty(typeof(Object), "Current");
                currentEn.Get.Return(Expr.This.Prop(current));
                currentEn.PrivateImplementationType = wrapped.Type;

                // add reset
                MethodDeclaration reset = en.AddMethod("Reset");
                reset.ImplementationTypes.Add(wrapped.Type);
                reset.Body.Add(Expr.This.Field(wrapped).Method("Reset").Invoke());

                // add movenext
                MethodDeclaration movenext = en.AddMethod("MoveNext");
                movenext.ImplementationTypes.Add(wrapped.Type);
                movenext.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
                movenext.Body.Return(Expr.This.Field(wrapped).Method("MoveNext").Invoke());

                // add get enuemrator
                MethodDeclaration geten = col.AddMethod("GetEnumerator");
                geten.Attributes |= MemberAttributes.New;
                geten.ImplementationTypes.Add(new TypeTypeDeclaration(typeof(IEnumerable)));
                geten.Signature.ReturnType = en;
                geten.Body.Return(Expr.New(en, Expr.This));
            }

            return(col);
        }
 /// <summary>
 /// Creates a property that maps to a table's primary key.
 /// </summary>
 /// <param name="cdecl">The ClassDeclaration that represents the database table.</param>
 /// <param name="table">The database table that contains the primary key we're mapping as a property.</param>
 protected override PropertyDeclaration CreatePrimaryKeyProperty(ClassDeclaration cdecl, TableSchema table)
 {
     PrimaryKeyColumnSchema pk = table.PrimaryKey;
     string propertyName = "ID";
     string fieldName = "_id"; // this.NameProvider.GetFieldName(pk);
     PropertyDeclaration pkprop = cdecl.AddProperty(propertyName, fieldName, pk.DataType);
     AttributeDeclaration pkatrrib = pkprop.AddAttribute("Castle.ActiveRecord.PrimaryKeyAttribute");
     // TODO: Remove this shit code
     if (pk.IsIdentity)
         pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Identity");
     else
     {
         if (pk.SqlType == System.Data.SqlDbType.UniqueIdentifier)
             pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.GuidComb");
         else
             pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Assigned");
     }
     pkatrrib.AddQuotedArgument((pk.Name));
     return pkprop;
 }
Esempio n. 18
0
        public override void Generate()
        {
            // generate data
            this.Data.NamespaceDeclaration = this.NamespaceDeclaration;
            this.Data.Generate();

            // generate the rest
            this.NamespaceDeclaration.Imports.Add("System.Data");

            // create class
            ClassDeclaration c = this.NamespaceDeclaration.AddClass(this.DataReaderName);

            // IDisposable
            c.Interfaces.Add(typeof(IDisposable));

            // add datareader field
            FieldDeclaration dr = c.AddField(typeof(IDataReader), "dr");

            // add data field
            FieldDeclaration data = c.AddField(
                this.Data.DataName
                , "data");

            data.InitExpression =
                Expr.New(data.Type);
            PropertyDeclaration datap = c.AddProperty(data, true, false, false);

            // foreach field values, add get property
            foreach (DictionaryEntry de in this.Data.Properties)
            {
                DictionaryEntry     dde = (DictionaryEntry)de.Key;
                PropertyDeclaration pd  = (PropertyDeclaration)de.Value;

                PropertyDeclaration pcd = c.AddProperty(pd.Type, pd.Name);
                pcd.Get.Return(
                    Expr.This.Field(data).Prop(pd)
                    );
            }


            // add constructor
            ConstructorDeclaration cs  = c.AddConstructor();
            ParameterDeclaration   drp = cs.Signature.Parameters.Add(dr.Type, "dr", false);

            cs.Body.Add(Stm.ThrowIfNull(drp));
            cs.Body.Add(
                Stm.Assign(
                    Expr.This.Field(dr),
                    Expr.Arg(drp)
                    )
                );

            // add close method
            MethodDeclaration close = c.AddMethod("Close");

            // if dr ==null return;
            close.Body.Add(
                Stm.IfNull(Expr.This.Field(dr), Stm.Return())
                );
            // dr.Close();
            close.Body.Add(
                Expr.This.Field(dr).Method("Close").Invoke()
                );
            // dr = null;
            close.Body.AddAssign(Expr.This.Field(dr), Expr.Null);
            // data = null
            close.Body.AddAssign(Expr.This.Field(data), Expr.Null);

            // add read method
            MethodDeclaration read = c.AddMethod("Read");

            read.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));

            // if (!dr.Read()){close and return)
            ConditionStatement ifnotread = Stm.IfIdentity(
                Expr.This.Field(dr).Method("Read").Invoke(),
                Expr.False,
                Stm.ToStm(Expr.This.Method(close).Invoke()),
                Stm.Return(Expr.False)
                );

            read.Body.Add(ifnotread);


            // foreach field values
            foreach (DictionaryEntry de in this.Data.Properties)
            {
                DictionaryEntry     dde = (DictionaryEntry)de.Key;
                PropertyDeclaration pd  = (PropertyDeclaration)de.Value;
                read.Body.AddAssign(
                    Expr.This.Field(data).Prop(pd),
                    (
                        Expr.This.Field(dr).Item(Expr.Prim(dde.Key.ToString()))
                    ).Cast(dde.Value.ToString())
                    );
            }
            // return true
            read.Body.Return(Expr.True);

            // add dispose method
            MethodDeclaration dispose = c.AddMethod("Dispose");

            dispose.ImplementationTypes.Add(typeof(IDisposable));

            // Close();
            dispose.Body.Add(
                Expr.This.Method(close).Invoke()
                );

            if (this.Enumerator)
            {
                AddEnumerator(c, data, close);
            }
        }
Esempio n. 19
0
        private void AddEnumerator(ClassDeclaration c, FieldDeclaration data, MethodDeclaration close)
        {
            c.Interfaces.Add(typeof(IEnumerable));
            // create subclass
            ClassDeclaration en = c.AddClass("Enumerator");
            // add wrapped field
            FieldDeclaration wrapped = en.AddField(
                c, "wrapped"
                );

            ITypeDeclaration enumeratorType = new TypeTypeDeclaration(typeof(IEnumerator));
            ITypeDeclaration disposableType = new TypeTypeDeclaration(typeof(IDisposable));

            // add IEnumerator
            en.Interfaces.Add(enumeratorType);
            en.Interfaces.Add(disposableType);

            // add constructor
            ConstructorDeclaration cs         = en.AddConstructor();
            ParameterDeclaration   collection = cs.Signature.Parameters.Add(c, "collection", true);

            cs.Body.AddAssign(Expr.This.Field(wrapped), Expr.Arg(collection));

            // add current
            PropertyDeclaration current = en.AddProperty(data.Type, "Current");

            current.Get.Return(
                Expr.This.Field(wrapped).Prop("Data")
                );

            // add explicit interface implementation
            PropertyDeclaration currentEn = en.AddProperty(typeof(Object), "Current");

            currentEn.Get.Return(Expr.This.Prop(current));
            currentEn.PrivateImplementationType = enumeratorType;

            // add reset
            MethodDeclaration reset = en.AddMethod("Reset");

            reset.ImplementationTypes.Add(wrapped.Type);
            reset.Body.Add(Stm.Throw(typeof(InvalidOperationException), Expr.Prim("Not supported")));

            // add movenext
            MethodDeclaration movenext = en.AddMethod("MoveNext");

            movenext.ImplementationTypes.Add(wrapped.Type);
            movenext.Signature.ReturnType = new TypeTypeDeclaration(typeof(bool));
            movenext.Body.Return(Expr.This.Field(wrapped).Method("Read").Invoke());

            // add dispose
            MethodDeclaration disposeEn = en.AddMethod("Dispose");

            disposeEn.ImplementationTypes.Add(disposableType);
            disposeEn.Body.Add(
                Expr.This.Field(wrapped).Method(close).Invoke()
                );
            disposeEn.Body.AddAssign(Expr.This.Field(wrapped), Expr.Null);


            // add get enuemrator
            MethodDeclaration geten = c.AddMethod("GetEnumerator");

            geten.Signature.ReturnType = en;
            geten.Body.Return(Expr.New(en, Expr.This));

            MethodDeclaration igeten = c.AddMethod("GetEnumerator");

            igeten.PrivateImplementationType = new TypeTypeDeclaration(typeof(IEnumerable));
            igeten.Signature.ReturnType      = new TypeTypeDeclaration(typeof(IEnumerator));
            igeten.Body.Return(Expr.This.Method("GetEnumerator").Invoke());
        }
        private void AddArrayField(ClassDeclaration c, FieldInfo f)
        {
            // create a collection
            var col = c.AddClass(this.conformer.ToCapitalized(f.Name) + "Collection");

            col.Parent = new TypeTypeDeclaration(typeof(System.Collections.CollectionBase));

            // default constructor
            col.AddConstructor();
            // default indexer
            var index = col.AddIndexer(
                typeof(Object)
                );
            var pindex = index.Signature.AddParam(typeof(int), "index", false);

/*			index.Get = new SnippetStatement();
 *                      index.Get.WriteLine("return this.List[{0}];",pindex.Name);
 *                      index.Set = new SnippetStatement();
 *                      index.Set.WriteLine("this.List[{0}]=value;",pindex.Name);
 */
            // add object method
            var addObject  = col.AddMethod("Add");
            var paraObject = addObject.Signature.AddParam(new TypeTypeDeclaration(typeof(Object)), "o", true);

            addObject.Body.Add(
                Expr.This.Prop("List").Method("Add").Invoke(paraObject)
                );

            // if typed array add methods for type
            if (f.FieldType.GetElementType() != typeof(Object))
            {
                AddCollectionMethods(
                    col,
                    MapType(f.FieldType.GetElementType()),
                    this.conformer.ToCapitalized(f.FieldType.GetElementType().Name),
                    "o"
                    );
            }

            foreach (XmlElementAttribute ea in f.GetCustomAttributes(typeof(XmlElementAttribute), true))
            {
                var name  = this.conformer.ToCapitalized(ea.ElementName);
                var pname = this.conformer.ToCamel(name);

                ITypeDeclaration mappedType = null;
                if (ea.Type != null)
                {
                    mappedType = MapType(ea.Type);
                }

                if (mappedType == null || f.FieldType.GetElementType() == (Type)mappedType)
                {
                    continue;
                }

                AddCollectionMethods(col, mappedType, name, pname);
            }

            // add field
            var fd = c.AddField(col, f.Name);

            fd.InitExpression = Expr.New(col);
            var p = c.AddProperty(fd, true, true, false);

            // setting attributes
            AttachXmlElementAttributes(p, f);
        }
        /// <summary>
        /// Creates a plain ol' property representing any column that is not a foreign key or primary key.
        /// </summary>
        /// <param name="classDeclaration">The class to which the property is added.</param>
        /// <param name="column">The column the property represents.</param>
        protected override void CreateNonKeyProperty(ClassDeclaration classDeclaration, ColumnSchema column)
        {
            string propertyName = this.NameProvider.GetPropertyName(column);
            string fieldName = this.NameProvider.GetFieldName(column);
            PropertyDeclaration prop = classDeclaration.AddProperty(propertyName, fieldName, column.DataType, column.Nullable);

            if (this.ConfigOptions.GenerateComments)
            {
                prop.AddComment("Gets or sets the {0} of the {1}.", this.NameProvider.GetPropertyName(column), classDeclaration.Name);
                if (column.Nullable)
                    prop.AddComment("This property is nullable.");
                else
                    prop.AddComment("This property cannot be null.");
                if (column.DataType == typeof(string))
                    prop.AddComment("The max length of this property is {0}.", column.Length);
            }

            AttributeDeclaration propAttrib = prop.AddAttribute("Castle.ActiveRecord.PropertyAttribute")
                    .AddQuotedArgument(column.Name)
                    .AddArgument("Length=" + (column.Length < 0 ? 0 : column.Length).ToString())
                    .AddArgument("NotNull=" + (column.Nullable == false).ToString().ToLower());

            if (column.SqlType == System.Data.SqlDbType.Image)
                propAttrib.AddArgument("ColumnType=\"BinaryBlob\"");

            if (column.SqlType == System.Data.SqlDbType.Xml)
                propAttrib.AddArgument("ColumnType=\"StringClob\"");
        }
        /// <summary>
        /// Adds a prrimary key property to the ClassDeclaration.
        /// </summary>
        /// <param name="classDeclaration">The ClassDeclaration instance the property is added to.</param>
        /// <param name="table">The database table the ClassDeclaration represents.</param>
        /// <returns></returns>
        protected override PropertyDeclaration CreatePrimaryKeyProperty(ClassDeclaration classDeclaration, TableSchema table)
        {
            PrimaryKeyColumnSchema pk = table.PrimaryKey;
            string propertyName = String.IsNullOrEmpty(this.ConfigOptions.StaticPrimaryKeyName) ? this.NameProvider.GetPropertyName(pk) : this.ConfigOptions.StaticPrimaryKeyName;
            string fieldName = String.IsNullOrEmpty(this.ConfigOptions.StaticPrimaryKeyName) ? this.NameProvider.GetFieldName(pk) : this.NameProvider.GetFieldName(this.ConfigOptions.StaticPrimaryKeyName);
            PropertyDeclaration pkprop = classDeclaration.AddProperty(propertyName, fieldName, pk.DataType);
            AttributeDeclaration pkatrrib = pkprop.AddAttribute("Castle.ActiveRecord.PrimaryKeyAttribute");

            if (pk.IsIdentity)
                pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Identity");
            else
            {
                if (pk.SqlType == System.Data.SqlDbType.UniqueIdentifier)
                    pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.GuidComb");
                else
                    pkatrrib.AddArgument("Castle.ActiveRecord.PrimaryKeyType.Assigned");
            }
            pkatrrib.AddQuotedArgument((pk.Name));
            if (this.ConfigOptions.GenerateComments)
            {
                pkprop.AddComment("This is the primary key and maps to {0}", table.PrimaryKey.Name);
            }
            return pkprop;
        }