private void DoFields(SupportClass.ListCollectionSupport fieldList, SupportClass.SetSupport imports, IDictionary class2classmap, StringWriter writer) { for (IEnumerator fields = fieldList.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GeneratedAsProperty) { string fieldScope = GetFieldScope(field, "scope-field", "private"); writer.WriteLine(" /// <summary>\n /// Holder for " + (field.Nullable && !field.Identifier ? "nullable " : string.Empty) + (field.Identifier ? "identifier" : "persistent") + " field " + field.FieldName + "\n /// </summary>"); writer.Write(" " + fieldScope + " " + field.FullyQualifiedTypeName + " " + field.fieldcase); if (field.GetMeta("default-value") != null) { writer.Write(" = " + field.GetMetaAsString("default-value")); } writer.WriteLine(';'); } writer.WriteLine(); } }
public virtual void AddCritera(ClassMapping criteriaClass, FieldProperty field, string condition) { string newCritera = criteriaClass.Name.ToLower() + "." + field.FieldName + condition + "?"; params_Renamed.Add(FinderRenderer.GetFieldAsObject(false, field)); criteria.Add(newCritera); criteriaParamTypes.Add(FinderRenderer.GetFieldAsHibernateType(false, field)); }
/// <summary> Gets the fieldAsObject attribute of the FinderRenderer object /// /// </summary> /// <returns> /// </returns> public static string GetFieldAsObject(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; if (type != null && type.Primitive && !type.Array) { string typeName = (String)primitiveToObject[type.Name]; typeName = "new " + typeName + "( "; typeName += (prependThis ? "this." : ""); return(typeName + field.FieldName + " )"); } return(field.FieldName); }
/// <summary> Return the hibernate type string for the given field /// /// </summary> /// <returns> /// </returns> public static string GetFieldAsHibernateType(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; string hibTypeString = (String)hibType[type.Name]; if ((object)hibTypeString != null) { return(hibTypeString); } else { return("Hibernate.OBJECT"); } }
/// <summary> Returns the true name for the given fields class name. By true name is /// that it will return the Proxy for the class name if the class was /// defined with a proxy attribute. /// /// If the Field has an <meta attribute="property-type"></meta> then that /// will overrule any other information. /// /// </summary> /// <param name="field">class name that we use to serach in class2classmap /// </param> /// <param name="class2classmap">a map from classname to classmappings /// </param> /// <returns> string return either name or the proxy name of the classmap /// </returns> public static string GetTrueTypeName(FieldProperty field, IDictionary class2classmap) { string name = (field.ClassType != null) ? field.ClassType.FullyQualifiedName : field.FullyQualifiedTypeName; if (field.GetMeta("property-type") != null) { name = field.GetMetaAsString("property-type"); } ClassMapping cmap = (ClassMapping)class2classmap[name]; if (cmap != null) { if ((Object)cmap.Proxy != null) { return(cmap.Proxy); } } return(name); }
/// <summary> Returns the true name for the given fields class name. By true name is /// that it will return the Proxy for the class name if the class was /// defined with a proxy attribute. /// /// If the Field has an <meta attribute="property-type"></meta> then that /// will overrule any other information. /// /// </summary> /// <param name="field">class name that we use to serach in class2classmap /// </param> /// <param name="class2classmap">a map from classname to classmappings /// </param> /// <returns> string return either name or the proxy name of the classmap /// </returns> public static string GetTrueTypeName(FieldProperty field, IDictionary class2classmap) { string name = (field.ClassType != null) ? field.ClassType.FullyQualifiedName : field.FullyQualifiedTypeName; if (field.GetMeta("property-type") != null) { name = field.GetMetaAsString("property-type"); } ClassMapping cmap = (ClassMapping) class2classmap[name]; if (cmap != null) { if ((Object) cmap.Proxy != null) { return cmap.Proxy; } } return name; }
public virtual string FieldsAsParameters(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping, IDictionary class2classmap) { StringBuilder buf = new StringBuilder(); bool first = true; for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();) { if (first) { first = false; } else { buf.Append(", "); } FieldProperty field = (FieldProperty)fields.Current; buf.Append(ShortenType(field.FullyQualifiedTypeName, classMapping.Imports) + " " + field.fieldcase); } return(buf.ToString()); }
public virtual string FieldsAsArguments(SupportClass.ListCollectionSupport fieldslist, ClassMapping classMapping, IDictionary class2classmap) { StringBuilder buf = new StringBuilder(); bool first = true; for (IEnumerator fields = fieldslist.GetEnumerator(); fields.MoveNext();) { if (first) { first = false; } else { buf.Append(", "); } FieldProperty field = (FieldProperty)fields.Current; buf.Append(field.fieldcase); } return(buf.ToString()); }
public virtual void DoToString(ClassMapping classMapping, StringWriter writer) { writer.WriteLine(" public override string ToString()"); writer.WriteLine(" {"); writer.WriteLine(" System.Text.StringBuilder sb = new System.Text.StringBuilder();"); for (IEnumerator fields = classMapping.AllFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; // If nothing is stated about id then include it in toString() if (field.Identifier && field.GetMeta("use-in-tostring") == null) { writer.WriteLine(" sb.AppendFormat(\"{0}={{0}} \", {0});", field.fieldcase); } else if (field.GetMetaAsBool("use-in-tostring")) { writer.WriteLine(" sb.AppendFormat(\"{0}={{0}} \", {0});", field.fieldcase); } } writer.WriteLine(" return sb.ToString();"); writer.WriteLine(" }"); writer.WriteLine(); }
private void AddFieldProperty(FieldProperty fieldProperty) { if (fieldProperty.ParentClass == null) { fields.Add(fieldProperty); } else { throw new SystemException("Field " + fieldProperty + " is already associated with a class: " + fieldProperty.ParentClass); } }
private void ExtractGenericArguments(FieldProperty field,string xmlName) { ClassName genericArgument; XmlNode n = field.XMLElement.SelectSingleNode("urn:one-to-many", CodeGenerator.nsmgr); if (n == null) n = field.XMLElement.SelectSingleNode("urn:many-to-many", CodeGenerator.nsmgr); if (null != n) { if (n.Attributes["class"] != null ) { genericArgument = GetFieldType(n.Attributes["class"].Value,false,false); AddImport(genericArgument); field.AddGenericArgument(genericArgument); } else log.Error("Missing class argument on collection:" + this.GeneratedName + " in " + xmlName + " " + field.FieldName); } else { //if there is an index element, add up do the generic definition... var key = field.XMLElement.SelectSingleNode("urn:index", CodeGenerator.nsmgr); if (null != key) { if (null != key.Attributes["type"]) { genericArgument = GetFieldType(key.Attributes["type"].Value, false, false); AddImport(genericArgument); field.AddGenericArgument(genericArgument); } else log.Error("Missing type argument on index:"+this.GeneratedName+" in "+xmlName+" "+field.FieldName); } //check for composite index... var compositeKey = field.XMLElement.SelectSingleNode("urn:composite-index", CodeGenerator.nsmgr); if (null != compositeKey) { if (null != compositeKey.Attributes["class"]) { genericArgument = GetFieldType(compositeKey.Attributes["class"].Value, false, false); AddImport(genericArgument); field.AddGenericArgument(genericArgument); } else log.Error("Missing class argument on composite-index:" + this.GeneratedName + " in " + xmlName + " " + field.FieldName); } // if it is a collection of value types... n = field.XMLElement.SelectSingleNode("urn:element", CodeGenerator.nsmgr); if (null != n ) { if (null != n.Attributes["type"]) { genericArgument = GetFieldType(n.Attributes["type"].Value, false, false); AddImport(genericArgument); field.AddGenericArgument(genericArgument); } else log.Error("Missing type argument on element:" + this.GeneratedName + " in " + xmlName + " " + field.FieldName); } n = field.XMLElement.SelectSingleNode("urn:composite-element", CodeGenerator.nsmgr); if (null != n) { if (null != n.Attributes["class"]) { genericArgument = GetFieldType(n.Attributes["class"].Value, false, false); AddImport(genericArgument); field.AddGenericArgument(genericArgument); } else log.Error("Missing type class on composite-element:" + this.GeneratedName + " in " + xmlName + " " + field.FieldName); } } }
protected internal virtual void InitWith(string classPackage, ClassName mySuperClass, Element classElement, bool component, MultiMap inheritedMeta) { IsComponent = component; string fullyQualifiedName = (classElement.Attributes[component ? "class" : "name"] == null ? string.Empty : classElement.Attributes[component ? "class" : "name"].Value); if (fullyQualifiedName.IndexOf('.') < 0 && (object) classPackage != null && classPackage.Trim().Length > 0) { fullyQualifiedName = classPackage + "." + fullyQualifiedName; } log.Debug("Processing mapping for class: " + fullyQualifiedName); MetaAttribs = MetaAttributeHelper.LoadAndMergeMetaMap(classElement, inheritedMeta); // class & package names name = new ClassName(fullyQualifiedName); if (GetMeta("generated-class") != null) { generatedName = new ClassName(GetMetaAsString("generated-class").Trim()); shouldBeAbstract_Renamed_Field = true; log.Warn("Generating " + generatedName + " instead of " + name); } else { generatedName = name; } XmlAttribute @abstract = classElement.Attributes["abstract"]; if (null != @abstract) { bool.TryParse(@abstract.Value, out shouldBeAbstract_Renamed_Field); } if (mySuperClass != null) { this.superClass = mySuperClass.Name; AddImport(mySuperClass); // can only be done AFTER this class gets its own name. } // get the properties defined for this class SupportClass.ListCollectionSupport propertyList = new SupportClass.ListCollectionSupport(); propertyList.AddAll(classElement.SelectNodes("urn:property", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:version", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:timestamp", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:key-property", CodeGenerator.nsmgr)); propertyList.AddAll(classElement.SelectNodes("urn:any", CodeGenerator.nsmgr)); // get the properties inside a <join/> mapping... var joins = classElement.SelectNodes("urn:join",CodeGenerator.nsmgr); foreach (XmlNode join in joins) { propertyList.AddAll( join.SelectNodes("urn:property", CodeGenerator.nsmgr)); } // get all many-to-one associations defined for the class SupportClass.ListCollectionSupport manyToOneList = new SupportClass.ListCollectionSupport(); manyToOneList.AddAll(classElement.SelectNodes("urn:many-to-one", CodeGenerator.nsmgr)); manyToOneList.AddAll(classElement.SelectNodes("urn:key-many-to-one", CodeGenerator.nsmgr)); XmlAttribute att = classElement.Attributes["proxy"]; if (att != null) { proxyClass = att.Value; if (proxyClass.IndexOf(",") > 0) proxyClass = proxyClass.Substring(0, proxyClass.IndexOf(",")); } Element id = classElement["id"]; if (id != null) { propertyList.Insert(0, id); // implementEquals(); } // composite id Element cmpid = classElement["composite-id"]; if (cmpid != null) { string cmpname = (cmpid.Attributes["name"] == null ? null : cmpid.Attributes["name"].Value); string cmpclass = (cmpid.Attributes["class"] == null ? null : cmpid.Attributes["class"].Value); if ((Object) cmpclass == null || cmpclass.Equals(string.Empty)) { //Embedded composite id //implementEquals(); propertyList.AddAll(0, cmpid.SelectNodes("urn:key-property", CodeGenerator.nsmgr)); manyToOneList.AddAll(0, cmpid.SelectNodes("urn:key-many-to-one", CodeGenerator.nsmgr)); if( manyToOneList.Count == 0 ) ImplementEquals(); } else { //Composite id class ClassMapping mapping = new ClassMapping(classPackage, cmpid, this, true, MetaAttribs); MultiMap metaForCompositeid = MetaAttributeHelper.LoadAndMergeMetaMap(cmpid, MetaAttribs); mapping.ImplementEquals(); ClassName classType = new ClassName(cmpclass); // add an import and field for this property AddImport(classType); if (cmpname != null) { FieldProperty cmpidfield = new FieldProperty(cmpid, this, cmpname, classType, false, true, false, metaForCompositeid); AddFieldProperty(cmpidfield); } else { //composite id with class MUST have a property name associated with... log.Error("Composite id with class MUST have a property name. In:"+mapping.Name); } object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } } // checked after the default sets of implement equals. if (GetMetaAsBool("implement-equals")) { ImplementEquals(); } // derive the class imports and fields from the properties for (IEnumerator properties = propertyList.GetEnumerator(); properties.MoveNext();) { Element property = (Element) properties.Current; MultiMap metaForProperty = MetaAttributeHelper.LoadAndMergeMetaMap(property, MetaAttribs); string propertyName = (property.Attributes["name"] == null ? null : property.Attributes["name"].Value); if ((Object) propertyName == null || propertyName.Trim().Equals(string.Empty)) { continue; //since an id doesn't necessarily need a name } // ensure that the type is specified string type = (property.Attributes["type"] == null ? null : property.Attributes["type"].Value); if ((Object) type == null && cmpid != null) { // for composite-keys type = (property.Attributes["class"] == null ? null : property.Attributes["class"].Value); } if ("timestamp".Equals(property.LocalName)) { type = "System.DateTime"; } if ("any".Equals(property.LocalName)) { type = "System.Object"; } if ((Object) type == null || type.Trim().Equals(string.Empty)) { if (property == id) { Element generator = property["generator"]; string generatorClass = generator.Attributes["class"] == null ? string.Empty : generator.Attributes["class"].Value; switch (generatorClass) { case "uuid.hex": type = "String"; break; case "guid": case "guid.native": case "guid.comb": type = "Guid"; break; default: type = "Int32"; break; } } else type = "String"; log.Warn("property \"" + propertyName + "\" in class " + Name + " is missing a type attribute, guessing " + type); } // handle in a different way id and properties... // ids may be generated and may need to be of object type in order to support // the unsaved-value "null" value. // Properties may be nullable (ids may not) if (property == id) { Element generator = property["generator"]; string unsavedValue = (property.Attributes["unsaved-value"] == null ? null : property.Attributes["unsaved-value"].Value); bool mustBeNullable = ((Object) unsavedValue != null && unsavedValue.Equals("null")); bool generated = !(generator.Attributes["class"] == null ? string.Empty : generator.Attributes["class"].Value).Equals("assigned"); ClassName rtype = GetFieldType(type, mustBeNullable, false); AddImport(rtype); FieldProperty idField = new FieldProperty(property, this, propertyName, rtype, false, true, generated, metaForProperty); AddFieldProperty(idField); } else { string notnull = (property.Attributes["not-null"] == null ? null : property.Attributes["not-null"].Value); // if not-null property is missing lets see if it has been // defined at column level if ((Object) notnull == null) { Element column = property["column"]; if (column != null) notnull = (column.Attributes["not-null"] == null ? null : column.Attributes["not-null"].Value); } bool nullable = ((Object) notnull == null || notnull.Equals("false")); bool key = property.LocalName.StartsWith("key-"); //a composite id property ClassName t = GetFieldType(type); AddImport(t); FieldProperty stdField = new FieldProperty(property, this, propertyName, t, nullable && !key, key, false, metaForProperty); AddFieldProperty(stdField); } } // one to ones for (IEnumerator onetoones = classElement.SelectNodes("urn:one-to-one", CodeGenerator.nsmgr).GetEnumerator(); onetoones.MoveNext();) { Element onetoone = (Element) onetoones.Current; MultiMap metaForOneToOne = MetaAttributeHelper.LoadAndMergeMetaMap(onetoone, MetaAttribs); string propertyName = (onetoone.Attributes["name"] == null ? string.Empty : onetoone.Attributes["name"].Value); // ensure that the class is specified string clazz = (onetoone.Attributes["class"] == null ? string.Empty : onetoone.Attributes["class"].Value); if (clazz.Length == 0) { log.Warn("one-to-one \"" + name + "\" in class " + Name + " is missing a class attribute"); continue; } ClassName cn = GetFieldType(clazz); AddImport(cn); FieldProperty fm = new FieldProperty(onetoone, this, propertyName, cn, true, metaForOneToOne); AddFieldProperty(fm); } // many to ones - TODO: consolidate with code above for (IEnumerator manytoOnes = manyToOneList.GetEnumerator(); manytoOnes.MoveNext();) { Element manyToOne = (Element) manytoOnes.Current; MultiMap metaForManyToOne = MetaAttributeHelper.LoadAndMergeMetaMap(manyToOne, MetaAttribs); string propertyName = (manyToOne.Attributes["name"] == null ? string.Empty : manyToOne.Attributes["name"].Value); // ensure that the type is specified string type = (manyToOne.Attributes["class"] == null ? string.Empty : manyToOne.Attributes["class"].Value); if (type.Length == 0) { log.Warn("many-to-one \"" + propertyName + "\" in class " + Name + " is missing a class attribute"); continue; } ClassName classType = new ClassName(type); // is it nullable? string notnull = (manyToOne.Attributes["not-null"] == null ? null : manyToOne.Attributes["not-null"].Value); bool nullable = ((Object) notnull == null || notnull.Equals("false")); bool key = manyToOne.LocalName.StartsWith("key-"); //a composite id property // add an import and field for this property AddImport(classType); FieldProperty f = new FieldProperty(manyToOne, this, propertyName, classType, nullable && !key, key, false, metaForManyToOne); AddFieldProperty(f); } // collections DoCollections(classPackage, classElement, "list", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoCollections(classPackage, classElement, "map", "System.Collections.Generic.IDictionary", "System.Collections.Generic.Dictionary", MetaAttribs); DoCollections(classPackage, classElement, "set", "Iesi.Collections.Generic.ISet", "Iesi.Collections.Generic.HashedSet", MetaAttribs); DoCollections(classPackage, classElement, "bag", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoCollections(classPackage, classElement, "idbag", "System.Collections.Generic.IList", "System.Collections.Generic.List", MetaAttribs); DoArrays(classElement, "array", MetaAttribs); DoArrays(classElement, "primitive-array", MetaAttribs); //dynamic-component foreach (Element dync in classElement.SelectNodes("urn:dynamic-component", CodeGenerator.nsmgr)) { MultiMap metaForDync = MetaAttributeHelper.LoadAndMergeMetaMap(dync, MetaAttribs); string propertyName = (dync.Attributes["name"] == null ? string.Empty : dync.Attributes["name"].Value); FieldProperty dynfield = new FieldProperty(dync, this, propertyName, new ClassName("System.Collections.Generic.IDictionary"), false, metaForDync); dynfield.AddGenericArgument(new ClassName("System.String")); dynfield.AddGenericArgument(new ClassName("System.Object")); AddImport("System.Collections.Generic.IDictionary"); AddFieldProperty(dynfield); } //components for (IEnumerator iter = classElement.SelectNodes("urn:component", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element cmpe = (Element) iter.Current; MultiMap metaForComponent = MetaAttributeHelper.LoadAndMergeMetaMap(cmpe, MetaAttribs); string cmpname = (cmpe.Attributes["name"] == null ? null : cmpe.Attributes["name"].Value); string cmpclass = (cmpe.Attributes["class"] == null ? null : cmpe.Attributes["class"].Value); if ((Object) cmpclass == null || cmpclass.Equals(string.Empty)) { log.Warn("component \"" + cmpname + "\" in class " + Name + " does not specify a class"); continue; } ClassMapping mapping = new ClassMapping(classPackage, cmpe, this, true, MetaAttribs); ClassName classType = new ClassName(cmpclass); // add an import and field for this property AddImport(classType); FieldProperty ff = new FieldProperty(cmpe, this, cmpname, classType, false, metaForComponent); AddFieldProperty(ff); object tempObject2; tempObject2 = mapping; components[mapping.FullyQualifiedName] = tempObject2; } // subclasses (done last so they can access this superclass for info) for (IEnumerator iter = classElement.SelectNodes("urn:subclass", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element subclass = (Element) iter.Current; ClassMapping subclassMapping = new ClassMapping(classPackage, this, name, this, subclass, MetaAttribs); AddSubClass(subclassMapping); } for (IEnumerator iter = classElement.SelectNodes("urn:joined-subclass", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { Element subclass = (Element) iter.Current; ClassMapping subclassMapping = new ClassMapping(classPackage, this, name, this, subclass, MetaAttribs); AddSubClass(subclassMapping); } ValidateMetaAttributes(); }
public virtual string GetFieldScope(FieldProperty field, string localScopeName, string defaultScope) { return(field.GetScope(localScopeName, defaultScope)); }
public virtual void DoConstructors(string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StringWriter writer) { // full constructor SupportClass.ListCollectionSupport allFieldsForFullConstructor = classMapping.AllFieldsForFullConstructor; writer.WriteLine(" /// <summary>\n /// full constructor\n /// </summary>"); string fullCons = " public " + savedToClass + StringHelper.OpenParen; fullCons += languageTool.FieldsAsParameters(allFieldsForFullConstructor, classMapping, class2classmap); writer.Write(fullCons + ")"); //invoke super to initialize superclass... SupportClass.ListCollectionSupport supersConstructorFields = classMapping.FieldsForSupersFullConstructor; if (!(supersConstructorFields.Count == 0)) { writer.Write(" : base("); bool first = true; for (IEnumerator fields = supersConstructorFields.GetEnumerator(); fields.MoveNext();) { if (first) { first = false; } else { writer.Write(", "); } FieldProperty field = (FieldProperty)fields.Current; writer.Write(field.FieldName); } writer.Write(")"); } writer.WriteLine(); writer.WriteLine(" {"); // initialisation of localfields for (IEnumerator fields = classMapping.LocalFieldsForFullConstructor.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GeneratedAsProperty) { writer.WriteLine(" this." + field.FieldName + " = " + field.FieldName + ";"); } } writer.WriteLine(" }"); writer.WriteLine(); // no args constructor (if fullconstructor had any arguments!) if (allFieldsForFullConstructor.Count > 0) { writer.WriteLine(" /// <summary>\n /// default constructor\n /// </summary>"); writer.WriteLine(" public " + savedToClass + "() {"); writer.WriteLine(" }"); writer.WriteLine(); } // minimal constructor (only if the fullconstructor had any arguments) if ((allFieldsForFullConstructor.Count > 0) && classMapping.NeedsMinimalConstructor()) { SupportClass.ListCollectionSupport allFieldsForMinimalConstructor = classMapping.AllFieldsForMinimalConstructor; writer.WriteLine(" /// <summary>\n /// minimal constructor\n /// </summary>"); string minCons = " public " + savedToClass + "("; bool first = true; for (IEnumerator fields = allFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();) { if (first) { first = false; } else { minCons = minCons + ", "; } FieldProperty field = (FieldProperty)fields.Current; minCons = minCons + LanguageTool.ShortenType(LanguageTool.GetTrueTypeName(field, class2classmap), classMapping.Imports) + " " + field.FieldName; } writer.Write(minCons + ")"); // invoke super to initialize superclass... SupportClass.ListCollectionSupport supersMinConstructorFields = classMapping.FieldsForSupersMinimalConstructor; if (!(supersMinConstructorFields.Count == 0)) { writer.Write(" : base("); bool first2 = true; for (IEnumerator fields = supersMinConstructorFields.GetEnumerator(); fields.MoveNext();) { if (first2) { first2 = false; } else { writer.Write(StringHelper.CommaSpace); } FieldProperty field = (FieldProperty)fields.Current; writer.Write(field.FieldName); } writer.Write(")"); } writer.WriteLine(); writer.WriteLine(" {"); // initialisation of localfields for (IEnumerator fields = classMapping.LocalFieldsForMinimalConstructor.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GeneratedAsProperty) { writer.WriteLine(" this." + field.FieldName + " = " + field.FieldName + ";"); } } writer.WriteLine(" }"); writer.WriteLine(); } }
public virtual void DoEqualsAndHashCode(string savedToClass, ClassMapping classMapping, StringWriter writer) { if (classMapping.MustImplementEquals()) { writer.WriteLine(" public override bool Equals(object obj) {"); writer.WriteLine(" if(this == obj) return true;"); writer.WriteLine(" if((obj == null) || (obj.GetType() != this.GetType())) return false;"); writer.WriteLine(" " + savedToClass + " castObj = (" + savedToClass + ") obj;"); writer.Write(" return (castObj != null) "); int usedFields = 0; SupportClass.ListCollectionSupport idFields = new SupportClass.ListCollectionSupport(); for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GetMetaAsBool("use-in-equals")) { writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")"); usedFields++; } if (field.Identifier) { idFields.Add(field); } } if (usedFields == 0) { log.Warn("No properties has been marked as being used in equals/hashcode for " + classMapping.Name + ". Using object identifier which is RARELY safe to use! See http://hibernate.org/109.html"); for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; writer.Write(" && (this." + field.fieldcase + " == castObj." + field.fieldcase + ")"); } } writer.WriteLine(";"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(" public override int GetHashCode() {"); writer.WriteLine(" int hash = 69;"); //writer.Write(" return"); for (IEnumerator fields = classMapping.Fields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GetMetaAsBool("use-in-equals")) { //writer.Write("\n " + field.FieldName + ".GetHashCode() ^"); writer.WriteLine(" hash = 31 * hash + " + field.fieldcase + ".GetHashCode();"); } } if (usedFields == 0) { for (IEnumerator fields = idFields.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; //writer.Write("\n " + field.FieldName + ".GetHashCode() ^"); writer.WriteLine(" hash = 31 * hash + " + field.fieldcase + ".GetHashCode();"); } } //writer.WriteLine(" 0;"); writer.WriteLine(" return hash;"); writer.WriteLine(" }"); writer.WriteLine(); } }
/// <summary> Gets the fieldAsObject attribute of the FinderRenderer object /// /// </summary> /// <returns> /// </returns> public static string GetFieldAsObject(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; if (type != null && type.Primitive && !type.Array) { string typeName = (String) primitiveToObject[type.Name]; typeName = "new " + typeName + "( "; typeName += (prependThis ? "this." : ""); return typeName + field.FieldName + " )"; } return field.FieldName; }
private void DoArrays(Element classElement, string type, MultiMap inheritedMeta) { for (IEnumerator arrays = classElement.SelectNodes("urn:" + type, CodeGenerator.nsmgr).GetEnumerator(); arrays.MoveNext();) { Element array = (Element) arrays.Current; MultiMap metaForArray = MetaAttributeHelper.LoadAndMergeMetaMap(array, inheritedMeta); string role = array.Attributes["name"].Value; string elementClass = (array.Attributes["element-class"] == null ? null : array.Attributes["element-class"].Value); if ((Object) elementClass == null) { Element elt = array["element"]; if (elt == null) elt = array["one-to-many"]; if (elt == null) elt = array["many-to-many"]; if (elt == null) elt = array["composite-element"]; if (elt == null) { log.Warn("skipping collection with subcollections"); continue; } elementClass = (elt.Attributes["type"] == null ? null : elt.Attributes["type"].Value); if ((Object) elementClass == null) elementClass = (elt.Attributes["class"] == null ? string.Empty : elt.Attributes["class"].Value); } ClassName cn = GetFieldType(elementClass, false, true); AddImport(cn); FieldProperty af = new FieldProperty(array, this, role, cn, false, metaForArray); AddFieldProperty(af); } }
private void DoCollections(string classPackage, Element classElement, string xmlName, string interfaceClass, string implementingClass, MultiMap inheritedMeta) { string originalInterface = interfaceClass; string originalImplementation = implementingClass; for (IEnumerator collections = classElement.SelectNodes("urn:" + xmlName, CodeGenerator.nsmgr).GetEnumerator(); collections.MoveNext();) { Element collection = (Element) collections.Current; MultiMap metaForCollection = MetaAttributeHelper.LoadAndMergeMetaMap(collection, inheritedMeta); string propertyName = (collection.Attributes["name"] == null ? string.Empty : collection.Attributes["name"].Value); //TODO: map and set in .net // Small hack to switch over to sortedSet/sortedMap if sort is specified. (that is sort != unsorted) string sortValue = (collection.Attributes["sort"] == null ? null : collection.Attributes["sort"].Value); if ((object) sortValue != null && !"unsorted".Equals(sortValue) && !"".Equals(sortValue.Trim())) { if ("map".Equals(xmlName)) { interfaceClass = typeof(IDictionary<,>).FullName; implementingClass = typeof(IDictionary<,>).FullName; } else if ("set".Equals(xmlName)) { interfaceClass = typeof(ISet<>).FullName; implementingClass = typeof(ISet<>).FullName; } } else { interfaceClass = originalInterface; implementingClass = originalImplementation; } ClassName interfaceClassName = new ClassName(interfaceClass); ClassName implementationClassName = new ClassName(implementingClass); // add an import and field for this collection AddImport(interfaceClassName); AddImport(implementationClassName); ClassName foreignClass = null; SupportClass.SetSupport foreignKeys = null; // Collect bidirectional data if (collection.SelectNodes("urn:one-to-many", CodeGenerator.nsmgr).Count != 0) { foreignClass = new ClassName(collection["one-to-many"].Attributes["class"].Value); } else if (collection.SelectNodes("urn:many-to-many", CodeGenerator.nsmgr).Count != 0) { foreignClass = new ClassName(collection["many-to-many"].Attributes["class"].Value); } // Do the foreign keys and import if (foreignClass != null) { // Collect the keys foreignKeys = new SupportClass.HashSetSupport(); if (collection["key"].Attributes["column"] != null) foreignKeys.Add(collection["key"].Attributes["column"].Value); for (IEnumerator iter = collection["key"].SelectNodes("urn:column", CodeGenerator.nsmgr).GetEnumerator(); iter.MoveNext();) { if (((Element) iter.Current).Attributes["name"] != null) foreignKeys.Add(((Element) iter.Current).Attributes["name"].Value); } AddImport(foreignClass); } FieldProperty cf = new FieldProperty(collection, this, propertyName, interfaceClassName, implementationClassName, false, foreignClass, foreignKeys, metaForCollection); AddFieldProperty(cf); if (collection.SelectNodes("urn:composite-element", CodeGenerator.nsmgr).Count != 0) { for ( IEnumerator compositeElements = collection.SelectNodes("urn:composite-element", CodeGenerator.nsmgr).GetEnumerator(); compositeElements.MoveNext();) { Element compositeElement = (Element) compositeElements.Current; string compClass = compositeElement.Attributes["class"].Value; try { ClassMapping mapping = new ClassMapping(classPackage, compositeElement, this, true, MetaAttribs); ClassName classType = new ClassName(compClass); // add an import and field for this property AddImport(classType); object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } catch (Exception e) { log.Error("Error building composite-element " + compClass, e); } } } if (collection.SelectNodes("urn:composite-index", CodeGenerator.nsmgr).Count != 0) { for ( IEnumerator compositeElements = collection.SelectNodes("urn:composite-index", CodeGenerator.nsmgr).GetEnumerator(); compositeElements.MoveNext(); ) { Element compositeElement = (Element)compositeElements.Current; string compClass = compositeElement.Attributes["class"].Value; try { ClassMapping mapping = new ClassMapping(classPackage, compositeElement, this, true, MetaAttribs); mapping.ImplementEquals(); ClassName classType = new ClassName(compClass); // add an import and field for this property AddImport(classType); object tempObject; tempObject = mapping; components[mapping.FullyQualifiedName] = tempObject; } catch (Exception e) { log.Error("Error building composite-index " + compClass, e); } } } ExtractGenericArguments(cf,xmlName); } }
private int DoFields(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer, string vetoSupport, string changeSupport, int fieldTypes, SupportClass.ListCollectionSupport fieldz) { // field accessors for (IEnumerator fields = fieldz.GetEnumerator(); fields.MoveNext();) { FieldProperty field = (FieldProperty)fields.Current; if (field.GeneratedAsProperty) { // getter string getAccessScope = GetFieldScope(field, "scope-get", "public"); if (field.GetMeta("field-description") != null) { //writer.WriteLine(" /** \n" + languageTool.toJavaDoc(field.getMetaAsString("field-description"), 4) + " */"); writer.WriteLine(" /// <summary>\n" + languageTool.ToJavaDoc(field.GetMetaAsString("field-description"), 4) + "\n /// </summary>"); } writer.Write(" " + getAccessScope + " virtual " + field.FullyQualifiedTypeName + " " + field.Propcase); if (classMapping.Interface) { writer.WriteLine(";"); } else { writer.WriteLine(); writer.WriteLine(" {"); writer.WriteLine(" get { return this." + field.fieldcase + "; }"); //writer.WriteLine(" {"); //writer.WriteLine(" return this." + field.FieldName + ";"); //writer.WriteLine(" }"); } // setter int fieldType = 0; if (field.GetMeta("beans-property-type") != null) { string beansPropertyType = field.GetMetaAsString("beans-property-type").Trim().ToLower(); if (beansPropertyType.Equals("constraint")) { fieldTypes = (fieldTypes | CONSTRAINT); fieldType = CONSTRAINT; } else if (beansPropertyType.Equals("bound")) { fieldTypes = (fieldTypes | BOUND); fieldType = BOUND; } } string setAccessScope = GetFieldScope(field, "scope-set", "public"); writer.Write(" set"); writer.Write((fieldType & CONSTRAINT) == CONSTRAINT ? " throws PropertyVetoException " : ""); if (classMapping.Interface) { writer.WriteLine(";"); } else { writer.WriteLine(); writer.WriteLine(" {"); if ((fieldType & CONSTRAINT) == CONSTRAINT || (fieldType & BOUND) == BOUND) { writer.WriteLine(" object oldValue = " + GetFieldAsObject(true, field) + ";"); } if ((fieldType & CONSTRAINT) == CONSTRAINT) { writer.WriteLine(" " + vetoSupport + ".fireVetoableChange(\"" + field.fieldcase + "\","); writer.WriteLine(" oldValue,"); writer.WriteLine(" " + GetFieldAsObject(false, field) + ");"); } writer.WriteLine(" this." + field.fieldcase + " = value;"); if ((fieldType & BOUND) == BOUND) { writer.WriteLine(" " + changeSupport + ".firePropertyChange(\"" + field.fieldcase + "\","); writer.WriteLine(" oldValue,"); writer.WriteLine(" " + GetFieldAsObject(false, field) + ");"); } writer.WriteLine(" }"); } writer.WriteLine(" }"); writer.WriteLine(); // add/remove'rs (commented out for now) /* * if(field.getForeignClass()!=null) { * ClassName foreignClass = field.getForeignClass(); * * string trueforeign = getTrueTypeName(foreignClass, class2classmap); * classMapping.addImport(trueforeign); * * // Try to identify the matching set method on the child. * ClassMapping forignMap = (ClassMapping) class2classmap.get(foreignClass.getFullyQualifiedName()); * * if(forignMap!=null) { * Iterator foreignFields = forignMap.getFields().iterator(); * while (foreignFields.hasNext()) { * Field ffield = (Field) foreignFields.next(); * if(ffield.isIdentifier()) { * log.Debug("Trying to match " + ffield.getName() + " with " + field.getForeignKeys()); * } * } * * } else { * log.Error("Could not find foreign class's mapping - cannot provide bidirectional setters!"); * } * * string addAccessScope = getFieldScope(field, "scope", "scope-add"); * writer.println(" " + setAccessScope + " void add" + field.getAsSuffix() + StringHelper.OPEN + shortenType(trueforeign, classMapping.getImports()) + " a" + field.getName() + ") {"); * writer.println(" this." + getterType + field.getAsSuffix() + "().add(a" + field.getName() + ");"); * writer.println(" a" + field.getName() + ".setXXX(this);"); * writer.println(" }"); * writer.println(); * * * } */ } } return(fieldTypes); }
/// <summary> Return the hibernate type string for the given field /// /// </summary> /// <returns> /// </returns> public static string GetFieldAsHibernateType(bool prependThis, FieldProperty field) { ClassName type = field.ClassType; string hibTypeString = (String) hibType[type.Name]; if ((object) hibTypeString != null) { return hibTypeString; } else { return "Hibernate.OBJECT"; } }
/// <summary> Create finders for properties that have the <meta atttribute="finder-method"> /// finderName</meta> block defined. Also, create a findAll(Session) method. /// /// </summary> public virtual void DoFinders(ClassMapping classMapping, IDictionary class2classmap, StringWriter writer) { // Find out of there is a system wide way to get sessions defined string sessionMethod = classMapping.GetMetaAsString("session-method").Trim(); // fields foreach (FieldProperty field in classMapping.Fields) { if (field.GetMeta(MT_FINDERMETHOD) != null) { string finderName = field.GetMetaAsString(MT_FINDERMETHOD); if ("".Equals(sessionMethod)) { // Make the method signature require a session to be passed in writer.WriteLine(" public static List " + finderName + "(Session session, " + LanguageTool.GetTrueTypeName(field, class2classmap) + " " + field.FieldName + ") " + "throws SQLException, HibernateException {"); } else { // Use the session method to get the session to execute the query writer.WriteLine(" public static List " + finderName + "(" + LanguageTool.GetTrueTypeName(field, class2classmap) + " " + field.FieldName + ") " + "throws SQLException, HibernateException {"); writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"from " + classMapping.FullyQualifiedName + " as " + classMapping.Name.ToLower() + " where " + classMapping.Name.ToLower() + "." + field.FieldName + "=?\", " + GetFieldAsObject(false, field) + ", " + GetFieldAsHibernateType(false, field) + ");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); } else if (field.GetMeta(MT_FOREIGNFINDERMETHOD) != null) { string finderName = field.GetMetaAsString(MT_FOREIGNFINDERMETHOD); string fieldName = field.GetMetaAsString(MT_FOREIGNFINDERFIELD); string joinFieldName = field.GetMetaAsString(MT_FOREIGNJOINFIELD); // Build the query QueryBuilder qb = new QueryBuilder(); qb.LocalClass = classMapping; qb.SetForeignClass(field.ForeignClass, class2classmap, joinFieldName); ClassMapping foreignClass = (ClassMapping)class2classmap[field.ForeignClass.FullyQualifiedName]; if (foreignClass == null) { // Can't find the class, return log.Error("Could not find the class " + field.ForeignClass.Name); return; } FieldProperty foreignField = null; foreach (FieldProperty f in foreignClass.Fields) { if (f.FieldName.Equals(fieldName)) { foreignField = f; } } if (foreignField != null) { qb.AddCritera(foreignClass, foreignField, "="); } else { // Can't find the field, return log.Error("Could not find the field " + fieldName + " that was supposed to be in class " + field.ForeignClass.Name); return; } MethodSignatureBuilder msb = new MethodSignatureBuilder(finderName, "List", "public static"); if ("".Equals(sessionMethod)) { // Make the method signature require a session to be passed in msb.AddParameter("Session session"); /* * writer.println(" public static List " + finderName + * "(Session session, " + getTrueTypeName(foreignField, class2classmap) + " " + foreignField.getName() + ") " + "throws SQLException, HibernateException {");*/ } else { // Use the session method to get the session to execute the query /* * writer.println(" public static List " + finderName + * "(" + getTrueTypeName(foreignField, class2classmap) + " " + foreignField.getName() + ") " + "throws SQLException, HibernateException {"); + writer.println(" Session session = " + sessionMethod);*/ } // Always need the object we're basing the query on msb.AddParameter(classMapping.Name + " " + classMapping.Name.ToLower()); // And the foreign class field msb.AddParameter(LanguageTool.GetTrueTypeName(foreignField, class2classmap) + " " + foreignField.FieldName); msb.AddThrows("SQLException"); msb.AddThrows("HibernateException"); writer.WriteLine(" " + msb.BuildMethodSignature()); if (!"".Equals(sessionMethod)) { writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"" + qb.Query + "\", " + qb.ParamsAsString + ", " + qb.ParamTypesAsString + ");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); } } // Create the findAll() method if ("".Equals(sessionMethod)) { writer.WriteLine(" public static List findAll" + "(Session session) " + "throws SQLException, HibernateException {"); } else { writer.WriteLine(" public static List findAll() " + "throws SQLException, HibernateException {"); writer.WriteLine(" Session session = " + sessionMethod); } writer.WriteLine(" List finds = session.find(\"from " + classMapping.Name + " in class " + classMapping.PackageName + "." + classMapping.Name + "\");"); writer.WriteLine(" return finds;"); writer.WriteLine(" }"); writer.WriteLine(); }
public virtual string GetFieldScope(FieldProperty field, string localScopeName, string defaultScope) { return field.GetScope(localScopeName, defaultScope); }