/// <summary> /// Load this Simple type from the .NET schema /// </summary> /// <param name="type">The type to load</param> public void Load(System.Xml.Schema.XmlSchemaSimpleType type) { if (type == null) { return; } this.Name = type.Name; this.Namespace = type.QualifiedName != null ? type.QualifiedName.Namespace : Schema.TargetNamespace; this.SystemType = type.Datatype.ValueType; this.systemTypeCode = type.Datatype.TypeCode; this.Type = SimpleType.Extension; // Deal with an enum if (type.Content is System.Xml.Schema.XmlSchemaSimpleTypeList) { Type = SimpleType.Enum; System.Xml.Schema.XmlSchemaSimpleTypeList stl = type.Content as System.Xml.Schema.XmlSchemaSimpleTypeList; this.SystemType = stl.BaseItemType.Datatype.ValueType; this.systemTypeCode = stl.BaseItemType.Datatype.TypeCode; System.Xml.Schema.XmlSchemaObjectCollection listitems = null; if (stl.ItemType != null && stl.ItemType.Content is System.Xml.Schema.XmlSchemaSimpleTypeRestriction) // Restriction meaning this is an enum { listitems = (stl.ItemType.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets; } else if (stl.BaseItemType.Content is System.Xml.Schema.XmlSchemaSimpleTypeUnion) { listitems = new System.Xml.Schema.XmlSchemaObjectCollection(); foreach (System.Xml.Schema.XmlSchemaObject so in (stl.BaseItemType.Content as System.Xml.Schema.XmlSchemaSimpleTypeUnion).BaseMemberTypes) { if (so is System.Xml.Schema.XmlSchemaSimpleType) { foreach (System.Xml.Schema.XmlSchemaObject o in ((so as System.Xml.Schema.XmlSchemaSimpleType).Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction).Facets) { listitems.Add(o); } } } } // TODO: Can lists appear somewhere else? // Iterate through the restrictions if (listitems != null) { foreach (System.Xml.Schema.XmlSchemaObject o in listitems) { if (o is System.Xml.Schema.XmlSchemaEnumerationFacet) { Restrictions.Add((o as System.Xml.Schema.XmlSchemaEnumerationFacet).Value); } } } } //Debugger.Break(); }
/// <summary> Fill the EnumDeclaration with Attributes of the XmlSchemaSimpleType. </summary> public static void GenerateEnumeration(System.Xml.Schema.XmlSchemaSimpleType enumElt, Refly.CodeDom.EnumDeclaration ed) { ed.Doc.Summary.AddText(AnnotationToString(enumElt.Annotation)); // Create the <summary /> ed.AddField("unspecified").Doc.Summary.AddText("Default value (don't use it)"); // The default value if (enumElt.Content is System.Xml.Schema.XmlSchemaSimpleTypeRestriction) { System.Xml.Schema.XmlSchemaSimpleTypeRestriction restric = enumElt.Content as System.Xml.Schema.XmlSchemaSimpleTypeRestriction; foreach (System.Xml.Schema.XmlSchemaObject obj in restric.Facets) { if (obj is System.Xml.Schema.XmlSchemaEnumerationFacet) { System.Xml.Schema.XmlSchemaEnumerationFacet elt = obj as System.Xml.Schema.XmlSchemaEnumerationFacet; Refly.CodeDom.FieldDeclaration field = ed.AddField(elt.Value.Replace("-", "").ToLower()); field.Doc.Summary.AddText(elt.Value); // Create the <summary /> // Add the XmlEnumAttribute used in GetXmlEnumValue() Refly.CodeDom.AttributeDeclaration enumAttrib = field.CustomAttributes.Add("System.Xml.Serialization.XmlEnumAttribute"); enumAttrib.Arguments.Add("", new Refly.CodeDom.Expressions.SnippetExpression("\"" + elt.Value + "\"")); } else { log.Warn("Unknow Enum: " + obj.ToString()); } } } else { log.Warn("Unknow Enum Content: " + enumElt.Content.ToString()); } }
private void ValidateRestrictedSimpleTypeValue (SimpleType st, ref XsDatatype dt, string normalized) { { string [] values; XsDatatype itemDatatype; SimpleType itemSimpleType; switch (st.DerivedBy) { case XmlSchemaDerivationMethod.List: SimpleTypeList listContent = st.Content as SimpleTypeList; values = normalized.Split (XmlChar.WhitespaceChars); itemDatatype = listContent.ValidatedListItemType as XsDatatype; itemSimpleType = listContent.ValidatedListItemType as SimpleType; for (int vi = 0; vi < values.Length; vi++) { string each = values [vi]; if (each == String.Empty) continue; // validate against ValidatedItemType if (itemDatatype != null) { try { itemDatatype.ParseValue (each, nameTable, nsResolver); } catch (Exception ex) { // FIXME: (wishlist) better exception handling ;-( HandleError ("List type value contains one or more invalid values.", ex); break; } } else AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each); } break; case XmlSchemaDerivationMethod.Union: SimpleTypeUnion union = st.Content as SimpleTypeUnion; { string each = normalized; // validate against ValidatedItemType bool passed = false; foreach (object eachType in union.ValidatedTypes) { itemDatatype = eachType as XsDatatype; itemSimpleType = eachType as SimpleType; if (itemDatatype != null) { try { itemDatatype.ParseValue (each, nameTable, nsResolver); } catch (Exception) { // FIXME: (wishlist) better exception handling ;-( continue; } } else { try { AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each); } catch (ValException) { continue; } } passed = true; break; } if (!passed) { HandleError ("Union type value contains one or more invalid values."); break; } } break; case XmlSchemaDerivationMethod.Restriction: SimpleTypeRest str = st.Content as SimpleTypeRest; // facet validation if (str != null) { /* Don't forget to validate against inherited type's facets * Could we simplify this by assuming that the basetype will also * be restriction? * */ // mmm, will check later. SimpleType baseType = st.BaseXmlSchemaType as SimpleType; if (baseType != null) { AssessStringValid(baseType, dt, normalized); } if (!str.ValidateValueWithFacets (normalized, nameTable, nsResolver)) { HandleError ("Specified value was invalid against the facets."); break; } } dt = st.Datatype; break; } } }
static void Main() { try { log.Info("Generation of NHibernate.Mapping.Attributes"); // Open the Schema (in /NHMA/ directory) System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../../../../NHibernate.Mapping.Attributes/nhibernate-mapping.xsd"); schema = System.Xml.Schema.XmlSchema.Read(reader, null); Refly.CodeDom.NamespaceDeclaration nd = new Refly.CodeDom.NamespaceDeclaration("NHibernate.Mapping.Attributes", conformer); nd.Imports.Clear(); // remove "using System;" conformer.Capitalize = true; Refly.CodeDom.ClassDeclaration hbmWriter = nd.AddClass("HbmWriter"); hbmWriter.Attributes = System.Reflection.TypeAttributes.Public; hbmWriter.Doc.Summary.AddText(" Write a XmlSchemaElement from attributes in a System.Type. "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdDefaultHelper = hbmWriter.AddField("HbmWriterHelper", "DefaultHelper"); fdDefaultHelper.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("new HbmWriterHelperEx()"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdDefaultHelper = hbmWriter.AddProperty(fdDefaultHelper, true, true, false); pdDefaultHelper.Doc.Summary.AddText(" Gets or sets the HbmWriterHelper used by HbmWriter "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdStartQuote = hbmWriter.AddField(typeof(string), "StartQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdStartQuote = hbmWriter.AddProperty(fdStartQuote, false, true, false); pdStartQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_startQuote==null || _startQuote.Length==0) _startQuote = ""{{""; return _startQuote" )); pdStartQuote.Doc.Summary.AddText(" Gets or sets the beginning string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdEndQuote = hbmWriter.AddField(typeof(string), "EndQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdEndQuote = hbmWriter.AddProperty(fdEndQuote, false, true, false); pdEndQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_endQuote==null || _endQuote.Length==0) _endQuote = ""}}""; return _endQuote" )); pdEndQuote.Doc.Summary.AddText(" Gets or sets the ending string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdPatterns = hbmWriter.AddField(typeof(System.Collections.Hashtable), "Patterns"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdPatterns = hbmWriter.AddProperty(fdPatterns, false, true, false); pdPatterns.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_patterns==null) { _patterns = new System.Collections.Hashtable(); _patterns.Add(@""Nullables.Nullable(\w+), Nullables"", ""Nullables.NHibernate.Nullable$1Type, Nullables.NHibernate""); _patterns.Add(@""System.Data.SqlTypes.Sql(\w+), System.Data"", ""NHibernate.UserTypes.SqlTypes.Sql$1Type, NHibernate.UserTypes.SqlTypes""); } return _patterns" )); pdPatterns.Doc.Summary.AddText(" Gets or sets the Patterns to convert properties types (the key is the pattern string and the value is the replacement string) "); // Create the <summary /> HbmWriterGenerator.FillFindAttributedMembers(hbmWriter.AddMethod("FindAttributedMembers")); HbmWriterGenerator.FillGetSortedAttributes(hbmWriter.AddMethod("GetSortedAttributes")); HbmWriterGenerator.FillIsNextElement(hbmWriter.AddMethod("IsNextElement"), schema.Items); HbmWriterGenerator.FillGetXmlEnumValue(hbmWriter.AddMethod("GetXmlEnumValue")); HbmWriterGenerator.FillGetAttributeValue(hbmWriter.AddMethod("GetAttributeValue")); HbmWriterGenerator.FillWriteUserDefinedContent(hbmWriter.AddMethod("WriteUserDefinedContent"), hbmWriter.AddMethod("WriteUserDefinedContent")); log.Info("Browse Schema.Items (Count=" + schema.Items.Count + ")"); foreach (System.Xml.Schema.XmlSchemaObject obj in schema.Items) { if (obj is System.Xml.Schema.XmlSchemaAttributeGroup) { // Ignore (used by Elements: <xs:attributeGroup ref="..." />) log.Debug("Ignore AttributeGroup: " + (obj as System.Xml.Schema.XmlSchemaAttributeGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if (obj is System.Xml.Schema.XmlSchemaGroup) { // Ignore (used by Elements: <xs:group ref="..." />) log.Debug("Ignore Group: " + (obj as System.Xml.Schema.XmlSchemaGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if (obj is System.Xml.Schema.XmlSchemaSimpleType) { System.Xml.Schema.XmlSchemaSimpleType elt = obj as System.Xml.Schema.XmlSchemaSimpleType; log.Debug("Generate Enumeration for SimpleType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateEnumeration(elt, nd.AddEnum(Utils.Capitalize(elt.Name), false)); } else if (obj is System.Xml.Schema.XmlSchemaElement) { System.Xml.Schema.XmlSchemaElement elt = obj as System.Xml.Schema.XmlSchemaElement; System.Xml.Schema.XmlSchemaComplexType type = null; if (!elt.SchemaTypeName.IsEmpty) // eg: <xs:element name="cache" type="cacheType" /> { foreach (System.Xml.Schema.XmlSchemaObject o in schema.Items) { System.Xml.Schema.XmlSchemaComplexType t = o as System.Xml.Schema.XmlSchemaComplexType; if (t != null && t.Name == elt.SchemaTypeName.Name) { type = t; break; } } } string eltName = Utils.Capitalize(elt.Name); log.Debug("Generate Attrib and EltWriter for Elt: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateAttribute(elt, nd.AddClass(eltName + "Attribute"), type); HbmWriterGenerator.GenerateElementWriter(elt, eltName, hbmWriter.AddMethod("Write" + eltName), type, schema.Items); if (Utils.IsRoot(eltName)) { HbmWriterGenerator.FillWriteNestedTypes(eltName, hbmWriter.AddMethod("WriteNested" + eltName + "Types")); } } else if (obj is System.Xml.Schema.XmlSchemaComplexType) { // Ignore (Note: Make sure that it is used by Elements only like this: <xs:element name="XXX" type="YYY" />) System.Xml.Schema.XmlSchemaComplexType elt = obj as System.Xml.Schema.XmlSchemaComplexType; log.Debug("Don't generate ComplexType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); // like <query> and <sql-query> } else { log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } } // Generate the source code // Note: NameConformer.WordSplit() has been replaced in Refly. Refly.CodeDom.CodeGenerator gen = new Refly.CodeDom.CodeGenerator(); gen.Options.IndentString = " "; // Tab gen.CreateFolders = false; #region Copyright gen.Copyright = string.Format(@" NHibernate.Mapping.Attributes This product is under the terms of the GNU Lesser General Public License. ------------------------------------------------------------------------------ <autogenerated> This code was generated by a tool. Runtime Version: {0}.{1}.{2}.x Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. </autogenerated> ------------------------------------------------------------------------------ This source code was auto-generated by Refly, Version={3} (modified). ", System.Environment.Version.Major, System.Environment.Version.Minor, System.Environment.Version.Build, gen.GetType().Assembly.GetName(false).Version); #endregion log.Info("CodeGenerator.GenerateCode()... Classes=" + nd.Classes.Count + ", Enums=" + nd.Enums.Count); gen.GenerateCode(@"../../../../NHibernate.Mapping.Attributes", nd); log.Info("Done !"); } catch (System.Exception ex) { log.Error("Unexpected Exception", ex); } }
// 3.14.4 String Valid private object AssessStringValid (SimpleType st, XsDatatype dt, string value) { XsDatatype validatedDatatype = dt; object ret = null; if (st != null) { string normalized = validatedDatatype.Normalize (value); string [] values; XsDatatype itemDatatype; SimpleType itemSimpleType; switch (st.DerivedBy) { case XmlSchemaDerivationMethod.List: SimpleTypeList listContent = st.Content as SimpleTypeList; values = normalized.Split (XmlChar.WhitespaceChars); // LAMESPEC: Types of each element in // the returned list might be // inconsistent, so basically returning // value does not make sense without // explicit runtime type information // for base primitive type. object [] retValues = new object [values.Length]; itemDatatype = listContent.ValidatedListItemType as XsDatatype; itemSimpleType = listContent.ValidatedListItemType as SimpleType; for (int vi = 0; vi < values.Length; vi++) { string each = values [vi]; if (each == String.Empty) continue; // validate against ValidatedItemType if (itemDatatype != null) { try { retValues [vi] = itemDatatype.ParseValue (each, nameTable, nsResolver); } catch (Exception ex) { // It is inevitable and bad manner. HandleError ("List type value contains one or more invalid values.", ex); break; } } else AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each); } ret = retValues; break; case XmlSchemaDerivationMethod.Union: SimpleTypeUnion union = st.Content as SimpleTypeUnion; { string each = normalized; // validate against ValidatedItemType bool passed = false; foreach (object eachType in union.ValidatedTypes) { itemDatatype = eachType as XsDatatype; itemSimpleType = eachType as SimpleType; if (itemDatatype != null) { try { ret = itemDatatype.ParseValue (each, nameTable, nsResolver); } catch (Exception) { // It is inevitable and bad manner. continue; } } else { try { ret = AssessStringValid (itemSimpleType, itemSimpleType.Datatype, each); } catch (ValException) { continue; } } passed = true; break; } if (!passed) { HandleError ("Union type value contains one or more invalid values."); break; } } break; case XmlSchemaDerivationMethod.Restriction: SimpleTypeRest str = st.Content as SimpleTypeRest; // facet validation if (str != null) { /* Don't forget to validate against inherited type's facets * Could we simplify this by assuming that the basetype will also * be restriction? * */ // mmm, will check later. SimpleType baseType = st.BaseXmlSchemaType as SimpleType; if (baseType != null) { ret = AssessStringValid (baseType, dt, value); } if (!str.ValidateValueWithFacets (value, nameTable, nsResolver)) { HandleError ("Specified value was invalid against the facets."); break; } } validatedDatatype = st.Datatype; break; } } if (validatedDatatype != null) { try { ret = validatedDatatype.ParseValue (value, nameTable, nsResolver); } catch (Exception ex) { // It is inevitable and bad manner. HandleError ("Invalidly typed data was specified", ex); } } return ret; }