private void WriteDataColumn(XmlSchema schema, CremaDataColumn dataColumn) { if (dataColumn.Validation != string.Empty) { var simpleType = new XmlSchemaSimpleType() { Name = dataColumn.GetXmlSchemaTypeName(), }; { var simpleTypeRestriction = new XmlSchemaSimpleTypeRestriction() { BaseTypeName = GetSystemQualifiedName(dataColumn.DataType) }; { var facet = new XmlSchemaPatternFacet() { Value = dataColumn.Validation }; simpleTypeRestriction.Facets.Add(facet); } simpleType.Content = simpleTypeRestriction; } schema.Items.Add(simpleType); } }
void ExportDerivedSchema(XmlTypeMapping map) { if (IsMapExported(map)) { return; } SetMapExported(map); XmlSchema schema = GetSchema(map.XmlTypeNamespace); for (int i = 0; i < schema.Items.Count; i++) { XmlSchemaSimpleType item = schema.Items [i] as XmlSchemaSimpleType; if (item != null && item.Name == map.ElementName) { return; } } XmlSchemaSimpleType stype = new XmlSchemaSimpleType(); stype.Name = map.ElementName; schema.Items.Add(stype); XmlSchemaSimpleTypeRestriction rest = new XmlSchemaSimpleTypeRestriction(); rest.BaseTypeName = new XmlQualifiedName(map.TypeData.MappedType.XmlType, XmlSchema.Namespace); XmlSchemaPatternFacet facet = map.TypeData.XmlSchemaPatternFacet; if (facet != null) { rest.Facets.Add(facet); } stype.Content = rest; }
private void ExportDerivedSchema(XmlTypeMapping map) { if (this.IsMapExported(map)) { return; } this.SetMapExported(map); XmlSchema schema = this.GetSchema(map.XmlTypeNamespace); for (int i = 0; i < schema.Items.Count; i++) { XmlSchemaSimpleType xmlSchemaSimpleType = schema.Items[i] as XmlSchemaSimpleType; if (xmlSchemaSimpleType != null && xmlSchemaSimpleType.Name == map.ElementName) { return; } } XmlSchemaSimpleType xmlSchemaSimpleType2 = new XmlSchemaSimpleType(); xmlSchemaSimpleType2.Name = map.ElementName; schema.Items.Add(xmlSchemaSimpleType2); XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction = new XmlSchemaSimpleTypeRestriction(); xmlSchemaSimpleTypeRestriction.BaseTypeName = new XmlQualifiedName(map.TypeData.MappedType.XmlType, "http://www.w3.org/2001/XMLSchema"); XmlSchemaPatternFacet xmlSchemaPatternFacet = map.TypeData.XmlSchemaPatternFacet; if (xmlSchemaPatternFacet != null) { xmlSchemaSimpleTypeRestriction.Facets.Add(xmlSchemaPatternFacet); } xmlSchemaSimpleType2.Content = xmlSchemaSimpleTypeRestriction; }
internal void Add(XmlDocument schemaDoc, XmlSchema schema, string typeName, string namespaceUri) { XmlSchemaSimpleType simpleType = schema.SchemaTypes[new XmlQualifiedName(typeName, namespaceUri)] as XmlSchemaSimpleType; XmlSchemaSimpleTypeRestriction typeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; XmlSchemaPatternFacet pattern = typeRestriction.Facets[0] as XmlSchemaPatternFacet; Regex re = new Regex(pattern.Value); XmlNodeList attributeNameNodes = schemaDoc.SelectNodes("//*[@type='" + typeName + "']/@name"); for (int i = 0; i < attributeNameNodes.Count; i++) { string attrName = attributeNameNodes.Item(i).Value; if (RegexForAttrName[attrName] != null) { continue; } else { RegexForAttrName[attrName] = re; if (XPathPredicateOfAttributes == null) { XPathPredicateOfAttributes = ""; } else { XPathPredicateOfAttributes += " or "; } XPathPredicateOfAttributes += "local-name() = '" + attrName + "'"; } } }
public TypeData(Type type, string elementName, bool isPrimitive, TypeData mappedType, XmlSchemaPatternFacet facet) { #if NET_2_0 if (type.IsGenericTypeDefinition) { throw new InvalidOperationException("Generic type definition cannot be used in serialization. Only specific generic types can be used."); } #endif this.mappedType = mappedType; this.facet = facet; this.type = type; this.typeName = type.Name; this.fullTypeName = type.FullName.Replace('+', '.'); if (isPrimitive) { sType = SchemaTypes.Primitive; } else { if (type.IsEnum) { sType = SchemaTypes.Enum; } else if (typeof(IXmlSerializable).IsAssignableFrom(type)) { sType = SchemaTypes.XmlSerializable; } else if (typeof(System.Xml.XmlNode).IsAssignableFrom(type)) { sType = SchemaTypes.XmlNode; } else if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type)) { sType = SchemaTypes.Array; } else { sType = SchemaTypes.Class; } } if (IsListType) { this.elementName = TypeTranslator.GetArrayName(ListItemTypeData.XmlType); } else { this.elementName = elementName; } if (sType == SchemaTypes.Array || sType == SchemaTypes.Class) { hasPublicConstructor = !type.IsInterface && (type.IsArray || type.GetConstructor(Type.EmptyTypes) != null || type.IsAbstract || type.IsValueType); } LookupTypeConvertor(); }
internal XSPatternFacet(XmlSchemaPatternFacet patternFacet) { _facet = patternFacet; if (_facet.Annotation is XmlSchemaAnnotation annotation) { _annotation = XMLSchemaSerializer.CreateXSAnnotation(annotation); _annotation.BindToContainer(RootContainer, this); } }
/// <summary> /// Returns a simple type which extends the basic datatype and /// restricts it using a regex pattern /// </summary> public override XmlSchemaSimpleType GetSimpleType(string attributeDataType) { var retVal = base.GetSimpleType(attributeDataType); var restriction = (XmlSchemaSimpleTypeRestriction)retVal.Content; var rxa = (RegexStringValidatorAttribute)Attribute; var pFacet = new XmlSchemaPatternFacet { Value = rxa.Regex }; restriction.Facets.Add(pFacet); return(retVal); }
static TypeScope() { AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference); AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(SByte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt16), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt32), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt64), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); // Types without direct mapping (ambigous) AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired); // NOTE, stefanph: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we // can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or // [XmlArrayItem]. XmlSchemaPatternFacet guidPattern = new XmlSchemaPatternFacet(); guidPattern.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[] { guidPattern }, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter); AddSoapEncodedTypes(Soap.Encoding); // Unsuppoted types that we map to string, if in the future we decide // to add support for them we would need to create custom formatters for them for (int i = 0; i < unsupportedTypes.Length; i++) { AddPrimitive(typeof(string), unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference); } }
public bool AddPatternConstraint(String pattern) { //TODO: check the pattern correctness. is there a nice way? if (pattern == null || pattern.Equals("")) { return(false); } XmlSchemaPatternFacet schemaPattern = new XmlSchemaPatternFacet(); schemaPattern.Value = pattern; Common.addFacet(schemaPattern, Common.getElementFromSchema(baseSchema)); return(true); }
/// <summary> /// Creates a simple type that matches a regex /// </summary> /// <param name="Name">Name of the new type</param> /// <param name="Pattern">Regex pattern to match</param> /// <returns>A simple type which will match the given pattern</returns> static XmlSchemaSimpleType CreateSimpleTypeFromRegex(string Name, string Pattern) { XmlSchemaPatternFacet PatternFacet = new XmlSchemaPatternFacet(); PatternFacet.Value = Pattern; XmlSchemaSimpleTypeRestriction Restriction = new XmlSchemaSimpleTypeRestriction(); Restriction.BaseTypeName = StringTypeName; Restriction.Facets.Add(PatternFacet); XmlSchemaSimpleType SimpleType = new XmlSchemaSimpleType(); SimpleType.Name = Name; SimpleType.Content = Restriction; return(SimpleType); }
private void method_3(XmlNode A_0, ModeType A_1) { int num = 5; XmlSchemaSimpleType item = new XmlSchemaSimpleType { Name = A_0.Attributes[BookmarkStart.b("䔪䰬䈮吰", 5)].Value }; XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction { BaseTypeName = new XmlQualifiedName(BookmarkStart.b("堪夬崮堰崲刴", 5), BookmarkStart.b("䌪夬嬮䄰लᨴᠶ丸䰺䨼ᄾ㙀灂歄⡆㭈ⱊ扌絎慐捒摔硖Řᙚᅜɠୢd੦ࡨ", 5)) }; item.Content = restriction; switch (A_1) { case ModeType.Enum: foreach (XmlNode node2 in A_0.SelectNodes(BookmarkStart.b("䘪ᜬ䨮弰䘲場", num), this.xmlNamespaceManager_0)) { XmlSchemaEnumerationFacet facet2 = new XmlSchemaEnumerationFacet { Value = node2.Attributes[BookmarkStart.b("崪䰬䌮䐰嘲", num)].Value }; restriction.Facets.Add(facet2); } break; case ModeType.Pattern: { XmlNode node = A_0.SelectSingleNode(BookmarkStart.b("䘪ᜬ弮倰䜲䄴制䬸唺", num), this.xmlNamespaceManager_0); XmlSchemaPatternFacet facet = new XmlSchemaPatternFacet { Value = node.Attributes[BookmarkStart.b("崪䰬䌮䐰嘲", num)].Value }; restriction.Facets.Add(facet); break; } case ModeType.Space: { XmlNode node3 = A_0.SelectSingleNode(BookmarkStart.b("䘪ᜬ堮夰娲䄴制䨸䬺尼尾⑀", num), this.xmlNamespaceManager_0); XmlSchemaWhiteSpaceFacet facet3 = new XmlSchemaWhiteSpaceFacet { Value = node3.Attributes[BookmarkStart.b("崪䰬䌮䐰嘲", num)].Value }; restriction.Facets.Add(facet3); break; } } this.xmlSchema_0.Items.Add(item); }
/// <summary> /// Gets the definition of the attribute from an XML schema simple type /// </summary> /// <param name="type">The XML schema simple type representing this attribute</param> private void LoadSimpleType(XmlSchemaSimpleType type) { XmlSchemaSimpleTypeRestriction restriction = type.Content as XmlSchemaSimpleTypeRestriction; if (((restriction == null) || (null == restriction.BaseTypeName)) || (restriction.BaseTypeName.Name == null)) { throw new InvalidOperationException("The schema attribute had an invalid or missing restriction"); } XmlSchemaObjectCollection facets = restriction.Facets; if (restriction.BaseTypeName.Name == "string") { this.Type = AttributeType.String; if (facets.Count != 1) { throw new InvalidOperationException("The number of restrictions on the attribute type was invalid"); } XmlSchemaPatternFacet facet = facets[0] as XmlSchemaPatternFacet; if (facet.Value != ".{0,448}") { this.Regex = facet.Value; } if (this.Regex != ".{0,448}" && !HasStringAnnotation(type.Annotation)) { this.Type = AttributeType.Text; } this.IsMultivalued = false; } else if (restriction.BaseTypeName.Name == "integer") { this.Type = AttributeType.Integer; this.IsMultivalued = false; } else { throw new InvalidOperationException("The attribute type was unknown"); } }
private void WriteGuidType(XmlSchema schema) { var pattern = new XmlSchemaPatternFacet() { Value = @"([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}", }; var restriction = new XmlSchemaSimpleTypeRestriction() { BaseTypeName = GetSystemQualifiedName(typeof(string)), }; restriction.Facets.Add(pattern); var simpleType = new XmlSchemaSimpleType() { Name = typeof(Guid).GetTypeName(), Content = restriction, }; schema.Items.Add(simpleType); }
static TypeScope() { AddPrimitive(typeof(string), "string", "String", TypeFlags.HasDefaultConstructor | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(int), "int", "Int32", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(short), "short", "Int16", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(long), "long", "Int64", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(float), "float", "Single", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(double), "double", "Double", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.XmlEncodingNotRequired | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.XmlEncodingNotRequired | TypeFlags.HasIsEmpty | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(sbyte), "byte", "SByte", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(ushort), "unsignedShort", "UInt16", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(uint), "unsignedInt", "UInt32", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(ulong), "unsignedLong", "UInt64", TypeFlags.XmlEncodingNotRequired | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.XmlEncodingNotRequired | TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.XmlEncodingNotRequired | TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor | TypeFlags.IgnoreDefault | TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor | TypeFlags.IgnoreDefault | TypeFlags.AmbiguousDataType | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); XmlSchemaPatternFacet facet = new XmlSchemaPatternFacet { Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" }; AddNonXsdPrimitive(typeof(Guid), "guid", "http://microsoft.com/wsdl/types/", "Guid", new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"), new XmlSchemaFacet[] { facet }, TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddNonXsdPrimitive(typeof(char), "char", "http://microsoft.com/wsdl/types/", "Char", new XmlQualifiedName("unsignedShort", "http://www.w3.org/2001/XMLSchema"), new XmlSchemaFacet[0], TypeFlags.IgnoreDefault | TypeFlags.HasCustomFormatter | TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); AddSoapEncodedTypes("http://schemas.xmlsoap.org/soap/encoding/"); AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.HasDefaultConstructor | TypeFlags.AmbiguousDataType | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); for (int i = 0; i < unsupportedTypes.Length; i++) { AddPrimitive(typeof(string), unsupportedTypes[i], "String", TypeFlags.CollapseWhitespace | TypeFlags.AmbiguousDataType | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue | TypeFlags.Reference); } }
/// <summary> /// Returns a simple type which extends the basic datatype and /// restricts is using the string validator /// </summary> public override XmlSchemaSimpleType GetSimpleType(string attributeDataType) { var retVal = base.GetSimpleType(attributeDataType); var restriction = (XmlSchemaSimpleTypeRestriction)retVal.Content; var sva = (StringValidatorAttribute)Attribute; if (!string.IsNullOrEmpty(sva.InvalidCharacters)) { var pFacet = new XmlSchemaPatternFacet { Value = sva.InvalidCharacters }; // TODO: convert this to a regex that excludes the characters pFacet.Value = string.Format( "[^{0}]*", pFacet.Value .Replace(@"\", @"\\") .Replace(@"[", @"\[") .Replace(@"]", @"\]")); restriction.Facets.Add(pFacet); } var minFacet = new XmlSchemaMinLengthFacet { Value = sva.MinLength.ToString() }; restriction.Facets.Add(minFacet); var maxFacet = new XmlSchemaMaxLengthFacet { Value = sva.MaxLength.ToString() }; restriction.Facets.Add(maxFacet); return(retVal); }
static TypeTranslator() { TypeTranslator.nameCache = Hashtable.Synchronized(TypeTranslator.nameCache); TypeTranslator.nameCache.Add(typeof(bool), new TypeData(typeof(bool), "boolean", true)); TypeTranslator.nameCache.Add(typeof(short), new TypeData(typeof(short), "short", true)); TypeTranslator.nameCache.Add(typeof(ushort), new TypeData(typeof(ushort), "unsignedShort", true)); TypeTranslator.nameCache.Add(typeof(int), new TypeData(typeof(int), "int", true)); TypeTranslator.nameCache.Add(typeof(uint), new TypeData(typeof(uint), "unsignedInt", true)); TypeTranslator.nameCache.Add(typeof(long), new TypeData(typeof(long), "long", true)); TypeTranslator.nameCache.Add(typeof(ulong), new TypeData(typeof(ulong), "unsignedLong", true)); TypeTranslator.nameCache.Add(typeof(float), new TypeData(typeof(float), "float", true)); TypeTranslator.nameCache.Add(typeof(double), new TypeData(typeof(double), "double", true)); TypeTranslator.nameCache.Add(typeof(DateTime), new TypeData(typeof(DateTime), "dateTime", true)); TypeTranslator.nameCache.Add(typeof(decimal), new TypeData(typeof(decimal), "decimal", true)); TypeTranslator.nameCache.Add(typeof(XmlQualifiedName), new TypeData(typeof(XmlQualifiedName), "QName", true)); TypeTranslator.nameCache.Add(typeof(string), new TypeData(typeof(string), "string", true)); XmlSchemaPatternFacet xmlSchemaPatternFacet = new XmlSchemaPatternFacet(); xmlSchemaPatternFacet.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; TypeTranslator.nameCache.Add(typeof(Guid), new TypeData(typeof(Guid), "guid", true, (TypeData)TypeTranslator.nameCache[typeof(string)], xmlSchemaPatternFacet)); TypeTranslator.nameCache.Add(typeof(byte), new TypeData(typeof(byte), "unsignedByte", true)); TypeTranslator.nameCache.Add(typeof(sbyte), new TypeData(typeof(sbyte), "byte", true)); TypeTranslator.nameCache.Add(typeof(char), new TypeData(typeof(char), "char", true, (TypeData)TypeTranslator.nameCache[typeof(ushort)], null)); TypeTranslator.nameCache.Add(typeof(object), new TypeData(typeof(object), "anyType", false)); TypeTranslator.nameCache.Add(typeof(byte[]), new TypeData(typeof(byte[]), "base64Binary", true)); TypeTranslator.nameCache.Add(typeof(XmlNode), new TypeData(typeof(XmlNode), "XmlNode", false)); TypeTranslator.nameCache.Add(typeof(XmlElement), new TypeData(typeof(XmlElement), "XmlElement", false)); TypeTranslator.primitiveTypes = new Hashtable(); ICollection values = TypeTranslator.nameCache.Values; foreach (object obj in values) { TypeData typeData = (TypeData)obj; TypeTranslator.primitiveTypes.Add(typeData.XmlType, typeData); } TypeTranslator.primitiveTypes.Add("date", new TypeData(typeof(DateTime), "date", true)); TypeTranslator.primitiveTypes.Add("time", new TypeData(typeof(DateTime), "time", true)); TypeTranslator.primitiveTypes.Add("timePeriod", new TypeData(typeof(DateTime), "timePeriod", true)); TypeTranslator.primitiveTypes.Add("gDay", new TypeData(typeof(string), "gDay", true)); TypeTranslator.primitiveTypes.Add("gMonthDay", new TypeData(typeof(string), "gMonthDay", true)); TypeTranslator.primitiveTypes.Add("gYear", new TypeData(typeof(string), "gYear", true)); TypeTranslator.primitiveTypes.Add("gYearMonth", new TypeData(typeof(string), "gYearMonth", true)); TypeTranslator.primitiveTypes.Add("month", new TypeData(typeof(DateTime), "month", true)); TypeTranslator.primitiveTypes.Add("NMTOKEN", new TypeData(typeof(string), "NMTOKEN", true)); TypeTranslator.primitiveTypes.Add("NMTOKENS", new TypeData(typeof(string), "NMTOKENS", true)); TypeTranslator.primitiveTypes.Add("Name", new TypeData(typeof(string), "Name", true)); TypeTranslator.primitiveTypes.Add("NCName", new TypeData(typeof(string), "NCName", true)); TypeTranslator.primitiveTypes.Add("language", new TypeData(typeof(string), "language", true)); TypeTranslator.primitiveTypes.Add("integer", new TypeData(typeof(string), "integer", true)); TypeTranslator.primitiveTypes.Add("positiveInteger", new TypeData(typeof(string), "positiveInteger", true)); TypeTranslator.primitiveTypes.Add("nonPositiveInteger", new TypeData(typeof(string), "nonPositiveInteger", true)); TypeTranslator.primitiveTypes.Add("negativeInteger", new TypeData(typeof(string), "negativeInteger", true)); TypeTranslator.primitiveTypes.Add("nonNegativeInteger", new TypeData(typeof(string), "nonNegativeInteger", true)); TypeTranslator.primitiveTypes.Add("ENTITIES", new TypeData(typeof(string), "ENTITIES", true)); TypeTranslator.primitiveTypes.Add("ENTITY", new TypeData(typeof(string), "ENTITY", true)); TypeTranslator.primitiveTypes.Add("hexBinary", new TypeData(typeof(byte[]), "hexBinary", true)); TypeTranslator.primitiveTypes.Add("ID", new TypeData(typeof(string), "ID", true)); TypeTranslator.primitiveTypes.Add("IDREF", new TypeData(typeof(string), "IDREF", true)); TypeTranslator.primitiveTypes.Add("IDREFS", new TypeData(typeof(string), "IDREFS", true)); TypeTranslator.primitiveTypes.Add("NOTATION", new TypeData(typeof(string), "NOTATION", true)); TypeTranslator.primitiveTypes.Add("token", new TypeData(typeof(string), "token", true)); TypeTranslator.primitiveTypes.Add("normalizedString", new TypeData(typeof(string), "normalizedString", true)); TypeTranslator.primitiveTypes.Add("anyURI", new TypeData(typeof(string), "anyURI", true)); TypeTranslator.primitiveTypes.Add("base64", new TypeData(typeof(byte[]), "base64", true)); TypeTranslator.primitiveTypes.Add("duration", new TypeData(typeof(string), "duration", true)); TypeTranslator.nullableTypes = Hashtable.Synchronized(new Hashtable()); foreach (object obj2 in TypeTranslator.primitiveTypes) { DictionaryEntry dictionaryEntry = (DictionaryEntry)obj2; TypeData typeData2 = (TypeData)dictionaryEntry.Value; TypeData typeData3 = new TypeData(typeData2.Type, typeData2.XmlType, true); typeData3.IsNullable = true; TypeTranslator.nullableTypes.Add(dictionaryEntry.Key, typeData3); } }
internal string GenerateSimpleType( XmlSchemaSimpleType type, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider) { CodeTypeDeclaration codeClass = CodeDomHelper.CreateClassDeclaration(type); mainNamespace.Types.Add(codeClass); CodeDomHelper.GenerateXmlTypeAttribute(codeClass, type.QualifiedName.Name, type.QualifiedName.Namespace); XmlSchemaSimpleTypeRestriction restriction = type.Content as XmlSchemaSimpleTypeRestriction; Type baseType = XsdToClrPrimitive(restriction.BaseTypeName); CodeMemberField field = CodeDomHelper.AddField(codeClass, "value", baseType); CodeMemberProperty prop = CodeDomHelper.AddPropertyDeclaration(codeClass, field, "Value", baseType); CodeDomHelper.AddTextAttribute(prop.CustomAttributes); CodeDomHelper.AddCtor(codeClass); CodeDomHelper.AddCtor(codeClass, prop); // for each facet we support, add validation to the setter foreach (object facet in restriction.Facets) { XmlSchemaLengthFacet length = facet as XmlSchemaLengthFacet; if (length != null) { int?value = ToInt32(length.Value); if (value.HasValue) { CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length"); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(value)); prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("length", value) }, new CodeStatement[0])); } continue; } XmlSchemaPatternFacet pattern = facet as XmlSchemaPatternFacet; if (pattern != null) { // TODO: might want ot validate the pattern value here to make sure that it is a valid Regex. if (!string.IsNullOrEmpty(pattern.Value)) { CodeExpression patternMatch = CodeDomHelper.MethodCall( CodeDomHelper.TypeExpr(typeof(Regex)), "IsMatch", new CodeExpression[] { CodeDomHelper.Value(), CodeDomHelper.Primitive(pattern.Value) }); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(patternMatch, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true)); prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("pattern", pattern.Value) }, new CodeStatement[0])); } continue; } XmlSchemaMinLengthFacet minLength = facet as XmlSchemaMinLengthFacet; if (minLength != null) { int?value = ToInt32(minLength.Value); if (value.HasValue) { CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length"); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(value)); prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("minLength", value) }, new CodeStatement[0])); } continue; } XmlSchemaMaxLengthFacet maxLength = facet as XmlSchemaMaxLengthFacet; if (maxLength != null) { int?value = ToInt32(maxLength.Value); if (value.HasValue) { CodeExpression valueLength = CodeDomHelper.Property(CodeDomHelper.Value(), "Length"); CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(value)); prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("maxLength", value) }, new CodeStatement[0])); } continue; } } //add ToSrting() Overload and implicit and explicit Cast operators for compatibilty woth previously generated code CodeMemberMethod toString = CodeDomHelper.MethodDecl(typeof(string), "ToString", MemberAttributes.Public | MemberAttributes.Override); toString.Statements.Add(CodeDomHelper.Return(CodeDomHelper.Property("value"))); codeClass.Members.Add(toString); // Unfortunately CodeDom does not support operators, so we have to use CodeSnippet to generate the Cast operators // CodeSnippet is not language aware, so we have to use different snippets for different providers // this version only support c# syntax if (codeProvider is Microsoft.CSharp.CSharpCodeProvider) { string implicitCast = string.Format(" public static implicit operator {0}({1} x) {{ return new {0}(x); }}", codeClass.Name, baseType.FullName); CodeSnippetTypeMember implicitOp = new CodeSnippetTypeMember(implicitCast); codeClass.Members.Add(implicitOp); string explicitCast = string.Format(" public static explicit operator {1}({0} x) {{ return x.Value; }}", codeClass.Name, baseType.FullName); CodeSnippetTypeMember explicitOp = new CodeSnippetTypeMember(explicitCast); codeClass.Members.Add(explicitOp); } return(codeClass.Name); }
protected override XmlSchemaType RamlTypeToSchemaType(RamlType ramlType, ConversionOptions options) { if (ramlType == null) { return(null); } XmlSchemaType xmlSchemaType; // check if it is enum if (ramlType.Enum != null) { xmlSchemaType = new XmlSchemaSimpleType(); xmlSchemaType.Name = ramlType.Name; var restriction = new XmlSchemaSimpleTypeRestriction(); var enumElementTypeName = RamlDataTypeToXmlSchemaDataType(ramlType.Enum.ItemsTypeName); if (enumElementTypeName == null) { enumElementTypeName = GetXmlRefDataType(ramlType.Enum.ItemsTypeName, options.XmlNamespace); } if (enumElementTypeName != null) { restriction.BaseTypeName = enumElementTypeName; } foreach (string enumValue in ramlType.Enum.EnumValues) { var enumerationFacet = new XmlSchemaEnumerationFacet(); enumerationFacet.Value = enumValue; restriction.Facets.Add(enumerationFacet); } ((XmlSchemaSimpleType)xmlSchemaType).Content = restriction; return(xmlSchemaType); } xmlSchemaType = new XmlSchemaComplexType(); xmlSchemaType.Name = ramlType.Name; // check if it is array if (ramlType.Array != null) { var arraySequence = new XmlSchemaSequence(); var arrayElement = new XmlSchemaElement(); arrayElement.Name = ramlType.Array.ItemName; arrayElement.MaxOccursString = "unbounded"; var arrayElementTypeName = RamlDataTypeToXmlSchemaDataType(ramlType.Array.ItemsTypeName); if (arrayElementTypeName == null) { arrayElementTypeName = GetXmlRefDataType(ramlType.Array.ItemsTypeName, options.XmlNamespace); } if (arrayElementTypeName != null) { arrayElement.SchemaTypeName = arrayElementTypeName; } arraySequence.Items.Add(arrayElement); ((XmlSchemaComplexType)xmlSchemaType).Particle = arraySequence; return(xmlSchemaType); } // check if it has base if (ramlType.Base != null) { // assume simple type for now xmlSchemaType = new XmlSchemaSimpleType(); xmlSchemaType.Name = ramlType.Name; var restriction = new XmlSchemaSimpleTypeRestriction(); var baseTypeName = RamlDataTypeToXmlSchemaDataType(ramlType.Base.Name); if (baseTypeName == null) { baseTypeName = GetXmlRefDataType(ramlType.Base.Name, options.XmlNamespace); } if (baseTypeName != null) { restriction.BaseTypeName = baseTypeName; } if (!string.IsNullOrEmpty(ramlType.Base.Pattern)) { var pattern = new XmlSchemaPatternFacet(); pattern.Value = ramlType.Base.Pattern; restriction.Facets.Add(pattern); } ((XmlSchemaSimpleType)xmlSchemaType).Content = restriction; return(xmlSchemaType); } var annotation = GetXmlAnnotattion(ramlType.Description); if (annotation != null && options.GenerateDescriptions) { xmlSchemaType.Annotation = annotation; } var sequence = new XmlSchemaSequence(); ((XmlSchemaComplexType)xmlSchemaType).Particle = sequence; if (ramlType.Properties == null || ramlType.Properties.Count == 0) { return(xmlSchemaType); } foreach (RamlProperty ramlProperty in ramlType.Properties) { var xmlSchemaProperty = new XmlSchemaElement(); xmlSchemaProperty.Name = ramlProperty.Name; var typeName = RamlDataTypeToXmlSchemaDataType(ramlProperty.Type); if (typeName == null) { typeName = GetXmlRefDataType(ramlProperty.Type, options.XmlNamespace); } if (typeName != null) { xmlSchemaProperty.SchemaTypeName = typeName; } var propertyAnnotation = GetXmlAnnotattion(ramlProperty.Description); if (propertyAnnotation != null && options.GenerateDescriptions) { xmlSchemaProperty.Annotation = propertyAnnotation; } sequence.Items.Add(xmlSchemaProperty); if (!ramlProperty.Required) { xmlSchemaProperty.MinOccurs = 0; xmlSchemaProperty.IsNillable = true; } } return(xmlSchemaType); }
private XmlSchemaSimpleType SetSchemaFacets(XmlSchemaSimpleType simpleType, List <MessagePart> MessageParts) { Debug.Assert(!(simpleType.Content is XmlSchemaSimpleTypeUnion), "Cannot apply restrictions to unions."); Debug.Assert(!(simpleType.Content is XmlSchemaSimpleTypeList), "Cannot apply restrictions to lists."); XmlSchemaSimpleTypeRestriction oldRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction; XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); //preserve existing facets if (oldRestriction != null) { foreach (XmlSchemaObject restrictionFacet in oldRestriction.Facets) { if (!(restrictionFacet is XmlSchemaMaxLengthFacet) && !(restrictionFacet is XmlSchemaMinLengthFacet)) { restriction.Facets.Add(restrictionFacet); } } } foreach (MessagePart messagePart in MessageParts) { StringLengthMessagePart stringLengthMessagePart = messagePart as StringLengthMessagePart; RegexMessagePart regexMessagePart = messagePart as RegexMessagePart; RangeMessagePart rangeMessagePart = messagePart as RangeMessagePart; if (stringLengthMessagePart != null) { if (stringLengthMessagePart.MaxLength > 0) { XmlSchemaMaxLengthFacet maxLengthFacet = new XmlSchemaMaxLengthFacet(); maxLengthFacet.Value = stringLengthMessagePart.MaxLength.ToString(); restriction.Facets.Add(maxLengthFacet); } if (stringLengthMessagePart.MinLength > 0) { XmlSchemaMinLengthFacet minLengthFacet = new XmlSchemaMinLengthFacet(); minLengthFacet.Value = stringLengthMessagePart.MinLength.ToString(); restriction.Facets.Add(minLengthFacet); } } if (regexMessagePart != null) { XmlSchemaPatternFacet patternFacet = new XmlSchemaPatternFacet(); patternFacet.Value = regexMessagePart.Regex; restriction.Facets.Add(patternFacet); } if (rangeMessagePart != null) { XmlSchemaMinInclusiveFacet minInclusiveFacet = new XmlSchemaMinInclusiveFacet(); minInclusiveFacet.Value = rangeMessagePart.Min.ToString(); restriction.Facets.Add(minInclusiveFacet); XmlSchemaMaxInclusiveFacet maxInclusiveFacet = new XmlSchemaMaxInclusiveFacet(); maxInclusiveFacet.Value = rangeMessagePart.Max.ToString(); restriction.Facets.Add(maxInclusiveFacet); } } restriction.BaseTypeName = simpleType.QualifiedName; XmlSchemaSimpleType newType = new XmlSchemaSimpleType(); newType.Content = restriction; return(newType); }
public XsdSimpleRestrictionType(RelaxngDatatype primitive, RelaxngParamList parameters) { type = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction r = new XmlSchemaSimpleTypeRestriction(); type.Content = r; string ns = primitive.NamespaceURI; // Remap XML Schema datatypes namespace -> XML Schema namespace. if (ns == "http://www.w3.org/2001/XMLSchema-datatypes") { ns = XSchema.Namespace; } r.BaseTypeName = new XmlQualifiedName(primitive.Name, ns); foreach (RelaxngParam p in parameters) { XmlSchemaFacet f = null; string value = p.Value; switch (p.Name) { case "maxExclusive": f = new XmlSchemaMaxExclusiveFacet(); break; case "maxInclusive": f = new XmlSchemaMaxInclusiveFacet(); break; case "minExclusive": f = new XmlSchemaMinExclusiveFacet(); break; case "minInclusive": f = new XmlSchemaMinInclusiveFacet(); break; case "pattern": f = new XmlSchemaPatternFacet(); // .NET/Mono Regex has a bug that it does not support "IsLatin-1Supplement" // (it somehow breaks at '-'). value = value.Replace("\\p{IsLatin-1Supplement}", "[\\x80-\\xFF]"); break; case "whiteSpace": f = new XmlSchemaWhiteSpaceFacet(); break; case "length": f = new XmlSchemaLengthFacet(); break; case "maxLength": f = new XmlSchemaMaxLengthFacet(); break; case "minLength": f = new XmlSchemaMinLengthFacet(); break; case "fractionDigits": f = new XmlSchemaFractionDigitsFacet(); break; case "totalDigits": f = new XmlSchemaTotalDigitsFacet(); break; default: throw new RelaxngException(String.Format("XML Schema facet {0} is not recognized or not supported.", p.Name)); } f.Value = value; r.Facets.Add(f); } // Now we create XmlSchema to handle simple-type // based validation (since there is no other way, // because of sucky XmlSchemaSimpleType design). schema = new XSchema(); XmlSchemaElement el = new XmlSchemaElement(); el.Name = "root"; el.SchemaType = type; schema.Items.Add(el); schema.Compile(null); }
private XmlSchemaSimpleTypeRestriction ExtractStringFacets(JsonSchema jSchema) { XmlSchemaSimpleTypeRestriction content = new XmlSchemaSimpleTypeRestriction { BaseTypeName = new XmlQualifiedName("string", XML_SCHEMA_NS), }; EnumKeyword enumKeyword = jSchema.Get<EnumKeyword>(); if (enumKeyword != null) { foreach (JsonValue enumValue in GetterExtensions.Enum(jSchema)) { XmlSchemaEnumerationFacet enumFacet = new XmlSchemaEnumerationFacet { Value = enumValue.String, }; content.Facets.Add(enumFacet); } } MinLengthKeyword minLength = jSchema.Get<MinLengthKeyword>(); MaxLengthKeyword maxLength = jSchema.Get<MaxLengthKeyword>(); if (minLength != null && maxLength != null && minLength.Value == maxLength.Value) { // special rule that maps equal min and max lengths to xsd length facet XmlSchemaLengthFacet lengthFacet = new XmlSchemaLengthFacet { Value = minLength.Value.ToString(), }; content.Facets.Add(lengthFacet); } else { if (minLength != null) { XmlSchemaMinLengthFacet minLengthFacet = new XmlSchemaMinLengthFacet { Value = minLength.Value.ToString(), }; content.Facets.Add(minLengthFacet); } if (maxLength != null) { XmlSchemaMaxLengthFacet maxLengthFacet = new XmlSchemaMaxLengthFacet { Value = maxLength.Value.ToString(), }; content.Facets.Add(maxLengthFacet); } } PatternKeyword pattern = jSchema.Get<PatternKeyword>(); if (pattern != null) { XmlSchemaPatternFacet patternFacet = new XmlSchemaPatternFacet { Value = pattern.Value.ToString(), }; content.Facets.Add(patternFacet); } FormatKeyword format = jSchema.Get<FormatKeyword>(); if (format != null && format.Value != null && !string.IsNullOrEmpty(format.Value.Key)) { content.BaseTypeName = ExtractBaseTypeNameFromFormat(format.Value.Key); } return content; }
/// <summary> /// Processes an attribute, generating the required field and property. Potentially generates /// an enum for an attribute restriction. /// </summary> /// <param name="attribute">Attribute element being processed.</param> /// <param name="typeDeclaration">CodeTypeDeclaration to be used when outputting code.</param> /// <param name="outputXmlMethod">Member method for the OutputXml method.</param> private static void ProcessAttribute(XmlSchemaAttribute attribute, CodeTypeDeclaration typeDeclaration, CodeMemberMethod outputXmlMethod) { string attributeName = attribute.Name; string rawAttributeType = attribute.SchemaTypeName.Name; string attributeType = null; EnumDeclaration enumDeclaration = null; if (rawAttributeType == null || rawAttributeType.Length == 0) { XmlSchemaSimpleTypeRestriction simpleTypeRestriction = attribute.SchemaType.Content as XmlSchemaSimpleTypeRestriction; if (simpleTypeRestriction != null) { attributeType = String.Concat(attributeName, "Type"); bool enumRestriction = false; CodeTypeDeclaration enumTypeDeclaration = new CodeTypeDeclaration(attributeType); enumTypeDeclaration.Attributes = MemberAttributes.Public; enumTypeDeclaration.IsEnum = true; enumDeclaration = new EnumDeclaration(attributeType, enumTypeDeclaration); foreach (XmlSchemaFacet facet in simpleTypeRestriction.Facets) { XmlSchemaEnumerationFacet enumFacet = facet as XmlSchemaEnumerationFacet; if (enumFacet != null) { enumRestriction = true; string enumValue = MakeEnumValue(enumFacet.Value); enumDeclaration.AddValue(enumFacet.Value); CodeMemberField memberField = new CodeMemberField(typeof(int), enumValue); enumTypeDeclaration.Members.Add(memberField); string enumItemDocumentation = GetDocumentation(enumFacet.Annotation); if (enumItemDocumentation != null) { GenerateSummaryComment(memberField.Comments, enumItemDocumentation); } } XmlSchemaPatternFacet patternFacet = facet as XmlSchemaPatternFacet; if (patternFacet != null) { attributeType = (string)simpleTypeNamesToClrTypeNames[simpleTypeRestriction.BaseTypeName.Name]; } } if (enumRestriction) { typeDeclaration.Members.Add(enumTypeDeclaration); } else { enumDeclaration = null; } } XmlSchemaSimpleTypeList simpleTypeList = attribute.SchemaType.Content as XmlSchemaSimpleTypeList; if (simpleTypeList != null) { attributeType = simpleTypeList.ItemTypeName.Name; EnumDeclaration declaration = (EnumDeclaration)typeNamesToEnumDeclarations[attributeType]; declaration.Flags = true; } } else { attributeType = (string)simpleTypeNamesToClrTypeNames[rawAttributeType]; } string documentation = GetDocumentation(attribute.Annotation); // TODO: Handle required fields. GenerateFieldAndProperty(attributeName, attributeType, typeDeclaration, outputXmlMethod, enumDeclaration, documentation, false, false); }
static void Main(string[] args) { // Add the customer schema to a new XmlSchemaSet and compile it. // Any schema validation warnings and errors encountered reading or // compiling the schema are handled by the ValidationEventHandler delegate. XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add("http://www.tempuri.org", "customer.xsd"); schemaSet.Compile(); // Retrieve the compiled XmlSchema object from the XmlSchemaSet // by iterating over the Schemas property. XmlSchema customerSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { customerSchema = schema; } // Create the PhoneNumber element. XmlSchemaElement phoneElement = new XmlSchemaElement(); phoneElement.Name = "PhoneNumber"; // Create the xs:string simple type restriction. XmlSchemaSimpleType phoneType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // Add a pattern facet to the restriction. XmlSchemaPatternFacet phonePattern = new XmlSchemaPatternFacet(); phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)"; restriction.Facets.Add(phonePattern); // Add the restriction to the Content property of the simple type // and the simple type to the SchemaType of the PhoneNumber element. phoneType.Content = restriction; phoneElement.SchemaType = phoneType; // Iterate over each XmlSchemaElement in the Values collection // of the Elements property. foreach (XmlSchemaElement element in customerSchema.Elements.Values) { // If the qualified name of the element is "Customer", // get the complex type of the Customer element // and the sequence particle of the complex type. if (element.QualifiedName.Name.Equals("Customer")) { XmlSchemaComplexType customerType = element.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence sequence = customerType.Particle as XmlSchemaSequence; // Add the new PhoneNumber element to the sequence. sequence.Items.Add(phoneElement); } } // Reprocess and compile the modified XmlSchema object and write it to the console. schemaSet.Reprocess(customerSchema); schemaSet.Compile(); customerSchema.Write(Console.Out); }
static XmlQualifiedName AddAttributeTypeToXmlSchema(SchemaInfo schemaInfo, UxmlAttributeDescription description, IUxmlFactory factory, FactoryProcessingHelper processingData) { if (description.name == null) { return(null); } string attrTypeName = factory.uxmlQualifiedName + "_" + description.name + "_" + k_TypeSuffix; string attrTypeNameInBaseElement = factory.substituteForTypeQualifiedName + "_" + description.name + "_" + k_TypeSuffix; FactoryProcessingHelper.AttributeRecord attrRecord; if (processingData.attributeTypeNames.TryGetValue(attrTypeNameInBaseElement, out attrRecord)) { // If restriction != baseElement.restriction, we need to declare a new type. // Note: we do not support attributes having a less restrictive restriction than its base type. if ((description.restriction == null && attrRecord.desc.restriction == null) || (description.restriction != null && description.restriction.Equals(attrRecord.desc.restriction))) { // Register attrTypeName -> attrRecord for potential future derived elements. processingData.attributeTypeNames.Add(attrTypeName, attrRecord); return(attrRecord.name); } } XmlQualifiedName xqn; FactoryProcessingHelper.AttributeRecord attributeRecord; if (description.restriction == null) { // Type is a built-in type. xqn = new XmlQualifiedName(description.type, description.typeNamespace); attributeRecord = new FactoryProcessingHelper.AttributeRecord { name = xqn, desc = description }; processingData.attributeTypeNames.Add(attrTypeName, attributeRecord); return(xqn); } string attrTypeNameForSchema = factory.uxmlName + "_" + description.name + "_" + k_TypeSuffix; xqn = new XmlQualifiedName(attrTypeNameForSchema, schemaInfo.schema.TargetNamespace); XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType(); simpleType.Name = attrTypeNameForSchema; UxmlEnumeration enumRestriction = description.restriction as UxmlEnumeration; if (enumRestriction != null) { XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); simpleType.Content = restriction; restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); foreach (var v in enumRestriction.values) { XmlSchemaEnumerationFacet enumValue = new XmlSchemaEnumerationFacet(); enumValue.Value = v; restriction.Facets.Add(enumValue); } } else { UxmlValueMatches regexRestriction = description.restriction as UxmlValueMatches; if (regexRestriction != null) { XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); simpleType.Content = restriction; restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); XmlSchemaPatternFacet pattern = new XmlSchemaPatternFacet(); pattern.Value = regexRestriction.regex; restriction.Facets.Add(pattern); } else { UxmlValueBounds bounds = description.restriction as UxmlValueBounds; if (bounds != null) { XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); simpleType.Content = restriction; restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); XmlSchemaFacet facet; if (bounds.excludeMin) { facet = new XmlSchemaMinExclusiveFacet(); } else { facet = new XmlSchemaMinInclusiveFacet(); } facet.Value = bounds.min; restriction.Facets.Add(facet); if (bounds.excludeMax) { facet = new XmlSchemaMaxExclusiveFacet(); } else { facet = new XmlSchemaMaxInclusiveFacet(); } facet.Value = bounds.max; restriction.Facets.Add(facet); } else { Debug.Log("Unsupported restriction type."); } } } schemaInfo.schema.Items.Add(simpleType); attributeRecord = new FactoryProcessingHelper.AttributeRecord { name = xqn, desc = description }; processingData.attributeTypeNames.Add(attrTypeName, attributeRecord); return(xqn); }
static TypeTranslator() { nameCache = new Hashtable(); primitiveArrayTypes = Hashtable.Synchronized(new Hashtable()); #if !TARGET_JVM nameCache = Hashtable.Synchronized(nameCache); #endif // XSD Types with direct map to CLR types nameCache.Add(typeof(bool), new TypeData(typeof(bool), "boolean", true)); nameCache.Add(typeof(short), new TypeData(typeof(short), "short", true)); nameCache.Add(typeof(ushort), new TypeData(typeof(ushort), "unsignedShort", true)); nameCache.Add(typeof(int), new TypeData(typeof(int), "int", true)); nameCache.Add(typeof(uint), new TypeData(typeof(uint), "unsignedInt", true)); nameCache.Add(typeof(long), new TypeData(typeof(long), "long", true)); nameCache.Add(typeof(ulong), new TypeData(typeof(ulong), "unsignedLong", true)); nameCache.Add(typeof(float), new TypeData(typeof(float), "float", true)); nameCache.Add(typeof(double), new TypeData(typeof(double), "double", true)); nameCache.Add(typeof(DateTime), new TypeData(typeof(DateTime), "dateTime", true)); // TODO: timeInstant, Xml date, xml time nameCache.Add(typeof(decimal), new TypeData(typeof(decimal), "decimal", true)); nameCache.Add(typeof(XmlQualifiedName), new TypeData(typeof(XmlQualifiedName), "QName", true)); nameCache.Add(typeof(string), new TypeData(typeof(string), "string", true)); #if !MOONLIGHT XmlSchemaPatternFacet guidFacet = new XmlSchemaPatternFacet(); guidFacet.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; nameCache.Add(typeof(Guid), new TypeData(typeof(Guid), "guid", true, (TypeData)nameCache[typeof(string)], guidFacet)); #endif nameCache.Add(typeof(byte), new TypeData(typeof(byte), "unsignedByte", true)); nameCache.Add(typeof(sbyte), new TypeData(typeof(sbyte), "byte", true)); nameCache.Add(typeof(char), new TypeData(typeof(char), "char", true, (TypeData)nameCache[typeof(ushort)], null)); nameCache.Add(typeof(object), new TypeData(typeof(object), "anyType", false)); nameCache.Add(typeof(byte[]), new TypeData(typeof(byte[]), "base64Binary", true)); #if !MOONLIGHT nameCache.Add(typeof(XmlNode), new TypeData(typeof(XmlNode), "XmlNode", false)); nameCache.Add(typeof(XmlElement), new TypeData(typeof(XmlElement), "XmlElement", false)); #endif primitiveTypes = new Hashtable(); ICollection types = nameCache.Values; foreach (TypeData td in types) { primitiveTypes.Add(td.XmlType, td); } // Additional XSD types primitiveTypes.Add("date", new TypeData(typeof(DateTime), "date", true)); // TODO: timeInstant primitiveTypes.Add("time", new TypeData(typeof(DateTime), "time", true)); primitiveTypes.Add("timePeriod", new TypeData(typeof(DateTime), "timePeriod", true)); primitiveTypes.Add("gDay", new TypeData(typeof(string), "gDay", true)); primitiveTypes.Add("gMonthDay", new TypeData(typeof(string), "gMonthDay", true)); primitiveTypes.Add("gYear", new TypeData(typeof(string), "gYear", true)); primitiveTypes.Add("gYearMonth", new TypeData(typeof(string), "gYearMonth", true)); primitiveTypes.Add("month", new TypeData(typeof(DateTime), "month", true)); primitiveTypes.Add("NMTOKEN", new TypeData(typeof(string), "NMTOKEN", true)); primitiveTypes.Add("NMTOKENS", new TypeData(typeof(string), "NMTOKENS", true)); primitiveTypes.Add("Name", new TypeData(typeof(string), "Name", true)); primitiveTypes.Add("NCName", new TypeData(typeof(string), "NCName", true)); primitiveTypes.Add("language", new TypeData(typeof(string), "language", true)); primitiveTypes.Add("integer", new TypeData(typeof(string), "integer", true)); primitiveTypes.Add("positiveInteger", new TypeData(typeof(string), "positiveInteger", true)); primitiveTypes.Add("nonPositiveInteger", new TypeData(typeof(string), "nonPositiveInteger", true)); primitiveTypes.Add("negativeInteger", new TypeData(typeof(string), "negativeInteger", true)); primitiveTypes.Add("nonNegativeInteger", new TypeData(typeof(string), "nonNegativeInteger", true)); primitiveTypes.Add("ENTITIES", new TypeData(typeof(string), "ENTITIES", true)); primitiveTypes.Add("ENTITY", new TypeData(typeof(string), "ENTITY", true)); primitiveTypes.Add("hexBinary", new TypeData(typeof(byte[]), "hexBinary", true)); primitiveTypes.Add("ID", new TypeData(typeof(string), "ID", true)); primitiveTypes.Add("IDREF", new TypeData(typeof(string), "IDREF", true)); primitiveTypes.Add("IDREFS", new TypeData(typeof(string), "IDREFS", true)); primitiveTypes.Add("NOTATION", new TypeData(typeof(string), "NOTATION", true)); primitiveTypes.Add("token", new TypeData(typeof(string), "token", true)); primitiveTypes.Add("normalizedString", new TypeData(typeof(string), "normalizedString", true)); primitiveTypes.Add("anyURI", new TypeData(typeof(string), "anyURI", true)); primitiveTypes.Add("base64", new TypeData(typeof(byte[]), "base64", true)); primitiveTypes.Add("duration", new TypeData(typeof(string), "duration", true)); #if NET_2_0 nullableTypes = Hashtable.Synchronized(new Hashtable()); foreach (DictionaryEntry de in primitiveTypes) { TypeData td = (TypeData)de.Value; TypeData ntd = new TypeData(td.Type, td.XmlType, true); ntd.IsNullable = true; nullableTypes.Add(de.Key, ntd); } #endif }
public static IEnumerable <XmlSchemaFacet> createXmlFacets(IEnumerable <ICctsFacet> facets) { var xmlFacets = new List <XmlSchemaFacet>(); foreach (var facet in facets) { XmlSchemaFacet xmlFacet = null; switch (facet.name) { case "fractionDigit": xmlFacet = new XmlSchemaFractionDigitsFacet(); break; case "length": xmlFacet = new XmlSchemaLengthFacet(); break; case "maxExclusive": xmlFacet = new XmlSchemaMaxExclusiveFacet(); break; case "maxInclusive": xmlFacet = new XmlSchemaMaxInclusiveFacet(); break; case "maxLength": xmlFacet = new XmlSchemaMaxLengthFacet(); break; case "minExclusive": xmlFacet = new XmlSchemaMinExclusiveFacet(); break; case "minInclusive": xmlFacet = new XmlSchemaMinInclusiveFacet(); break; case "minLength": xmlFacet = new XmlSchemaMinLengthFacet(); break; case "pattern": xmlFacet = new XmlSchemaPatternFacet(); break; case "totalDigits": xmlFacet = new XmlSchemaTotalDigitsFacet(); break; case "whiteSpace": xmlFacet = new XmlSchemaWhiteSpaceFacet(); break; case "enumeration": foreach (var enumValue in facet.content.Split('|')) { var enumerationFacet = new XmlSchemaEnumerationFacet(); enumerationFacet.Value = enumValue; xmlFacets.Add(enumerationFacet); } break; } if (xmlFacet != null) { xmlFacet.Value = facet.content; xmlFacets.Add(xmlFacet); } } return(xmlFacets); }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="ZipCodeType"> XmlSchemaSimpleType ZipCodeType = new XmlSchemaSimpleType(); ZipCodeType.Name = "ZipCodeType"; // <xs:restriction base="xs:string"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:pattern value="[0-9]{5}(-[0-9]{4})?"/> XmlSchemaPatternFacet pattern = new XmlSchemaPatternFacet(); pattern.Value = "[0-9]{5}(-[0-9]{4})?"; restriction.Facets.Add(pattern); ZipCodeType.Content = restriction; schema.Items.Add(ZipCodeType); // <xs:element name="Address"> XmlSchemaElement element = new XmlSchemaElement(); element.Name = "Address"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="ZipCode" type="ZipCodeType"/> XmlSchemaAttribute ZipCodeAttribute = new XmlSchemaAttribute(); ZipCodeAttribute.Name = "ZipCode"; ZipCodeAttribute.SchemaTypeName = new XmlQualifiedName("ZipCodeType", ""); complexType.Attributes.Add(ZipCodeAttribute); element.SchemaType = complexType; schema.Items.Add(element); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
protected virtual void Visit(XmlSchemaPatternFacet facet) { }
/// <summary> /// Render field-criteria such as max length and patterns. /// </summary> /// <param name="restrictions">XSD restriction object to receive the facets.</param> /// <param name="fieldEntity">The field being described.</param> /// <param name="fieldTypeAlias">The XSD type string for the field type. E.g. 'string'.</param> private void AddFieldRestrictions(XmlSchemaSimpleTypeRestriction restrictions, Entity fieldEntity, string fieldTypeAlias) { switch (fieldTypeAlias) { // Int constraints case "intField": int?minValue = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MinInt); if (minValue != null) { var minFacet = new XmlSchemaMinInclusiveFacet() { Value = minValue.ToString() }; restrictions.Facets.Add(minFacet); } int?maxValue = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MaxInt); if (maxValue != null) { var maxFacet = new XmlSchemaMaxInclusiveFacet() { Value = maxValue.ToString() }; restrictions.Facets.Add(maxFacet); } break; // String constraints case "stringField": int?minLength = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MinLength); if (minLength != null) { var minFacet = new XmlSchemaMinLengthFacet() { Value = minLength.ToString() }; restrictions.Facets.Add(minFacet); } int?maxLength = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MaxLength); if (maxLength != null) { var maxFacet = new XmlSchemaMaxLengthFacet() { Value = maxLength.ToString() }; restrictions.Facets.Add(maxFacet); } var stringPattern = _schemaManager.GetRelationshipsFromEntity(fieldEntity, A(Aliases2.Pattern)).FirstOrDefault(); if (stringPattern != null) { string sRegex = _schemaManager.GetStringFieldValue(stringPattern, Aliases2.Regex); if (sRegex != null) { var regexFacet = new XmlSchemaPatternFacet() { Value = sRegex }; restrictions.Facets.Add(regexFacet); } } break; // String constraints case "aliasField": // optional namespace prefix, followed by lower-case alpha, alphanumeric string aliasRegex = @"([_a-zA-Z][_a-zA-Z0-9]*\:)?[_a-zA-Z][_a-zA-Z0-9]{0,99}"; var aliasRegexFacet = new XmlSchemaPatternFacet() { Value = aliasRegex }; restrictions.Facets.Add(aliasRegexFacet); break; } }
protected override void Visit(XmlSchemaPatternFacet facet) { AddLeaf(SimpleTypeStructureNodeType.FacetPattern, facet); }