public XmlSchemaElement GetSchema()
        {
            var type = new XmlSchemaComplexType();

            type.Attributes.Add(new XmlSchemaAttribute
                                    {
                                        Name = "refValue",
                                        Use = XmlSchemaUse.Required,
                                        SchemaTypeName =
                                            new XmlQualifiedName("positiveInteger", "http://www.w3.org/2001/XMLSchema")
                                    });

            type.Attributes.Add(new XmlSchemaAttribute
                                    {
                                        Name = "test",
                                        Use = XmlSchemaUse.Optional,
                                        SchemaTypeName =
                                            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
                                    });

            
            var restriction = new XmlSchemaSimpleTypeRestriction
                                  {
                                      BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
                                  };

            restriction.Facets.Add(new XmlSchemaEnumerationFacet {Value = "years"});
            restriction.Facets.Add(new XmlSchemaEnumerationFacet {Value = "weeks"});
            restriction.Facets.Add(new XmlSchemaEnumerationFacet {Value = "days"});

            var simpleType = new XmlSchemaSimpleType {Content = restriction};


            type.Attributes.Add(new XmlSchemaAttribute
                                    {
                                        Name = "units",
                                        Use = XmlSchemaUse.Required,
                                        SchemaType = simpleType
                                    });


            type.Attributes.Add(new XmlSchemaAttribute
                                    {
                                        Name = "expressionLanguage",
                                        Use = XmlSchemaUse.Optional,
                                        SchemaTypeName =
                                            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
                                    });

            var element = new XmlSchemaElement
                              {
                                  Name = "dicom-age-less-than",
                                  SchemaType = type
                              };

            return element;
        }
Esempio n. 2
0
    private void CreateSimpletypeLength(string length, string minLength, string maxLength, bool expected) {
      passed = true;

      XmlSchema schema = new XmlSchema();

      XmlSchemaSimpleType testType = new XmlSchemaSimpleType();
      testType.Name = "TestType";

      XmlSchemaSimpleTypeRestriction testTypeRestriction = new XmlSchemaSimpleTypeRestriction();
      testTypeRestriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

      if (length != "-") {
        XmlSchemaLengthFacet _length = new XmlSchemaLengthFacet();
        _length.Value = length;
        testTypeRestriction.Facets.Add(_length);
      }
      if (minLength != "-") {
        XmlSchemaMinLengthFacet _minLength = new XmlSchemaMinLengthFacet();
        _minLength.Value = minLength;
        testTypeRestriction.Facets.Add(_minLength);
      }
      if (maxLength != "-") {
        XmlSchemaMaxLengthFacet _maxLength = new XmlSchemaMaxLengthFacet();
        _maxLength.Value = maxLength;
        testTypeRestriction.Facets.Add(_maxLength);
      }

      testType.Content = testTypeRestriction;
      schema.Items.Add(testType);
      schema.Compile(new ValidationEventHandler(ValidationCallbackOne));

      Assert.IsTrue (expected == passed, (passed ? "Test passed, should have failed" : "Test failed, should have passed") + ": " + length + " " + minLength + " " + maxLength);
      
    }
        /// <summary>
        /// Create an XmlQueryType from an Xsd simple type (where variety can be Atomic, List, or Union).
        /// </summary>
        /// <param name="schemaType">the simple Xsd schema type of the atomic value</param>
        /// <param name="isStrict">true if the dynamic type is guaranteed to match the static type exactly</param>
        /// <returns>the atomic value type</returns>
        public static XmlQueryType Type(XmlSchemaSimpleType schemaType, bool isStrict) {
            if (schemaType.Datatype.Variety == XmlSchemaDatatypeVariety.Atomic) {
                // We must special-case xs:anySimpleType because it is broken in Xsd and is sometimes treated as
                // an atomic value and sometimes as a list value.  In XQuery, it always maps to xdt:anyAtomicType*.
                if (schemaType == DatatypeImplementation.AnySimpleType)
                    return AnyAtomicTypeS;

                return ItemType.Create(schemaType, isStrict);
            }

            // Skip restrictions. It is safe to do that because this is a list or union, so it's not a build in type
            while (schemaType.DerivedBy == XmlSchemaDerivationMethod.Restriction)
                schemaType = (XmlSchemaSimpleType) schemaType.BaseXmlSchemaType;

            // Convert Xsd list
            if (schemaType.DerivedBy == XmlSchemaDerivationMethod.List)
                return PrimeProduct(Type(((XmlSchemaSimpleTypeList) schemaType.Content).BaseItemType, isStrict), XmlQueryCardinality.ZeroOrMore);

            // Convert Xsd union
            Debug.Assert(schemaType.DerivedBy == XmlSchemaDerivationMethod.Union);
            XmlSchemaSimpleType[] baseMemberTypes = ((XmlSchemaSimpleTypeUnion) schemaType.Content).BaseMemberTypes;
            XmlQueryType[] queryMemberTypes = new XmlQueryType[baseMemberTypes.Length];

            for (int i = 0; i < baseMemberTypes.Length; i++)
                queryMemberTypes[i] = Type(baseMemberTypes[i], isStrict);

            return Choice(queryMemberTypes);
        }
Esempio n. 4
0
        private QName InferMergedType(string value, QName typeName)
        {
            // examine value against specified type and
            // if unacceptable, then return a relaxed type.

            SimpleType st = XmlSchemaType.GetBuiltInSimpleType(
                typeName);

            if (st == null)             // non-primitive type => see above.
            {
                return(QNameString);
            }
            do
            {
                try {
                    st.Datatype.ParseValue(value,
                                           source.NameTable,
                                           source as IXmlNamespaceResolver);
                    return(typeName);
                } catch {
                    st       = st.BaseXmlSchemaType as XmlSchemaSimpleType;
                    typeName = st != null ? st.QualifiedName : QName.Empty;
                }
            } while (typeName != QName.Empty);
            return(QNameString);
        }
 protected override void Visit(XmlSchemaSimpleType type)
 {
     if (type.QualifiedName.IsEmpty)
         Traverse(type.Content);
     else
         AddLeaf(SimpleTypeStructureNodeType.NamedType, type);
 }
 internal XmlNameEx(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) : base(prefix, localName, ns, hashCode, ownerDoc, next)
 {
     this.SetValidity(schemaInfo.Validity);
     this.SetIsDefault(schemaInfo.IsDefault);
     this.SetIsNil(schemaInfo.IsNil);
     this.memberType = schemaInfo.MemberType;
     this.schemaType = schemaInfo.SchemaType;
     this.decl = (schemaInfo.SchemaElement != null) ? ((object) schemaInfo.SchemaElement) : ((object) schemaInfo.SchemaAttribute);
 }
 internal void Clear()
 {
     this.isNil = false;
     this.isDefault = false;
     this.schemaType = null;
     this.schemaElement = null;
     this.schemaAttribute = null;
     this.memberType = null;
     this.validity = XmlSchemaValidity.NotKnown;
     this.contentType = XmlSchemaContentType.Empty;
 }
Esempio n. 8
0
        private XmlSchemaSimpleType CreateGuidType()
        {
            var type = new XmlSchemaSimpleType { Name = "Guid" };

            var restriction = new XmlSchemaSimpleTypeRestriction { BaseType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String) };
            restriction.Facets.Add(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|\(loc|\(wix)\.[_A-Za-z][0-9A-Za-z_.]*\)"
            });
            type.Content = restriction;
            return type;
        }
        public override void FixtureInit()
        {
            XmlSchemaCompletionDataCollection schemas = new XmlSchemaCompletionDataCollection();
            schemas.Add(SchemaCompletionData);
            XmlSchemaCompletionData xsdSchemaCompletionData = new XmlSchemaCompletionData(ResourceManager.GetXsdSchema());
            schemas.Add(xsdSchemaCompletionData);
            XmlCompletionDataProvider provider = new XmlCompletionDataProvider(schemas, xsdSchemaCompletionData, String.Empty);

            string xml = GetSchema();
            int index = xml.IndexOf("type=\"dir\"/>");
            index = xml.IndexOf("dir", index);
            schemaSimpleType = (XmlSchemaSimpleType)XmlView.GetSchemaObjectSelected(xml, index, provider, SchemaCompletionData);
        }
        public override void FixtureInit()
        {
            XmlSchemaCompletionCollection schemas = new XmlSchemaCompletionCollection();
            schemas.Add(SchemaCompletion);
            XmlSchemaCompletion xsdSchemaCompletionData = new XmlSchemaCompletion(ResourceManager.ReadXsdSchema());
            schemas.Add(xsdSchemaCompletionData);

            string xml = GetSchema();
            int index = xml.IndexOf("type=\"dir\"/>");
            index = xml.IndexOf("dir", index);
            XmlSchemaDefinition schemaDefinition = new XmlSchemaDefinition(schemas, SchemaCompletion);
            schemaSimpleType = (XmlSchemaSimpleType)schemaDefinition.GetSelectedSchemaObject(xml, index);
        }
Esempio n. 11
0
        private SimpleType MakeBaseTypeAsEmptiable(SimpleType st)
        {
            switch (st.QualifiedName.Namespace)
            {
            case XmlSchema.Namespace:
            case XdtNamespace:
                // If a primitive type
                return(XmlSchemaType.GetBuiltInSimpleType(
                           XmlTypeCode.String));
            }
            SimpleTypeRst str = st.Content as SimpleTypeRst;

            if (str != null)
            {
                ArrayList al = null;
                foreach (SchemaFacet f in str.Facets)
                {
                    if (f is LengthFacet ||
                        f is MinLengthFacet)
                    {
                        if (al == null)
                        {
                            al = new ArrayList();
                        }
                        al.Add(f);
                    }
                }
                foreach (SchemaFacet f in al)
                {
                    str.Facets.Remove(f);
                }
                if (str.BaseType != null)
                {
                    str.BaseType =
                        MakeBaseTypeAsEmptiable(st);
                }
                else
                {
                    // It might have a reference to an
                    // external simple type, but there is
                    // no assurance that any of those
                    // external types allow an empty
                    // string. So just set base type as
                    // xs:string.
                    str.BaseTypeName = QNameString;
                }
            }             // union/list can have empty string value.

            return(st);
        }
Esempio n. 12
0
        protected override void Visit(XmlSchemaSimpleType type)
        {
            if (type.QualifiedName.IsEmpty)
                base.Visit(type);
            else
            {
                if (!AddUsage(type))
                    return;

                PushNamedObject(type);
                base.Visit(type);
                PopNamedObject();
            }
        }
        public static XmlSchemaSimpleType ResolveType(this XmlSchemaSet schemaSet, XmlSchemaSimpleType type, XmlQualifiedName typeName)
        {
            if (type != null)
                return type;

            var resolvedType = schemaSet.GlobalTypes[typeName] as XmlSchemaSimpleType;
            if (resolvedType != null)
                return resolvedType;

            var builtInSimpleType = XmlSchemaType.GetBuiltInSimpleType(typeName);
            if (builtInSimpleType != null)
                return builtInSimpleType;

            return null;
        }
 private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType)
 {
     if ((dataType.Name != null) && (dataType.Name.Length != 0))
     {
         TypeDesc typeDesc = base.Scope.GetTypeDesc(dataType);
         if (typeDesc != null)
         {
             return typeDesc;
         }
     }
     if (!dataType.DerivedFrom.IsEmpty)
     {
         return this.GetDataTypeSource(this.FindDataType(dataType.DerivedFrom));
     }
     return base.Scope.GetTypeDesc(typeof(string));
 }
Esempio n. 15
0
        private void InferAsEmptyElement(Element el, string ns,
                                         bool isNew)
        {
            ComplexType ct = el.SchemaType as ComplexType;

            if (ct != null)
            {
                SimpleModel sm =
                    ct.ContentModel as SimpleModel;
                if (sm != null)
                {
                    ToEmptiableSimpleContent(sm, isNew);
                    return;
                }

                ComplexModel cm = ct.ContentModel
                                  as ComplexModel;
                if (cm != null)
                {
                    ToEmptiableComplexContent(cm, isNew);
                    return;
                }

                if (ct.Particle != null)
                {
                    ct.Particle.MinOccurs = 0;
                }
                return;
            }
            SimpleType st = el.SchemaType as SimpleType;

            if (st != null)
            {
                st = MakeBaseTypeAsEmptiable(st);
                switch (st.QualifiedName.Namespace)
                {
                case XmlSchema.Namespace:
                case XdtNamespace:
                    el.SchemaTypeName = st.QualifiedName;
                    break;

                default:
                    el.SchemaType = st;
                    break;
                }
            }
        }
 internal SimpleType(XmlSchemaSimpleType node)
 {
     this.name = "";
     this.length = -1;
     this.minLength = -1;
     this.maxLength = -1;
     this.pattern = "";
     this.ns = "";
     this.maxExclusive = "";
     this.maxInclusive = "";
     this.minExclusive = "";
     this.minInclusive = "";
     this.enumeration = "";
     this.name = node.Name;
     this.ns = (node.QualifiedName != null) ? node.QualifiedName.Namespace : "";
     this.LoadTypeValues(node);
 }
Esempio n. 17
0
        /// <summary>
        /// Register a simple type in this schema object
        /// </summary>
        /// <param name="type">The simple type to register</param>
        protected void RegisterSimpleType(System.Xml.Schema.XmlSchemaSimpleType type)
        {
            if (types == null)
            {
                types = new List <XmlSchemaType>();
            }

            if (FindType(type.Name) != null)
            {
                return;                              // Already registered
            }
            // Now create a type
            XmlSchemaSimpleType simp = new XmlSchemaSimpleType(this, null);

            simp.Load(type);

            // Finally, add
            types.Add(simp);
            typesDirty = true;
        }
 private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags)
 {
     XmlSchemaSimpleType dataType = new XmlSchemaSimpleType {
         Name = dataTypeName
     };
     XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction {
         BaseTypeName = baseTypeName
     };
     foreach (XmlSchemaFacet facet in facets)
     {
         restriction.Facets.Add(facet);
     }
     dataType.Content = restriction;
     TypeDesc desc = new TypeDesc(type, false, dataType, formatterName, flags);
     if (primitiveTypes[type] == null)
     {
         primitiveTypes.Add(type, desc);
     }
     primitiveDataTypes.Add(dataType, desc);
     primitiveNames.Add(dataTypeName, ns, desc);
 }
Esempio n. 19
0
 string CreateProtoSimpleType(XmlSchemaSimpleType simpleType) {
     if (simpleType.QualifiedName.Namespace == XmlSchema.Namespace) {
         return CreateProtoXsdType(simpleType.QualifiedName.Name);
     } else if ((simpleType.Content as XmlSchemaSimpleTypeRestriction) != null) {
         var facets = (simpleType.Content as XmlSchemaSimpleTypeRestriction).Facets.OfType<XmlSchemaFacet>();
         foreach (var facet in facets) {
             if ((facet as XmlSchemaEnumerationFacet) != null) {
                 return (facet as XmlSchemaEnumerationFacet).Value;
             } else if ((facet as XmlSchemaMinInclusiveFacet) != null) {
                 return (facet as XmlSchemaMinInclusiveFacet).Value;
             } else if ((facet as XmlSchemaMaxLengthFacet) != null) {
                 return (facet as XmlSchemaMaxLengthFacet).Value;
             }
         }
         throw new Exception("not implemented");
     } else if ((simpleType.Content as XmlSchemaSimpleTypeUnion) != null) {
         return CreateProtoSimpleType((simpleType.Content as XmlSchemaSimpleTypeUnion).BaseMemberTypes.First());
     } else {
         throw new Exception("not implemented");
     }
 }
Esempio n. 20
0
        void SetupSimpleTypeWrappers()
        {
            XmlSchema    schema = new XmlSchema();
            List <QName> qnames = new List <QName> ();

            foreach (string name in allTypes)
            {
                SimpleType st = new SimpleType();
                st.Name = "x-" + name;
                SimpleRest r = new SimpleRest();
                st.Content = r;
                QName qname = new QName(name, XmlSchema.Namespace);
                r.BaseTypeName = qname;
                qnames.Add(qname);
                schema.Items.Add(st);
            }
            XmlSchemaSet sset = new XmlSchemaSet();

            sset.Add(schema);
            sset.Compile();
            allWrappers = sset;
        }
Esempio n. 21
0
        /// <summary>
        ///     Returns a SimpleType restricted by the datatype only
        /// </summary>
        public override XmlSchemaSimpleType GetSimpleType(string attributeDataType)
        {
            var retVal = new XmlSchemaSimpleType();

            // <xs:restriction base="<whatever xs:datatype is required>" />
            var dataTypeRestriction = new XmlSchemaSimpleTypeRestriction
            {
                BaseTypeName = new XmlQualifiedName(attributeDataType)
            };
            retVal.Content = dataTypeRestriction;

            //  if the property type is an enum then add an enumeration facet to the simple type
            if (Property.PropertyType.IsEnum)
            {
                // <xs:enumeration value="123" />
                foreach (var enumValue in Enum.GetNames(Property.PropertyType))
                {
                    var enumFacet = new XmlSchemaEnumerationFacet { Value = enumValue };
                    dataTypeRestriction.Facets.Add(enumFacet);
                }
            }

            return retVal;
        }
//<redefine
//  id = ID
//  schemaLocation = anyURI
//  {any attributes with non-schema namespace . . .}>
//  Content: (annotation | (simpleType | complexType | group | attributeGroup))*
//</redefine>
        internal static XmlSchemaRedefine Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaRedefine redefine = new XmlSchemaRedefine();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaRedefine.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }

            redefine.LineNumber   = reader.LineNumber;
            redefine.LinePosition = reader.LinePosition;
            redefine.SourceUri    = reader.BaseURI;

            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    redefine.Id = reader.Value;
                }
                else if (reader.Name == "schemaLocation")
                {
                    redefine.SchemaLocation = reader.Value;
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for redefine", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, redefine);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(redefine);
            }

            //(annotation | (simpleType | complexType | group | attributeGroup))*
            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaRedefine.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (reader.LocalName == "annotation")
                {
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        redefine.items.Add(annotation);
                    }
                    continue;
                }
                if (reader.LocalName == "simpleType")
                {
                    XmlSchemaSimpleType simpleType = XmlSchemaSimpleType.Read(reader, h);
                    if (simpleType != null)
                    {
                        redefine.items.Add(simpleType);
                    }
                    continue;
                }
                if (reader.LocalName == "complexType")
                {
                    XmlSchemaComplexType complexType = XmlSchemaComplexType.Read(reader, h);
                    if (complexType != null)
                    {
                        redefine.items.Add(complexType);
                    }
                    continue;
                }
                if (reader.LocalName == "group")
                {
                    XmlSchemaGroup group = XmlSchemaGroup.Read(reader, h);
                    if (group != null)
                    {
                        redefine.items.Add(group);
                    }
                    continue;
                }
                if (reader.LocalName == "attributeGroup")
                {
                    XmlSchemaAttributeGroup attributeGroup = XmlSchemaAttributeGroup.Read(reader, h);
                    if (attributeGroup != null)
                    {
                        redefine.items.Add(attributeGroup);
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(redefine);
        }
        //<restriction
        //base = QName
        //id = ID
        //{any attributes with non-schema namespace . . .}>
        //Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)?, ((attribute | attributeGroup)*, anyAttribute?))
        //</restriction>
        internal static XmlSchemaSimpleContentRestriction Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleContentRestriction restriction = new XmlSchemaSimpleContentRestriction();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaComplexContentRestriction.Read, name=" + reader.Name, null);
                reader.SkipToEnd();
                return(null);
            }

            restriction.LineNumber   = reader.LineNumber;
            restriction.LinePosition = reader.LinePosition;
            restriction.SourceUri    = reader.BaseURI;

            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "base")
                {
                    Exception innerex;
                    restriction.baseTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for base attribute", innerex);
                    }
                }
                else if (reader.Name == "id")
                {
                    restriction.Id = reader.Value;
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for restriction", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, restriction);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(restriction);
            }

            //Content:  1.annotation?,
            //		    2.simpleType?,
            //			3.(minExclusive |...| enumeration | whiteSpace | pattern)*,
            //			4.(attribute | attributeGroup)*,
            //			5.anyAttribute?
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaSimpleContentRestriction.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2; //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        restriction.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2 && reader.LocalName == "simpleType")
                {
                    level = 3;
                    XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h);
                    if (stype != null)
                    {
                        restriction.baseType = stype;
                    }
                    continue;
                }
                if (level <= 3)
                {
                    if (reader.LocalName == "minExclusive")
                    {
                        level = 3;
                        XmlSchemaMinExclusiveFacet minex = XmlSchemaMinExclusiveFacet.Read(reader, h);
                        if (minex != null)
                        {
                            restriction.facets.Add(minex);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "minInclusive")
                    {
                        level = 3;
                        XmlSchemaMinInclusiveFacet mini = XmlSchemaMinInclusiveFacet.Read(reader, h);
                        if (mini != null)
                        {
                            restriction.facets.Add(mini);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "maxExclusive")
                    {
                        level = 3;
                        XmlSchemaMaxExclusiveFacet maxex = XmlSchemaMaxExclusiveFacet.Read(reader, h);
                        if (maxex != null)
                        {
                            restriction.facets.Add(maxex);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "maxInclusive")
                    {
                        level = 3;
                        XmlSchemaMaxInclusiveFacet maxi = XmlSchemaMaxInclusiveFacet.Read(reader, h);
                        if (maxi != null)
                        {
                            restriction.facets.Add(maxi);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "totalDigits")
                    {
                        level = 3;
                        XmlSchemaTotalDigitsFacet total = XmlSchemaTotalDigitsFacet.Read(reader, h);
                        if (total != null)
                        {
                            restriction.facets.Add(total);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "fractionDigits")
                    {
                        level = 3;
                        XmlSchemaFractionDigitsFacet fraction = XmlSchemaFractionDigitsFacet.Read(reader, h);
                        if (fraction != null)
                        {
                            restriction.facets.Add(fraction);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "length")
                    {
                        level = 3;
                        XmlSchemaLengthFacet length = XmlSchemaLengthFacet.Read(reader, h);
                        if (length != null)
                        {
                            restriction.facets.Add(length);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "minLength")
                    {
                        level = 3;
                        XmlSchemaMinLengthFacet minlen = XmlSchemaMinLengthFacet.Read(reader, h);
                        if (minlen != null)
                        {
                            restriction.facets.Add(minlen);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "maxLength")
                    {
                        level = 3;
                        XmlSchemaMaxLengthFacet maxlen = XmlSchemaMaxLengthFacet.Read(reader, h);
                        if (maxlen != null)
                        {
                            restriction.facets.Add(maxlen);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "enumeration")
                    {
                        level = 3;
                        XmlSchemaEnumerationFacet enumeration = XmlSchemaEnumerationFacet.Read(reader, h);
                        if (enumeration != null)
                        {
                            restriction.facets.Add(enumeration);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "whiteSpace")
                    {
                        level = 3;
                        XmlSchemaWhiteSpaceFacet ws = XmlSchemaWhiteSpaceFacet.Read(reader, h);
                        if (ws != null)
                        {
                            restriction.facets.Add(ws);
                        }
                        continue;
                    }
                    else if (reader.LocalName == "pattern")
                    {
                        level = 3;
                        XmlSchemaPatternFacet pattern = XmlSchemaPatternFacet.Read(reader, h);
                        if (pattern != null)
                        {
                            restriction.facets.Add(pattern);
                        }
                        continue;
                    }
                }
                if (level <= 4)
                {
                    if (reader.LocalName == "attribute")
                    {
                        level = 4;
                        XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader, h);
                        if (attr != null)
                        {
                            restriction.Attributes.Add(attr);
                        }
                        continue;
                    }
                    if (reader.LocalName == "attributeGroup")
                    {
                        level = 4;
                        XmlSchemaAttributeGroupRef attr = XmlSchemaAttributeGroupRef.Read(reader, h);
                        if (attr != null)
                        {
                            restriction.attributes.Add(attr);
                        }
                        continue;
                    }
                }
                if (level <= 5 && reader.LocalName == "anyAttribute")
                {
                    level = 6;
                    XmlSchemaAnyAttribute anyattr = XmlSchemaAnyAttribute.Read(reader, h);
                    if (anyattr != null)
                    {
                        restriction.AnyAttribute = anyattr;
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(restriction);
        }
Esempio n. 24
0
        //<simpleType
        //  final = (#all | (list | union | restriction))
        //  id = ID
        //  name = NCName
        //  {any attributes with non-schema namespace . . .}>
        //  Content: (annotation?, (restriction | list | union))
        //</simpleType>
        internal static XmlSchemaSimpleType Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleType stype = new XmlSchemaSimpleType();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaGroup.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }

            stype.LineNumber   = reader.LineNumber;
            stype.LinePosition = reader.LinePosition;
            stype.SourceUri    = reader.BaseURI;

            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "final")
                {
                    Exception innerex;
                    stype.Final = XmlSchemaUtil.ReadDerivationAttribute(reader, out innerex, "final",
                                                                        XmlSchemaUtil.FinalAllowed);
                    if (innerex != null)
                    {
                        error(h, "some invalid values not a valid value for final", innerex);
                    }
                }
                else if (reader.Name == "id")
                {
                    stype.Id = reader.Value;
                }
                else if (reader.Name == "name")
                {
                    stype.Name = reader.Value;
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for simpleType", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, stype);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(stype);
            }

            //	Content: (annotation?, (restriction | list | union))
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaSimpleType.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2; //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        stype.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2)
                {
                    if (reader.LocalName == "restriction")
                    {
                        level = 3;
                        XmlSchemaSimpleTypeRestriction restriction = XmlSchemaSimpleTypeRestriction.Read(reader, h);
                        if (restriction != null)
                        {
                            stype.content = restriction;
                        }
                        continue;
                    }
                    if (reader.LocalName == "list")
                    {
                        level = 3;
                        XmlSchemaSimpleTypeList list = XmlSchemaSimpleTypeList.Read(reader, h);
                        if (list != null)
                        {
                            stype.content = list;
                        }
                        continue;
                    }
                    if (reader.LocalName == "union")
                    {
                        level = 3;
                        XmlSchemaSimpleTypeUnion union = XmlSchemaSimpleTypeUnion.Read(reader, h);
                        if (union != null)
                        {
                            stype.content = union;
                        }
                        continue;
                    }
                }
                reader.RaiseInvalidElementError();
            }
            return(stype);
        }
Esempio n. 25
0
        // 3.14.6 Type Derivation OK (Simple)
        internal bool ValidateTypeDerivationOK(object baseType,
                                               ValidationEventHandler h, XmlSchema schema, bool raiseError)
        {
            // 1
            // Note that anyType should also be allowed as anySimpleType.
            if (this == baseType || baseType == XmlSchemaSimpleType.AnySimpleType ||
                baseType == XmlSchemaComplexType.AnyType)
            {
                return(true);
            }

            // 2.1
            XmlSchemaSimpleType baseSimpleType = baseType as XmlSchemaSimpleType;

            if (baseSimpleType != null &&
                (baseSimpleType.FinalResolved & resolvedDerivedBy) != 0)
            {
                if (raiseError)
                {
                    error(h, "Specified derivation is prohibited by the base type.");
                }
                return(false);
            }

            // 2.2.1
            if (BaseXmlSchemaType == baseType || Datatype == baseType)
            {
                return(true);
            }

            // 2.2.2
            XmlSchemaSimpleType thisBaseSimpleType = BaseXmlSchemaType as XmlSchemaSimpleType;

            if (thisBaseSimpleType != null)
            {
                if (thisBaseSimpleType.ValidateTypeDerivationOK(baseType, h, schema, false))
                {
                    return(true);
                }
            }

            // 2.2.3
            switch (Variety)
            {
            case XmlSchemaDerivationMethod.Union:
            case XmlSchemaDerivationMethod.List:
                if (baseType == XmlSchemaSimpleType.AnySimpleType)
                {
                    return(true);
                }
                break;
            }

            // 2.2.4 validly derived from one of the union member type.
            if (baseSimpleType != null && baseSimpleType.Variety == XmlSchemaDerivationMethod.Union)
            {
                foreach (object memberType in ((XmlSchemaSimpleTypeUnion)baseSimpleType.Content).ValidatedTypes)
                {
                    if (this.ValidateTypeDerivationOK(memberType, h, schema, false))
                    {
                        return(true);
                    }
                }
            }

            if (raiseError)
            {
                error(h, "Invalid simple type derivation was found.");
            }
            return(false);
        }
        //<attribute
        //  default = string
        //  fixed = string
        //  form = (qualified | unqualified)
        //  id = ID
        //  name = NCName
        //  ref = QName
        //  type = QName
        //  use = (optional | prohibited | required) : optional
        //  {any attributes with non-schema namespace . . .}>
        //  Content: (annotation?, (simpleType?))
        //</attribute>
        internal static XmlSchemaAttribute Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaAttribute attribute = new XmlSchemaAttribute();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaAttribute.Read, name=" + reader.Name, null);
                reader.SkipToEnd();
                return(null);
            }

            attribute.LineNumber   = reader.LineNumber;
            attribute.LinePosition = reader.LinePosition;
            attribute.SourceUri    = reader.BaseURI;

            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "default")
                {
                    attribute.defaultValue = reader.Value;
                }
                else if (reader.Name == "fixed")
                {
                    attribute.fixedValue = reader.Value;
                }
                else if (reader.Name == "form")
                {
                    Exception innerex;
                    attribute.form = XmlSchemaUtil.ReadFormAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for form attribute", innerex);
                    }
                }
                else if (reader.Name == "id")
                {
                    attribute.Id = reader.Value;
                }
                else if (reader.Name == "name")
                {
                    attribute.name = reader.Value;
                }
                else if (reader.Name == "ref")
                {
                    Exception innerex;
                    attribute.refName = XmlSchemaUtil.ReadQNameAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for ref attribute", innerex);
                    }
                }
                else if (reader.Name == "type")
                {
                    Exception innerex;
                    attribute.schemaTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for type attribute", innerex);
                    }
                }
                else if (reader.Name == "use")
                {
                    Exception innerex;
                    attribute.use = XmlSchemaUtil.ReadUseAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for use attribute", innerex);
                    }
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for attribute", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, attribute);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(attribute);
            }

            //  Content: (annotation?, (simpleType?))
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaAttribute.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2; //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        attribute.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2 && reader.LocalName == "simpleType")
                {
                    level = 3;
                    XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h);
                    if (stype != null)
                    {
                        attribute.schemaType = stype;
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(attribute);
        }
Esempio n. 27
0
        internal static XmlSchemaSimpleTypeList Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleTypeList xmlSchemaSimpleTypeList = new XmlSchemaSimpleTypeList();

            reader.MoveToElement();
            if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "list")
            {
                XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaSimpleTypeList.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }
            xmlSchemaSimpleTypeList.LineNumber   = reader.LineNumber;
            xmlSchemaSimpleTypeList.LinePosition = reader.LinePosition;
            xmlSchemaSimpleTypeList.SourceUri    = reader.BaseURI;
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    xmlSchemaSimpleTypeList.Id = reader.Value;
                }
                else if (reader.Name == "itemType")
                {
                    Exception ex;
                    xmlSchemaSimpleTypeList.ItemTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out ex);
                    if (ex != null)
                    {
                        XmlSchemaObject.error(h, reader.Value + " is not a valid value for itemType attribute", ex);
                    }
                }
                else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema")
                {
                    XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for list", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaSimpleTypeList);
                }
            }
            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(xmlSchemaSimpleTypeList);
            }
            int num = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != "list")
                    {
                        XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaSimpleTypeList.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (num <= 1 && reader.LocalName == "annotation")
                {
                    num = 2;
                    XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h);
                    if (xmlSchemaAnnotation != null)
                    {
                        xmlSchemaSimpleTypeList.Annotation = xmlSchemaAnnotation;
                    }
                }
                else if (num <= 2 && reader.LocalName == "simpleType")
                {
                    num = 3;
                    XmlSchemaSimpleType xmlSchemaSimpleType = XmlSchemaSimpleType.Read(reader, h);
                    if (xmlSchemaSimpleType != null)
                    {
                        xmlSchemaSimpleTypeList.itemType = xmlSchemaSimpleType;
                    }
                }
                else
                {
                    reader.RaiseInvalidElementError();
                }
            }
            return(xmlSchemaSimpleTypeList);
        }
        internal override Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue)
        {
            Exception exception;

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            typedValue = null;
            string s = value as string;

            if (s != null)
            {
                return(this.TryParseValue(s, nameTable, nsmgr, out typedValue));
            }
            object obj2            = null;
            XmlSchemaSimpleType st = null;

            for (int i = 0; i < this.types.Length; i++)
            {
                if (this.types[i].Datatype.TryParseValue(value, nameTable, nsmgr, out obj2) == null)
                {
                    st = this.types[i];
                    break;
                }
            }
            if (obj2 == null)
            {
                return(new XmlSchemaException("Sch_UnionFailedEx", value.ToString()));
            }
            try
            {
                if (this.HasLexicalFacets)
                {
                    string parseString = (string)this.ValueConverter.ChangeType(obj2, typeof(string), nsmgr);
                    exception = DatatypeImplementation.unionFacetsChecker.CheckLexicalFacets(ref parseString, this);
                    if (exception != null)
                    {
                        return(exception);
                    }
                }
                typedValue = new XsdSimpleValue(st, obj2);
                if (this.HasValueFacets)
                {
                    exception = DatatypeImplementation.unionFacetsChecker.CheckValueFacets(typedValue, this);
                    if (exception != null)
                    {
                        return(exception);
                    }
                }
                return(null);
            }
            catch (FormatException exception2)
            {
                exception = exception2;
            }
            catch (InvalidCastException exception3)
            {
                exception = exception3;
            }
            catch (OverflowException exception4)
            {
                exception = exception4;
            }
            catch (ArgumentException exception5)
            {
                exception = exception5;
            }
            return(exception);
        }
        internal static XmlSchemaRedefine Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaRedefine xmlSchemaRedefine = new XmlSchemaRedefine();

            reader.MoveToElement();
            if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "redefine")
            {
                XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaRedefine.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }
            xmlSchemaRedefine.LineNumber   = reader.LineNumber;
            xmlSchemaRedefine.LinePosition = reader.LinePosition;
            xmlSchemaRedefine.SourceUri    = reader.BaseURI;
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    xmlSchemaRedefine.Id = reader.Value;
                }
                else if (reader.Name == "schemaLocation")
                {
                    xmlSchemaRedefine.SchemaLocation = reader.Value;
                }
                else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema")
                {
                    XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for redefine", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaRedefine);
                }
            }
            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(xmlSchemaRedefine);
            }
            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != "redefine")
                    {
                        XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaRedefine.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (reader.LocalName == "annotation")
                {
                    XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h);
                    if (xmlSchemaAnnotation != null)
                    {
                        xmlSchemaRedefine.items.Add(xmlSchemaAnnotation);
                    }
                }
                else if (reader.LocalName == "simpleType")
                {
                    XmlSchemaSimpleType xmlSchemaSimpleType = XmlSchemaSimpleType.Read(reader, h);
                    if (xmlSchemaSimpleType != null)
                    {
                        xmlSchemaRedefine.items.Add(xmlSchemaSimpleType);
                    }
                }
                else if (reader.LocalName == "complexType")
                {
                    XmlSchemaComplexType xmlSchemaComplexType = XmlSchemaComplexType.Read(reader, h);
                    if (xmlSchemaComplexType != null)
                    {
                        xmlSchemaRedefine.items.Add(xmlSchemaComplexType);
                    }
                }
                else if (reader.LocalName == "group")
                {
                    XmlSchemaGroup xmlSchemaGroup = XmlSchemaGroup.Read(reader, h);
                    if (xmlSchemaGroup != null)
                    {
                        xmlSchemaRedefine.items.Add(xmlSchemaGroup);
                    }
                }
                else if (reader.LocalName == "attributeGroup")
                {
                    XmlSchemaAttributeGroup xmlSchemaAttributeGroup = XmlSchemaAttributeGroup.Read(reader, h);
                    if (xmlSchemaAttributeGroup != null)
                    {
                        xmlSchemaRedefine.items.Add(xmlSchemaAttributeGroup);
                    }
                }
                else
                {
                    reader.RaiseInvalidElementError();
                }
            }
            return(xmlSchemaRedefine);
        }
Esempio n. 30
0
        private ComplexType ToComplexType(Element el)
        {
            QName         name = el.SchemaTypeName;
            XmlSchemaType type = el.SchemaType;

            // 1. element type is complex.
            ComplexType ct = type as ComplexType;

            if (ct != null)
            {
                return(ct);
            }

            // 2. reference to global complexType.
            XmlSchemaType globalType = schemas.GlobalTypes [name]
                                       as XmlSchemaType;

            ct = globalType as ComplexType;
            if (ct != null)
            {
                return(ct);
            }

            ct                = new ComplexType();
            el.SchemaType     = ct;
            el.SchemaTypeName = QName.Empty;

            // 3. base type name is xs:anyType or no specification.
            // <xs:complexType />
            if (name == QNameAnyType)
            {
                return(ct);
            }
            else if (type == null && name == QName.Empty)
            {
                return(ct);
            }

            SimpleModel sc = new SimpleModel();

            ct.ContentModel = sc;

            // 4. type is simpleType
            //    -> extension of existing simple type.
            SimpleType st = type as SimpleType;

            if (st != null)
            {
                SimpleRst scr = new SimpleRst();
                scr.BaseType = st;
                sc.Content   = scr;
                return(ct);
            }

            SimpleExt sce = new SimpleExt();

            sc.Content = sce;

            // 5. type name points to primitive type
            //    -> simple extension of a primitive type
            st = XmlSchemaType.GetBuiltInSimpleType(name);
            if (st != null)
            {
                sce.BaseTypeName = name;
                return(ct);
            }

            // 6. type name points to global simpleType.
            st = globalType as SimpleType;
            if (st != null)
            {
                sce.BaseTypeName = name;
                return(ct);
            }

            throw Error(el, "Unexpected schema component that contains simpleTypeName that could not be resolved.");
        }
 private void CompileSimpleType(XmlSchemaSimpleType simpleType)
 {
     if (simpleType.IsProcessing)
     {
         throw new XmlSchemaException("Sch_TypeCircularRef", simpleType);
     }
     if (simpleType.ElementDecl == null)
     {
         simpleType.IsProcessing = true;
         try
         {
             if (simpleType.Content is XmlSchemaSimpleTypeList)
             {
                 XmlSchemaDatatype datatype;
                 XmlSchemaSimpleTypeList content = (XmlSchemaSimpleTypeList) simpleType.Content;
                 simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType);
                 if (content.ItemTypeName.IsEmpty)
                 {
                     this.CompileSimpleType(content.ItemType);
                     content.BaseItemType = content.ItemType;
                     datatype = content.ItemType.Datatype;
                 }
                 else
                 {
                     XmlSchemaSimpleType type = this.GetSimpleType(content.ItemTypeName);
                     if (type == null)
                     {
                         throw new XmlSchemaException("Sch_UndeclaredSimpleType", content.ItemTypeName.ToString(), simpleType);
                     }
                     if ((type.FinalResolved & XmlSchemaDerivationMethod.List) != XmlSchemaDerivationMethod.Empty)
                     {
                         base.SendValidationEvent("Sch_BaseFinalList", simpleType);
                     }
                     content.BaseItemType = type;
                     datatype = type.Datatype;
                 }
                 simpleType.SetDatatype(datatype.DeriveByList(simpleType));
                 simpleType.SetDerivedBy(XmlSchemaDerivationMethod.List);
             }
             else if (simpleType.Content is XmlSchemaSimpleTypeRestriction)
             {
                 XmlSchemaDatatype datatype2;
                 XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction) simpleType.Content;
                 if (restriction.BaseTypeName.IsEmpty)
                 {
                     this.CompileSimpleType(restriction.BaseType);
                     simpleType.SetBaseSchemaType(restriction.BaseType);
                     datatype2 = restriction.BaseType.Datatype;
                 }
                 else if ((simpleType.Redefined != null) && (restriction.BaseTypeName == simpleType.Redefined.QualifiedName))
                 {
                     this.CompileSimpleType((XmlSchemaSimpleType) simpleType.Redefined);
                     simpleType.SetBaseSchemaType(simpleType.Redefined.BaseXmlSchemaType);
                     datatype2 = simpleType.Redefined.Datatype;
                 }
                 else
                 {
                     if (restriction.BaseTypeName.Equals(DatatypeImplementation.QnAnySimpleType))
                     {
                         throw new XmlSchemaException("Sch_InvalidSimpleTypeRestriction", restriction.BaseTypeName.ToString(), simpleType);
                     }
                     XmlSchemaSimpleType type2 = this.GetSimpleType(restriction.BaseTypeName);
                     if (type2 == null)
                     {
                         throw new XmlSchemaException("Sch_UndeclaredSimpleType", restriction.BaseTypeName.ToString(), simpleType);
                     }
                     if ((type2.FinalResolved & XmlSchemaDerivationMethod.Restriction) != XmlSchemaDerivationMethod.Empty)
                     {
                         base.SendValidationEvent("Sch_BaseFinalRestriction", simpleType);
                     }
                     simpleType.SetBaseSchemaType(type2);
                     datatype2 = type2.Datatype;
                 }
                 simpleType.SetDatatype(datatype2.DeriveByRestriction(restriction.Facets, base.NameTable, simpleType));
                 simpleType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction);
             }
             else
             {
                 XmlSchemaSimpleType[] types = this.CompileBaseMemberTypes(simpleType);
                 simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType);
                 simpleType.SetDatatype(XmlSchemaDatatype.DeriveByUnion(types, simpleType));
                 simpleType.SetDerivedBy(XmlSchemaDerivationMethod.Union);
             }
         }
         catch (XmlSchemaException exception)
         {
             if (exception.SourceSchemaObject == null)
             {
                 exception.SetSource(simpleType);
             }
             base.SendValidationEvent(exception);
             simpleType.SetDatatype(DatatypeImplementation.AnySimpleType.Datatype);
         }
         finally
         {
             SchemaElementDecl decl = new SchemaElementDecl {
                 ContentValidator = ContentValidator.TextOnly,
                 SchemaType = simpleType,
                 Datatype = simpleType.Datatype
             };
             simpleType.ElementDecl = decl;
             simpleType.IsProcessing = false;
         }
     }
 }
Esempio n. 32
0
 public UnionSimpleTypeValidator(XmlSchemaSimpleType type,
                              RestrictionFacets facets,
                              SimpleTypeValidator[] memberTypes)
     : base(XmlSchemaDatatypeVariety.Union, type, FacetsChecker.UnionFacetsChecker, facets) {
     this.memberTypes = memberTypes;
 }
Esempio n. 33
0
        void DoCompile(ValidationEventHandler handler, Hashtable handledUris, XmlSchemaSet col, XmlResolver resolver)
        {
            SetParent();
            CompilationId = col.CompilationId;
            schemas       = col;
            if (!schemas.Contains(this))              // e.g. xs:import
            {
                schemas.Add(this);
            }

            attributeGroups.Clear();
            attributes.Clear();
            elements.Clear();
            groups.Clear();
            notations.Clear();
            schemaTypes.Clear();

            //1. Union and List are not allowed in block default
            if (BlockDefault != XmlSchemaDerivationMethod.All)
            {
                if ((BlockDefault & XmlSchemaDerivationMethod.List) != 0)
                {
                    error(handler, "list is not allowed in blockDefault attribute");
                }
                if ((BlockDefault & XmlSchemaDerivationMethod.Union) != 0)
                {
                    error(handler, "union is not allowed in blockDefault attribute");
                }
            }

            //2. Substitution is not allowed in finaldefault.
            if (FinalDefault != XmlSchemaDerivationMethod.All)
            {
                if ((FinalDefault & XmlSchemaDerivationMethod.Substitution) != 0)
                {
                    error(handler, "substitution is not allowed in finalDefault attribute");
                }
            }

            //3. id must be of type ID
            XmlSchemaUtil.CompileID(Id, this, col.IDCollection, handler);

            //4. targetNamespace should be of type anyURI or absent
            if (TargetNamespace != null)
            {
                if (TargetNamespace.Length == 0)
                {
                    error(handler, "The targetNamespace attribute cannot have have empty string as its value.");
                }

                if (!XmlSchemaUtil.CheckAnyUri(TargetNamespace))
                {
                    error(handler, TargetNamespace + " is not a valid value for targetNamespace attribute of schema");
                }
            }

            //5. version should be of type normalizedString
            if (!XmlSchemaUtil.CheckNormalizedString(Version))
            {
                error(handler, Version + "is not a valid value for version attribute of schema");
            }

            // Compile the content of this schema

            compilationItems = new XmlSchemaObjectCollection();
            for (int i = 0; i < Items.Count; i++)
            {
                compilationItems.Add(Items [i]);
            }

            // First, we run into inclusion schemas to collect
            // compilation target items into compiledItems.
            for (int i = 0; i < Includes.Count; i++)
            {
                XmlSchemaExternal ext = Includes [i] as XmlSchemaExternal;
                if (ext == null)
                {
                    error(handler, String.Format("Object of Type {0} is not valid in Includes Property of XmlSchema", Includes [i].GetType().Name));
                    continue;
                }

                if (ext.SchemaLocation == null)
                {
                    continue;
                }

                Stream stream = null;
                string url    = null;
                if (resolver != null)
                {
                    url = GetResolvedUri(resolver, ext.SchemaLocation);
                    if (handledUris.Contains(url))
                    {
                        // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur.
                        continue;
                    }
                    handledUris.Add(url, url);
                    try {
                        stream = resolver.GetEntity(new Uri(url), null, typeof(Stream)) as Stream;
                    } catch (Exception) {
                        // LAMESPEC: This is not good way to handle errors, but since we cannot know what kind of XmlResolver will come, so there are no mean to avoid this ugly catch.
                        warn(handler, "Could not resolve schema location URI: " + url);
                        stream = null;
                    }
                }

                // Process redefinition children in advance.
                XmlSchemaRedefine redefine = Includes [i] as XmlSchemaRedefine;
                if (redefine != null)
                {
                    for (int j = 0; j < redefine.Items.Count; j++)
                    {
                        XmlSchemaObject redefinedObj = redefine.Items [j];
                        redefinedObj.isRedefinedComponent = true;
                        redefinedObj.isRedefineChild      = true;
                        if (redefinedObj is XmlSchemaType ||
                            redefinedObj is XmlSchemaGroup ||
                            redefinedObj is XmlSchemaAttributeGroup)
                        {
                            compilationItems.Add(redefinedObj);
                        }
                        else
                        {
                            error(handler, "Redefinition is only allowed to simpleType, complexType, group and attributeGroup.");
                        }
                    }
                }

                XmlSchema includedSchema = null;
                if (stream == null)
                {
                    // It is missing schema components.
                    missedSubComponents = true;
                    continue;
                }
                else
                {
                    XmlTextReader xtr = null;
                    try {
                        xtr            = new XmlTextReader(url, stream, nameTable);
                        includedSchema = XmlSchema.Read(xtr, handler);
                    } finally {
                        if (xtr != null)
                        {
                            xtr.Close();
                        }
                    }
                    includedSchema.schemas = schemas;
                }
                includedSchema.SetParent();
                ext.Schema = includedSchema;

                // Set - actual - target namespace for the included schema * before compilation*.
                XmlSchemaImport import = ext as XmlSchemaImport;
                if (import != null)
                {
                    if (TargetNamespace == includedSchema.TargetNamespace)
                    {
                        error(handler, "Target namespace must be different from that of included schema.");
                        continue;
                    }
                    else if (includedSchema.TargetNamespace != import.Namespace)
                    {
                        error(handler, "Attribute namespace and its importing schema's target namespace must be the same.");
                        continue;
                    }
                }
                else
                {
                    if (TargetNamespace == null &&
                        includedSchema.TargetNamespace != null)
                    {
                        error(handler, "Target namespace is required to include a schema which has its own target namespace");
                        continue;
                    }
                    else if (TargetNamespace != null &&
                             includedSchema.TargetNamespace == null)
                    {
                        includedSchema.TargetNamespace = TargetNamespace;
                    }
                }

                // Do not compile included schema here.

                AddExternalComponentsTo(includedSchema, compilationItems);
            }

            // Compilation phase.
            // At least each Compile() must give unique (qualified) name for each component.
            // It also checks self-resolvable properties correctness.
            // Post compilation schema information contribution is not done here.
            // It should be done by Validate().
            for (int i = 0; i < compilationItems.Count; i++)
            {
                XmlSchemaObject obj = compilationItems [i];
                if (obj is XmlSchemaAnnotation)
                {
                    int numerr = ((XmlSchemaAnnotation)obj).Compile(handler, this);
                    errorCount += numerr;
                }
                else if (obj is XmlSchemaAttribute)
                {
                    XmlSchemaAttribute attr = (XmlSchemaAttribute)obj;
                    int numerr = attr.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(Attributes, attr, attr.QualifiedName, handler);
                    }
                }
                else if (obj is XmlSchemaAttributeGroup)
                {
                    XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup)obj;
                    int numerr = attrgrp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            AttributeGroups,
                            attrgrp,
                            attrgrp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType ctype = (XmlSchemaComplexType)obj;
                    int numerr = ctype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            schemaTypes,
                            ctype,
                            ctype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaSimpleType)
                {
                    XmlSchemaSimpleType stype = (XmlSchemaSimpleType)obj;
                    stype.islocal = false;                     //This simple type is toplevel
                    int numerr = stype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            SchemaTypes,
                            stype,
                            stype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaElement)
                {
                    XmlSchemaElement elem = (XmlSchemaElement)obj;
                    elem.parentIsSchema = true;
                    int numerr = elem.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Elements,
                            elem,
                            elem.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaGroup)
                {
                    XmlSchemaGroup grp    = (XmlSchemaGroup)obj;
                    int            numerr = grp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Groups,
                            grp,
                            grp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaNotation)
                {
                    XmlSchemaNotation ntn = (XmlSchemaNotation)obj;
                    int numerr            = ntn.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Notations,
                            ntn,
                            ntn.QualifiedName,
                            handler);
                    }
                }
                else
                {
                    ValidationHandler.RaiseValidationEvent(
                        handler,
                        null,
                        String.Format("Object of Type {0} is not valid in Item Property of Schema", obj.GetType().Name),
                        null,
                        this,
                        null,
                        XmlSeverityType.Error);
                }
            }
        }
Esempio n. 34
0
 public static bool AreSchemaDatatypeEqual(XmlSchemaSimpleType st1, object v1, XmlSchemaSimpleType st2, object v2)
 {
     if (st1.Datatype is XsdAnySimpleType)
     {
         return(AreSchemaDatatypeEqual(st1.Datatype as XsdAnySimpleType, v1, st2.Datatype as XsdAnySimpleType, v2));
     }
     // otherwise the types are lists of strings.
     string [] a1 = v1 as string [];
     string [] a2 = v2 as string [];
     if (st1 != st2 || a1 == null || a2 == null || a1.Length != a2.Length)
     {
         return(false);
     }
     for (int i = 0; i < a1.Length; i++)
     {
         if (a1 [i] != a2 [i])
         {
             return(false);
         }
     }
     return(true);
 }
Esempio n. 35
0
 private SchemaElementDecl ThoroughGetElementDecl(SchemaElementDecl elementDecl, XmlQualifiedName xsiType, string xsiNil)
 {
     if (elementDecl == null)
     {
         elementDecl = schemaInfo.GetElementDecl(elementName);
     }
     if (elementDecl != null)
     {
         if (xsiType.IsEmpty)
         {
             if (elementDecl.IsAbstract)
             {
                 SendValidationEvent(SR.Sch_AbstractElement, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace));
                 elementDecl = null;
             }
         }
         else if (xsiNil != null && xsiNil.Equals("true"))
         {
             SendValidationEvent(SR.Sch_XsiNilAndType);
         }
         else
         {
             SchemaElementDecl elementDeclXsi;
             if (!schemaInfo.ElementDeclsByType.TryGetValue(xsiType, out elementDeclXsi) && xsiType.Namespace == _nsXs)
             {
                 XmlSchemaSimpleType simpleType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName(xsiType.Name, _nsXs));
                 if (simpleType != null)
                 {
                     elementDeclXsi = simpleType.ElementDecl;
                 }
             }
             if (elementDeclXsi == null)
             {
                 SendValidationEvent(SR.Sch_XsiTypeNotFound, xsiType.ToString());
                 elementDecl = null;
             }
             else if (!XmlSchemaType.IsDerivedFrom(elementDeclXsi.SchemaType, elementDecl.SchemaType, elementDecl.Block))
             {
                 SendValidationEvent(SR.Sch_XsiTypeBlockedEx, new string[] { xsiType.ToString(), XmlSchemaValidator.QNameString(context.LocalName, context.Namespace) });
                 elementDecl = null;
             }
             else
             {
                 elementDecl = elementDeclXsi;
             }
         }
         if (elementDecl != null && elementDecl.IsNillable)
         {
             if (xsiNil != null)
             {
                 context.IsNill = XmlConvert.ToBoolean(xsiNil);
                 if (context.IsNill && elementDecl.DefaultValueTyped != null)
                 {
                     SendValidationEvent(SR.Sch_XsiNilAndFixed);
                 }
             }
         }
         else if (xsiNil != null)
         {
             SendValidationEvent(SR.Sch_InvalidXsiNill);
         }
     }
     return(elementDecl);
 }
        internal override int Validate(ValidationEventHandler h, XmlSchema schema)
        {
            if (IsValidated(schema.ValidationId))
            {
                return(errorCount);
            }

            ArrayList al = new ArrayList();

            // Validate MemberTypes
            if (MemberTypes != null)
            {
                foreach (XmlQualifiedName memberTypeName in MemberTypes)
                {
                    object        type   = null;
                    XmlSchemaType xstype = schema.FindSchemaType(memberTypeName) as XmlSchemaSimpleType;
                    if (xstype != null)
                    {
                        errorCount += xstype.Validate(h, schema);
                        type        = xstype;
                    }
                    else if (memberTypeName == XmlSchemaComplexType.AnyTypeName)
                    {
                        type = XmlSchemaSimpleType.AnySimpleType;
                    }
                    else if (memberTypeName.Namespace == XmlSchema.Namespace ||
                             memberTypeName.Namespace == XmlSchema.XdtNamespace)
                    {
                        type = XmlSchemaDatatype.FromName(memberTypeName);
                        if (type == null)
                        {
                            error(h, "Invalid schema type name was specified: " + memberTypeName);
                        }
                    }
                    // otherwise, it might be missing sub components.
                    else if (!schema.IsNamespaceAbsent(memberTypeName.Namespace))
                    {
                        error(h, "Referenced base schema type " + memberTypeName + " was not found in the corresponding schema.");
                    }

                    al.Add(type);
                }
            }
            if (BaseTypes != null)
            {
                foreach (XmlSchemaSimpleType st in BaseTypes)
                {
                    st.Validate(h, schema);
                    al.Add(st);
                }
            }
            this.validatedTypes = al.ToArray();

#if NET_2_0
            if (validatedTypes != null)
            {
                validatedSchemaTypes = new XmlSchemaSimpleType [validatedTypes.Length];
                for (int i = 0; i < validatedTypes.Length; i++)
                {
                    object t = validatedTypes [i];
                    XmlSchemaSimpleType st = t as XmlSchemaSimpleType;
                    if (st == null && t != null)
                    {
                        st = XmlSchemaType.GetBuiltInSimpleType(((XmlSchemaDatatype)t).TypeCode);
                    }
                    validatedSchemaTypes [i] = st;
                }
            }
#endif

            ValidationId = schema.ValidationId;
            return(errorCount);
        }
        //<union
        //  id = ID
        //  memberTypes = List of QName
        //  {any attributes with non-schema namespace . . .}>
        //  Content: (annotation?, (simpleType*))
        //</union>
        internal static XmlSchemaSimpleTypeUnion Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleTypeUnion union = new XmlSchemaSimpleTypeUnion();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaSimpleTypeUnion.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }

            union.LineNumber   = reader.LineNumber;
            union.LinePosition = reader.LinePosition;
            union.SourceUri    = reader.BaseURI;

            //Read Attributes
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    union.Id = reader.Value;
                }
                else if (reader.Name == "memberTypes")
                {
                    Exception innerEx;
                    string[]  names = XmlSchemaUtil.SplitList(reader.Value);
                    union.memberTypes = new XmlQualifiedName[names.Length];
                    for (int i = 0; i < names.Length; i++)
                    {
                        union.memberTypes[i] = XmlSchemaUtil.ToQName(reader, names[i], out innerEx);
                        if (innerEx != null)
                        {
                            error(h, "'" + names[i] + "' is not a valid memberType", innerEx);
                        }
                    }
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for union", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, union);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(union);
            }

            //  Content: annotation?, simpleType*
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaSimpleTypeUnion.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2; //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        union.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2 && reader.LocalName == "simpleType")
                {
                    level = 2;
                    XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h);
                    if (stype != null)
                    {
                        union.baseTypes.Add(stype);
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(union);
        }
 void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o) {
     if ((object)o == null) return;
     WriteStartElement("simpleType");
     
     WriteAttribute(@"id", @"", ((System.String)o.@Id));
     WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o);
     WriteAttribute(@"name", @"", ((System.String)o.@Name));
     WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
     Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation);
     if (o.@Content is XmlSchemaSimpleTypeUnion) {
         Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content);
     }
     else if (o.@Content is XmlSchemaSimpleTypeRestriction) {
         Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content);
     }
     else if (o.@Content is XmlSchemaSimpleTypeList) {
         Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content);
     }
     WriteEndElement();
 }
Esempio n. 39
0
 public AtomicSimpleTypeValidator(XmlSchemaSimpleType type,
                                RestrictionFacets facets)
     : base(XmlSchemaDatatypeVariety.Atomic, 
            type, 
            FacetsChecker.GetFacetsChecker(type.Datatype.TypeCode), 
           facets) {
 }
 internal void SetAttributeType(XmlSchemaSimpleType value)
 {
     this.attributeType = value;
 }
 private static void CleanupSimpleType(XmlSchemaSimpleType simpleType)
 {
     simpleType.ElementDecl = null;
 }
Esempio n. 42
0
 private SchemaElementDecl ThoroughGetElementDecl(SchemaElementDecl elementDecl, XmlQualifiedName xsiType, string xsiNil)
 {
     if (elementDecl == null)
     {
         elementDecl = base.schemaInfo.GetElementDecl(base.elementName);
     }
     if (elementDecl != null)
     {
         if (xsiType.IsEmpty)
         {
             if (elementDecl.IsAbstract)
             {
                 base.SendValidationEvent("Sch_AbstractElement", XmlSchemaValidator.QNameString(base.context.LocalName, base.context.Namespace));
                 elementDecl = null;
             }
         }
         else if ((xsiNil != null) && xsiNil.Equals("true"))
         {
             base.SendValidationEvent("Sch_XsiNilAndType");
         }
         else
         {
             SchemaElementDecl decl;
             if (!base.schemaInfo.ElementDeclsByType.TryGetValue(xsiType, out decl) && (xsiType.Namespace == this.NsXs))
             {
                 XmlSchemaSimpleType simpleTypeFromXsdType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName(xsiType.Name, this.NsXs));
                 if (simpleTypeFromXsdType != null)
                 {
                     decl = simpleTypeFromXsdType.ElementDecl;
                 }
             }
             if (decl == null)
             {
                 base.SendValidationEvent("Sch_XsiTypeNotFound", xsiType.ToString());
                 elementDecl = null;
             }
             else if (!XmlSchemaType.IsDerivedFrom(decl.SchemaType, elementDecl.SchemaType, elementDecl.Block))
             {
                 base.SendValidationEvent("Sch_XsiTypeBlockedEx", new string[] { xsiType.ToString(), XmlSchemaValidator.QNameString(base.context.LocalName, base.context.Namespace) });
                 elementDecl = null;
             }
             else
             {
                 elementDecl = decl;
             }
         }
         if ((elementDecl != null) && elementDecl.IsNillable)
         {
             if (xsiNil != null)
             {
                 base.context.IsNill = XmlConvert.ToBoolean(xsiNil);
                 if (base.context.IsNill && (elementDecl.DefaultValueTyped != null))
                 {
                     base.SendValidationEvent("Sch_XsiNilAndFixed");
                 }
             }
             return(elementDecl);
         }
         if (xsiNil != null)
         {
             base.SendValidationEvent("Sch_InvalidXsiNill");
         }
     }
     return(elementDecl);
 }
Esempio n. 43
0
        private void InferTextContent(Element el, bool isNew)
        {
            string value = source.ReadString();

            if (el.SchemaType == null)
            {
                if (el.SchemaTypeName == QName.Empty)
                {
                    // no type information -> infer type
                    if (isNew)
                    {
                        el.SchemaTypeName =
                            InferSimpleType(
                                value);
                    }
                    else
                    {
                        el.SchemaTypeName =
                            QNameString;
                    }
                    return;
                }
                switch (el.SchemaTypeName.Namespace)
                {
                case XmlSchema.Namespace:
                case XdtNamespace:
                    // existing primitive type
                    el.SchemaTypeName = InferMergedType(
                        value, el.SchemaTypeName);
                    break;

                default:
                    ComplexType ct = schemas.GlobalTypes [
                        el.SchemaTypeName]
                                     as ComplexType;
                    // If it is complex, then just set
                    // mixed='true' (type cannot be set.)
                    // If it is simple, then we cannot
                    // make sure that string value is
                    // valid. So just set as xs:string.
                    if (ct != null)
                    {
                        MarkAsMixed(ct);
                    }
                    else
                    {
                        el.SchemaTypeName = QNameString;
                    }
                    break;
                }
                return;
            }
            // simpleType
            SimpleType st = el.SchemaType as SimpleType;

            if (st != null)
            {
                // If simple, then (described above)
                el.SchemaType     = null;
                el.SchemaTypeName = QNameString;
                return;
            }

            // complexType
            ComplexType ect = el.SchemaType as ComplexType;

            SimpleModel sm = ect.ContentModel as SimpleModel;

            if (sm == null)
            {
                // - ComplexContent
                MarkAsMixed(ect);
                return;
            }

            // - SimpleContent
            SimpleExt se = sm.Content as SimpleExt;

            if (se != null)
            {
                se.BaseTypeName = InferMergedType(value,
                                                  se.BaseTypeName);
            }
            SimpleRst sr = sm.Content as SimpleRst;

            if (sr != null)
            {
                sr.BaseTypeName = InferMergedType(value,
                                                  sr.BaseTypeName);
                sr.BaseType = null;
            }
        }
 private void CheckRefinedSimpleType(XmlSchemaSimpleType stype)
 {
     if ((stype.Content != null) && (stype.Content is XmlSchemaSimpleTypeRestriction))
     {
         XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction) stype.Content;
         if (content.BaseTypeName == stype.QualifiedName)
         {
             return;
         }
     }
     base.SendValidationEvent("Sch_InvalidTypeRedefine", stype);
 }
 internal static XmlSchema GetBuildInSchema()
 {
     if (builtInSchemaForXmlNS == null)
     {
         XmlSchema schema = new XmlSchema {
             TargetNamespace = "http://www.w3.org/XML/1998/namespace"
         };
         schema.Namespaces.Add("xml", "http://www.w3.org/XML/1998/namespace");
         XmlSchemaAttribute item = new XmlSchemaAttribute {
             Name = "lang",
             SchemaTypeName = new XmlQualifiedName("language", "http://www.w3.org/2001/XMLSchema")
         };
         schema.Items.Add(item);
         XmlSchemaAttribute attribute2 = new XmlSchemaAttribute {
             Name = "base",
             SchemaTypeName = new XmlQualifiedName("anyURI", "http://www.w3.org/2001/XMLSchema")
         };
         schema.Items.Add(attribute2);
         XmlSchemaAttribute attribute3 = new XmlSchemaAttribute {
             Name = "space"
         };
         XmlSchemaSimpleType type = new XmlSchemaSimpleType();
         XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction {
             BaseTypeName = new XmlQualifiedName("NCName", "http://www.w3.org/2001/XMLSchema")
         };
         XmlSchemaEnumerationFacet facet = new XmlSchemaEnumerationFacet {
             Value = "default"
         };
         restriction.Facets.Add(facet);
         XmlSchemaEnumerationFacet facet2 = new XmlSchemaEnumerationFacet {
             Value = "preserve"
         };
         restriction.Facets.Add(facet2);
         type.Content = restriction;
         attribute3.SchemaType = type;
         attribute3.DefaultValue = "preserve";
         schema.Items.Add(attribute3);
         XmlSchemaAttributeGroup group = new XmlSchemaAttributeGroup {
             Name = "specialAttrs"
         };
         XmlSchemaAttribute attribute4 = new XmlSchemaAttribute {
             RefName = new XmlQualifiedName("lang", "http://www.w3.org/XML/1998/namespace")
         };
         group.Attributes.Add(attribute4);
         XmlSchemaAttribute attribute5 = new XmlSchemaAttribute {
             RefName = new XmlQualifiedName("space", "http://www.w3.org/XML/1998/namespace")
         };
         group.Attributes.Add(attribute5);
         XmlSchemaAttribute attribute6 = new XmlSchemaAttribute {
             RefName = new XmlQualifiedName("base", "http://www.w3.org/XML/1998/namespace")
         };
         group.Attributes.Add(attribute6);
         schema.Items.Add(group);
         schema.IsPreprocessed = true;
         schema.CompileSchemaInSet(new NameTable(), null, null);
         Interlocked.CompareExchange<XmlSchema>(ref builtInSchemaForXmlNS, schema, null);
     }
     return builtInSchemaForXmlNS;
 }
        internal static XmlSchemaSimpleType Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleType xmlSchemaSimpleType = new XmlSchemaSimpleType();

            reader.MoveToElement();
            if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "simpleType")
            {
                XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaGroup.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }
            xmlSchemaSimpleType.LineNumber   = reader.LineNumber;
            xmlSchemaSimpleType.LinePosition = reader.LinePosition;
            xmlSchemaSimpleType.SourceUri    = reader.BaseURI;
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "final")
                {
                    Exception ex;
                    xmlSchemaSimpleType.Final = XmlSchemaUtil.ReadDerivationAttribute(reader, out ex, "final", XmlSchemaUtil.FinalAllowed);
                    if (ex != null)
                    {
                        XmlSchemaObject.error(h, "some invalid values not a valid value for final", ex);
                    }
                }
                else if (reader.Name == "id")
                {
                    xmlSchemaSimpleType.Id = reader.Value;
                }
                else if (reader.Name == "name")
                {
                    xmlSchemaSimpleType.Name = reader.Value;
                }
                else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema")
                {
                    XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for simpleType", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaSimpleType);
                }
            }
            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(xmlSchemaSimpleType);
            }
            int num = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != "simpleType")
                    {
                        XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaSimpleType.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (num <= 1 && reader.LocalName == "annotation")
                {
                    num = 2;
                    XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h);
                    if (xmlSchemaAnnotation != null)
                    {
                        xmlSchemaSimpleType.Annotation = xmlSchemaAnnotation;
                    }
                }
                else
                {
                    if (num <= 2)
                    {
                        if (reader.LocalName == "restriction")
                        {
                            num = 3;
                            XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction = XmlSchemaSimpleTypeRestriction.Read(reader, h);
                            if (xmlSchemaSimpleTypeRestriction != null)
                            {
                                xmlSchemaSimpleType.content = xmlSchemaSimpleTypeRestriction;
                            }
                            continue;
                        }
                        if (reader.LocalName == "list")
                        {
                            num = 3;
                            XmlSchemaSimpleTypeList xmlSchemaSimpleTypeList = XmlSchemaSimpleTypeList.Read(reader, h);
                            if (xmlSchemaSimpleTypeList != null)
                            {
                                xmlSchemaSimpleType.content = xmlSchemaSimpleTypeList;
                            }
                            continue;
                        }
                        if (reader.LocalName == "union")
                        {
                            num = 3;
                            XmlSchemaSimpleTypeUnion xmlSchemaSimpleTypeUnion = XmlSchemaSimpleTypeUnion.Read(reader, h);
                            if (xmlSchemaSimpleTypeUnion != null)
                            {
                                xmlSchemaSimpleType.content = xmlSchemaSimpleTypeUnion;
                            }
                            continue;
                        }
                    }
                    reader.RaiseInvalidElementError();
                }
            }
            return(xmlSchemaSimpleType);
        }
Esempio n. 47
0
 internal SimpleTypeValidator(XmlSchemaDatatypeVariety variety, 
                           XmlSchemaSimpleType type,
                           FacetsChecker facetsChecker,
                           RestrictionFacets facets) {
     this.restrictionFacets = facets;
     this.facetsChecker = facetsChecker;
     this.dataType = type.Datatype;
     this.variety = variety;
 }
Esempio n. 48
0
        // 3.14.6 Derivation Valid (RestrictionSimple)
        internal void ValidateDerivationValid(object baseType, XmlSchemaObjectCollection facets,
                                              ValidationEventHandler h, XmlSchema schema)
        {
            // TODO
            XmlSchemaSimpleType baseSimpleType = baseType as XmlSchemaSimpleType;

            switch (this.Variety)
            {
            // 1. atomic type
            case XmlSchemaDerivationMethod.Restriction:
                // 1.1
                if (baseSimpleType != null && baseSimpleType.resolvedDerivedBy != XmlSchemaDerivationMethod.Restriction)
                {
                    error(h, "Base schema type is not either atomic type or primitive type.");
                }
                // 1.2
                if (baseSimpleType != null &&
                    (baseSimpleType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0)
                {
                    error(h, "Derivation by restriction is prohibited by the base simple type.");
                }
                // TODO: 1.3 facet restriction valid.
                break;

            case XmlSchemaDerivationMethod.List:
                /*
                 * XmlSchemaSimpleTypeList thisList = Content as XmlSchemaSimpleTypeList;
                 * // 2.1 item list type not allowed
                 * if (baseSimpleType != null && baseSimpleType.resolvedDerivedBy == XmlSchemaDerivationMethod.List)
                 *  error (h, "Base list schema type is not allowed.");
                 * XmlSchemaSimpleTypeUnion baseUnion = baseSimpleType.Content as XmlSchemaSimpleTypeUnion;
                 * if (baseUnion != null) {
                 *  bool errorFound = false;
                 *  foreach (object memberType in baseUnion.ValidatedTypes) {
                 *          XmlSchemaSimpleType memberST = memberType as XmlSchemaSimpleType;
                 *          if (memberST != null && memberST.resolvedDerivedBy == XmlSchemaDerivationMethod.List)
                 *                  errorFound = true;
                 *  }
                 *  if (errorFound)
                 *          error (h, "Base union schema type should not contain list types.");
                 * }
                 */
                // 2.2 facets limited
                if (facets != null)
                {
                    foreach (XmlSchemaFacet facet in facets)
                    {
                        if (facet is XmlSchemaLengthFacet ||
                            facet is XmlSchemaMaxLengthFacet ||
                            facet is XmlSchemaMinLengthFacet ||
                            facet is XmlSchemaEnumerationFacet ||
                            facet is XmlSchemaPatternFacet)
                        {
                            continue;
                        }
                        else
                        {
                            error(h, "Not allowed facet was found on this simple type which derives list type.");
                        }
                    }
                }
                break;

            case XmlSchemaDerivationMethod.Union:
                // 3.1

                // 3.2
                if (facets != null)
                {
                    foreach (XmlSchemaFacet facet in facets)
                    {
                        if (facet is XmlSchemaEnumerationFacet ||
                            facet is XmlSchemaPatternFacet)
                        {
                            continue;
                        }
                        else
                        {
                            error(h, "Not allowed facet was found on this simple type which derives list type.");
                        }
                    }
                }
                break;
            }
        }
Esempio n. 49
0
 public ListSimpleTypeValidator(XmlSchemaSimpleType type,
                             RestrictionFacets facets,
                             SimpleTypeValidator itemType)
     : base(XmlSchemaDatatypeVariety.List, type, FacetsChecker.ListFacetsChecker, facets) {
     this.itemType = itemType;
 }
        /// <summary>
        /// Schema Component:
        ///			QName, SimpleType, Scope, Default|Fixed, annotation
        /// </summary>
        internal override int Validate(ValidationEventHandler h, XmlSchema schema)
        {
            if (IsValidated(schema.ValidationId))
            {
                return(errorCount);
            }

            // -- Attribute Declaration Schema Component --
            // {name}, {target namespace} -> QualifiedName. Already Compile()d.
            // {type definition} -> attributeType. From SchemaType or SchemaTypeName.
            // {scope} -> ParentIsSchema | isRedefineChild.
            // {value constraint} -> ValidatedFixedValue, ValidatedDefaultValue.
            // {annotation}
            // -- Attribute Use Schema Component --
            // {required}
            // {attribute declaration}
            // {value constraint}

            // First, fill type information for type reference
            if (SchemaType != null)
            {
                SchemaType.Validate(h, schema);
                attributeType = SchemaType;
            }
            else if (SchemaTypeName != null && SchemaTypeName != XmlQualifiedName.Empty)
            {
                // If type is null, then it is missing sub components .
                XmlSchemaType type = schema.FindSchemaType(SchemaTypeName);
                if (type is XmlSchemaComplexType)
                {
                    error(h, "An attribute can't have complexType Content");
                }
                else if (type != null)  // simple type
                {
                    errorCount   += type.Validate(h, schema);
                    attributeType = type;
                }
                else if (SchemaTypeName == XmlSchemaComplexType.AnyTypeName)
                {
                    attributeType = XmlSchemaComplexType.AnyType;
                }
                else if (XmlSchemaUtil.IsBuiltInDatatypeName(SchemaTypeName))
                {
                    attributeType = XmlSchemaDatatype.FromName(SchemaTypeName);
                    if (attributeType == null)
                    {
                        error(h, "Invalid xml schema namespace datatype was specified.");
                    }
                }
                // otherwise, it might be missing sub components.
                else if (!schema.IsNamespaceAbsent(SchemaTypeName.Namespace))
                {
                    error(h, "Referenced schema type " + SchemaTypeName + " was not found in the corresponding schema.");
                }
            }

            // Then, fill type information for the type references for the referencing attributes
            if (RefName != null && RefName != XmlQualifiedName.Empty)
            {
                referencedAttribute = schema.FindAttribute(RefName);
                // If el is null, then it is missing sub components .
                if (referencedAttribute != null)
                {
                    errorCount += referencedAttribute.Validate(h, schema);
                }
                // otherwise, it might be missing sub components.
                else if (!schema.IsNamespaceAbsent(RefName.Namespace))
                {
                    error(h, "Referenced attribute " + RefName + " was not found in the corresponding schema.");
                }
            }

            if (attributeType == null)
            {
                attributeType = XmlSchemaSimpleType.AnySimpleType;
            }

            // Validate {value constraints}
            if (defaultValue != null || fixedValue != null)
            {
                XmlSchemaDatatype datatype = attributeType as XmlSchemaDatatype;
                if (datatype == null)
                {
                    datatype = ((XmlSchemaSimpleType)attributeType).Datatype;
                }
                if (datatype.TokenizedType == XmlTokenizedType.QName)
                {
                    error(h, "By the defection of the W3C XML Schema specification, it is impossible to supply QName default or fixed values.");
                }
                else
                {
                    try
                    {
                        if (defaultValue != null)
                        {
                            validatedDefaultValue = datatype.Normalize(defaultValue);
                            datatype.ParseValue(validatedDefaultValue, null, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        // FIXME: This is not a good way to handle exception.
                        error(h, "The Attribute's default value is invalid with its type definition.", ex);
                    }
                    try
                    {
                        if (fixedValue != null)
                        {
                            validatedFixedValue      = datatype.Normalize(fixedValue);
                            validatedFixedTypedValue = datatype.ParseValue(validatedFixedValue, null, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        // FIXME: This is not a good way to handle exception.
                        error(h, "The Attribute's fixed value is invalid with its type definition.", ex);
                    }
                }
            }
            if (Use == XmlSchemaUse.None)
            {
                validatedUse = XmlSchemaUse.Optional;
            }
            else
            {
                validatedUse = Use;
            }

#if NET_2_0
            if (attributeType != null)
            {
                attributeSchemaType = attributeType as XmlSchemaSimpleType;
                if (attributeType == XmlSchemaSimpleType.AnySimpleType)
                {
                    attributeSchemaType = XmlSchemaSimpleType.XsAnySimpleType;
                }
                if (attributeSchemaType == null)
                {
                    attributeSchemaType = XmlSchemaType.GetBuiltInSimpleType(SchemaTypeName);
                }
            }
#endif

            ValidationId = schema.ValidationId;
            return(errorCount);
        }
 private XmlSchemaSimpleType[] CompileBaseMemberTypes(XmlSchemaSimpleType simpleType)
 {
     ArrayList memberTypeDefinitions = new ArrayList();
     XmlSchemaSimpleTypeUnion content = (XmlSchemaSimpleTypeUnion) simpleType.Content;
     XmlQualifiedName[] memberTypes = content.MemberTypes;
     if (memberTypes != null)
     {
         for (int i = 0; i < memberTypes.Length; i++)
         {
             XmlSchemaSimpleType unionMember = this.GetSimpleType(memberTypes[i]);
             if (unionMember == null)
             {
                 throw new XmlSchemaException("Sch_UndeclaredSimpleType", memberTypes[i].ToString(), simpleType);
             }
             if (unionMember.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
             {
                 this.CheckUnionType(unionMember, memberTypeDefinitions, simpleType);
             }
             else
             {
                 memberTypeDefinitions.Add(unionMember);
             }
             if ((unionMember.FinalResolved & XmlSchemaDerivationMethod.Union) != XmlSchemaDerivationMethod.Empty)
             {
                 base.SendValidationEvent("Sch_BaseFinalUnion", simpleType);
             }
         }
     }
     XmlSchemaObjectCollection baseTypes = content.BaseTypes;
     if (baseTypes != null)
     {
         for (int j = 0; j < baseTypes.Count; j++)
         {
             XmlSchemaSimpleType type2 = (XmlSchemaSimpleType) baseTypes[j];
             this.CompileSimpleType(type2);
             if (type2.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
             {
                 this.CheckUnionType(type2, memberTypeDefinitions, simpleType);
             }
             else
             {
                 memberTypeDefinitions.Add(type2);
             }
         }
     }
     content.SetBaseMemberTypes(memberTypeDefinitions.ToArray(typeof(XmlSchemaSimpleType)) as XmlSchemaSimpleType[]);
     return content.BaseMemberTypes;
 }
Esempio n. 52
0
        //<list
        //  id = ID
        //  itemType = QName
        //  {any attributes with non-schema namespace . . .}>
        //  Content: (annotation?, (simpleType?))
        //</list>
        internal static XmlSchemaSimpleTypeList Read(XmlSchemaReader reader, ValidationEventHandler h)
        {
            XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();

            reader.MoveToElement();

            if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
            {
                error(h, "Should not happen :1: XmlSchemaSimpleTypeList.Read, name=" + reader.Name, null);
                reader.Skip();
                return(null);
            }

            list.LineNumber   = reader.LineNumber;
            list.LinePosition = reader.LinePosition;
            list.SourceUri    = reader.BaseURI;

            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "id")
                {
                    list.Id = reader.Value;
                }
                else if (reader.Name == "itemType")
                {
                    Exception innerex;
                    list.ItemTypeName = XmlSchemaUtil.ReadQNameAttribute(reader, out innerex);
                    if (innerex != null)
                    {
                        error(h, reader.Value + " is not a valid value for itemType attribute", innerex);
                    }
                }
                else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
                {
                    error(h, reader.Name + " is not a valid attribute for list", null);
                }
                else
                {
                    XmlSchemaUtil.ReadUnhandledAttribute(reader, list);
                }
            }

            reader.MoveToElement();
            if (reader.IsEmptyElement)
            {
                return(list);
            }
            //  Content: annotation?, simpleType?
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchemaSimpleTypeList.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1 && reader.LocalName == "annotation")
                {
                    level = 2;                     //Only one annotation
                    XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                    if (annotation != null)
                    {
                        list.Annotation = annotation;
                    }
                    continue;
                }
                if (level <= 2 && reader.LocalName == "simpleType")
                {
                    level = 3;
                    XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h);
                    if (stype != null)
                    {
                        list.itemType = stype;
                    }
                    continue;
                }
                reader.RaiseInvalidElementError();
            }
            return(list);
        }
 private void CheckUnionType(XmlSchemaSimpleType unionMember, ArrayList memberTypeDefinitions, XmlSchemaSimpleType parentType)
 {
     XmlSchemaDatatype datatype = unionMember.Datatype;
     if ((unionMember.DerivedBy == XmlSchemaDerivationMethod.Restriction) && (datatype.HasLexicalFacets || datatype.HasValueFacets))
     {
         base.SendValidationEvent("Sch_UnionFromUnion", parentType);
     }
     else
     {
         Datatype_union _union = unionMember.Datatype as Datatype_union;
         memberTypeDefinitions.AddRange(_union.BaseMemberTypes);
     }
 }
Esempio n. 54
0
        void DoCompile(ValidationEventHandler handler, Hashtable handledUris, XmlSchemaSet col, XmlResolver resolver)
        {
            SetParent();
            CompilationId = col.CompilationId;
            schemas       = col;
            if (!schemas.Contains(this))              // e.g. xs:import
            {
                schemas.Add(this);
            }

            attributeGroups.Clear();
            attributes.Clear();
            elements.Clear();
            groups.Clear();
            notations.Clear();
            schemaTypes.Clear();

            //1. Union and List are not allowed in block default
            if (BlockDefault != XmlSchemaDerivationMethod.All)
            {
                if ((BlockDefault & XmlSchemaDerivationMethod.List) != 0)
                {
                    error(handler, "list is not allowed in blockDefault attribute");
                }
                if ((BlockDefault & XmlSchemaDerivationMethod.Union) != 0)
                {
                    error(handler, "union is not allowed in blockDefault attribute");
                }
            }

            //2. Substitution is not allowed in finaldefault.
            if (FinalDefault != XmlSchemaDerivationMethod.All)
            {
                if ((FinalDefault & XmlSchemaDerivationMethod.Substitution) != 0)
                {
                    error(handler, "substitution is not allowed in finalDefault attribute");
                }
            }

            //3. id must be of type ID
            XmlSchemaUtil.CompileID(Id, this, col.IDCollection, handler);

            //4. targetNamespace should be of type anyURI or absent
            if (TargetNamespace != null)
            {
                if (TargetNamespace.Length == 0)
                {
                    error(handler, "The targetNamespace attribute cannot have have empty string as its value.");
                }

                if (!XmlSchemaUtil.CheckAnyUri(TargetNamespace))
                {
                    error(handler, TargetNamespace + " is not a valid value for targetNamespace attribute of schema");
                }
            }

            //5. version should be of type normalizedString
            if (!XmlSchemaUtil.CheckNormalizedString(Version))
            {
                error(handler, Version + "is not a valid value for version attribute of schema");
            }

            // Compile the content of this schema

            compilationItems = new XmlSchemaObjectCollection();
            for (int i = 0; i < Items.Count; i++)
            {
                compilationItems.Add(Items [i]);
            }

            // First, we run into inclusion schemas to collect
            // compilation target items into compiledItems.
            for (int i = 0; i < Includes.Count; i++)
            {
                ProcessExternal(handler, handledUris, resolver, Includes [i] as XmlSchemaExternal, col);
            }

            // Compilation phase.
            // At least each Compile() must give unique (qualified) name for each component.
            // It also checks self-resolvable properties correctness.
            // Post compilation schema information contribution is not done here.
            // It should be done by Validate().
            for (int i = 0; i < compilationItems.Count; i++)
            {
                XmlSchemaObject obj = compilationItems [i];
                if (obj is XmlSchemaAnnotation)
                {
                    int numerr = ((XmlSchemaAnnotation)obj).Compile(handler, this);
                    errorCount += numerr;
                }
                else if (obj is XmlSchemaAttribute)
                {
                    XmlSchemaAttribute attr = (XmlSchemaAttribute)obj;
                    int numerr = attr.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(Attributes, attr, attr.QualifiedName, handler);
                    }
                }
                else if (obj is XmlSchemaAttributeGroup)
                {
                    XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup)obj;
                    int numerr = attrgrp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            AttributeGroups,
                            attrgrp,
                            attrgrp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType ctype = (XmlSchemaComplexType)obj;
                    int numerr = ctype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            schemaTypes,
                            ctype,
                            ctype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaSimpleType)
                {
                    XmlSchemaSimpleType stype = (XmlSchemaSimpleType)obj;
                    stype.islocal = false;                     //This simple type is toplevel
                    int numerr = stype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            SchemaTypes,
                            stype,
                            stype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaElement)
                {
                    XmlSchemaElement elem = (XmlSchemaElement)obj;
                    elem.parentIsSchema = true;
                    int numerr = elem.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Elements,
                            elem,
                            elem.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaGroup)
                {
                    XmlSchemaGroup grp    = (XmlSchemaGroup)obj;
                    int            numerr = grp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Groups,
                            grp,
                            grp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaNotation)
                {
                    XmlSchemaNotation ntn = (XmlSchemaNotation)obj;
                    int numerr            = ntn.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Notations,
                            ntn,
                            ntn.QualifiedName,
                            handler);
                    }
                }
                else
                {
                    ValidationHandler.RaiseValidationEvent(
                        handler,
                        null,
                        String.Format("Object of Type {0} is not valid in Item Property of Schema", obj.GetType().Name),
                        null,
                        this,
                        null,
                        XmlSeverityType.Error);
                }
            }
        }
 internal void SetAttributeType(XmlSchemaSimpleType value) { 
     attributeType = value;
 }
Esempio n. 56
0
        private static void ReadContent(XmlSchema schema, XmlSchemaReader reader, ValidationEventHandler h)
        {
            reader.MoveToElement();
            if (reader.LocalName != "schema" && reader.NamespaceURI != XmlSchema.Namespace && reader.NodeType != XmlNodeType.Element)
            {
                error(h, "UNREACHABLE CODE REACHED: Method: Schema.ReadContent, " + reader.LocalName + ", " + reader.NamespaceURI, null);
            }

            //(include | import | redefine | annotation)*,
            //((simpleType | complexType | group | attributeGroup | element | attribute | notation | annotation)*
            int level = 1;

            while (reader.ReadNextElement())
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    if (reader.LocalName != xmlname)
                    {
                        error(h, "Should not happen :2: XmlSchema.Read, name=" + reader.Name, null);
                    }
                    break;
                }
                if (level <= 1)
                {
                    if (reader.LocalName == "include")
                    {
                        XmlSchemaInclude include = XmlSchemaInclude.Read(reader, h);
                        if (include != null)
                        {
                            schema.includes.Add(include);
                        }
                        continue;
                    }
                    if (reader.LocalName == "import")
                    {
                        XmlSchemaImport import = XmlSchemaImport.Read(reader, h);
                        if (import != null)
                        {
                            schema.includes.Add(import);
                        }
                        continue;
                    }
                    if (reader.LocalName == "redefine")
                    {
                        XmlSchemaRedefine redefine = XmlSchemaRedefine.Read(reader, h);
                        if (redefine != null)
                        {
                            schema.includes.Add(redefine);
                        }
                        continue;
                    }
                    if (reader.LocalName == "annotation")
                    {
                        XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                        if (annotation != null)
                        {
                            schema.items.Add(annotation);
                        }
                        continue;
                    }
                }
                if (level <= 2)
                {
                    level = 2;
                    if (reader.LocalName == "simpleType")
                    {
                        XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h);
                        if (stype != null)
                        {
                            schema.items.Add(stype);
                        }
                        continue;
                    }
                    if (reader.LocalName == "complexType")
                    {
                        XmlSchemaComplexType ctype = XmlSchemaComplexType.Read(reader, h);
                        if (ctype != null)
                        {
                            schema.items.Add(ctype);
                        }
                        continue;
                    }
                    if (reader.LocalName == "group")
                    {
                        XmlSchemaGroup group = XmlSchemaGroup.Read(reader, h);
                        if (group != null)
                        {
                            schema.items.Add(group);
                        }
                        continue;
                    }
                    if (reader.LocalName == "attributeGroup")
                    {
                        XmlSchemaAttributeGroup attributeGroup = XmlSchemaAttributeGroup.Read(reader, h);
                        if (attributeGroup != null)
                        {
                            schema.items.Add(attributeGroup);
                        }
                        continue;
                    }
                    if (reader.LocalName == "element")
                    {
                        XmlSchemaElement element = XmlSchemaElement.Read(reader, h);
                        if (element != null)
                        {
                            schema.items.Add(element);
                        }
                        continue;
                    }
                    if (reader.LocalName == "attribute")
                    {
                        XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader, h);
                        if (attr != null)
                        {
                            schema.items.Add(attr);
                        }
                        continue;
                    }
                    if (reader.LocalName == "notation")
                    {
                        XmlSchemaNotation notation = XmlSchemaNotation.Read(reader, h);
                        if (notation != null)
                        {
                            schema.items.Add(notation);
                        }
                        continue;
                    }
                    if (reader.LocalName == "annotation")
                    {
                        XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h);
                        if (annotation != null)
                        {
                            schema.items.Add(annotation);
                        }
                        continue;
                    }
                }
                reader.RaiseInvalidElementError();
            }
        }
 private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local)
 {
     if (local)
     {
         if (simpleType.Name != null)
         {
             base.SendValidationEvent("Sch_ForbiddenAttribute", "name", simpleType);
         }
     }
     else
     {
         if (simpleType.Name != null)
         {
             this.ValidateNameAttribute(simpleType);
             simpleType.SetQualifiedName(new XmlQualifiedName(simpleType.Name, this.targetNamespace));
         }
         else
         {
             base.SendValidationEvent("Sch_MissRequiredAttribute", "name", simpleType);
         }
         if (simpleType.Final == XmlSchemaDerivationMethod.All)
         {
             simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
         }
         else if (simpleType.Final == XmlSchemaDerivationMethod.None)
         {
             if (this.finalDefault == XmlSchemaDerivationMethod.All)
             {
                 simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
             }
             else
             {
                 simpleType.SetFinalResolved(this.finalDefault & (XmlSchemaDerivationMethod.Union | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension));
             }
         }
         else
         {
             if ((simpleType.Final & ~(XmlSchemaDerivationMethod.Union | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension)) != XmlSchemaDerivationMethod.Empty)
             {
                 base.SendValidationEvent("Sch_InvalidSimpleTypeFinalValue", simpleType);
             }
             simpleType.SetFinalResolved(simpleType.Final & (XmlSchemaDerivationMethod.Union | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension));
         }
     }
     if (simpleType.Content == null)
     {
         base.SendValidationEvent("Sch_NoSimpleTypeContent", simpleType);
     }
     else if (simpleType.Content is XmlSchemaSimpleTypeRestriction)
     {
         XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction) simpleType.Content;
         this.SetParent(content, simpleType);
         for (int i = 0; i < content.Facets.Count; i++)
         {
             this.SetParent(content.Facets[i], content);
         }
         if (content.BaseType != null)
         {
             if (!content.BaseTypeName.IsEmpty)
             {
                 base.SendValidationEvent("Sch_SimpleTypeRestRefBase", content);
             }
             this.PreprocessSimpleType(content.BaseType, true);
         }
         else if (content.BaseTypeName.IsEmpty)
         {
             base.SendValidationEvent("Sch_SimpleTypeRestRefBaseNone", content);
         }
         else
         {
             this.ValidateQNameAttribute(content, "base", content.BaseTypeName);
         }
         this.PreprocessAnnotation(content);
         this.ValidateIdAttribute(content);
     }
     else if (simpleType.Content is XmlSchemaSimpleTypeList)
     {
         XmlSchemaSimpleTypeList child = (XmlSchemaSimpleTypeList) simpleType.Content;
         this.SetParent(child, simpleType);
         if (child.ItemType != null)
         {
             if (!child.ItemTypeName.IsEmpty)
             {
                 base.SendValidationEvent("Sch_SimpleTypeListRefBase", child);
             }
             this.SetParent(child.ItemType, child);
             this.PreprocessSimpleType(child.ItemType, true);
         }
         else if (child.ItemTypeName.IsEmpty)
         {
             base.SendValidationEvent("Sch_SimpleTypeListRefBaseNone", child);
         }
         else
         {
             this.ValidateQNameAttribute(child, "itemType", child.ItemTypeName);
         }
         this.PreprocessAnnotation(child);
         this.ValidateIdAttribute(child);
     }
     else
     {
         XmlSchemaSimpleTypeUnion union = (XmlSchemaSimpleTypeUnion) simpleType.Content;
         this.SetParent(union, simpleType);
         int count = union.BaseTypes.Count;
         if (union.MemberTypes != null)
         {
             count += union.MemberTypes.Length;
             XmlQualifiedName[] memberTypes = union.MemberTypes;
             for (int k = 0; k < memberTypes.Length; k++)
             {
                 this.ValidateQNameAttribute(union, "memberTypes", memberTypes[k]);
             }
         }
         if (count == 0)
         {
             base.SendValidationEvent("Sch_SimpleTypeUnionNoBase", union);
         }
         for (int j = 0; j < union.BaseTypes.Count; j++)
         {
             XmlSchemaSimpleType type = (XmlSchemaSimpleType) union.BaseTypes[j];
             this.SetParent(type, union);
             this.PreprocessSimpleType(type, true);
         }
         this.PreprocessAnnotation(union);
         this.ValidateIdAttribute(union);
     }
     this.ValidateIdAttribute(simpleType);
 }
Esempio n. 58
0
        static XmlSchemaSimpleType()
        {
            // This is not used in the meantime.
            XmlSchemaSimpleType     st   = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();

            list.ItemTypeName            = new XmlQualifiedName("anyURI", XmlSchema.Namespace);
            st.Content                   = list;
            st.BaseXmlSchemaTypeInternal = null;
            st.variety                   = XmlSchemaDerivationMethod.List;
            schemaLocationType           = st;

#if NET_2_0
            // Built-In schema types
            XsAnySimpleType = BuildSchemaType("anySimpleType", null);
            XsString        = BuildSchemaType("string", "anySimpleType");
            XsBoolean       = BuildSchemaType("boolean", "anySimpleType");
            XsDecimal       = BuildSchemaType("decimal", "anySimpleType");
            XsFloat         = BuildSchemaType("float", "anySimpleType");
            XsDouble        = BuildSchemaType("double", "anySimpleType");
            XsDuration      = BuildSchemaType("duration", "anySimpleType");
            XsDateTime      = BuildSchemaType("dateTime", "anySimpleType");
            XsTime          = BuildSchemaType("time", "anySimpleType");
            XsDate          = BuildSchemaType("date", "anySimpleType");
            XsGYearMonth    = BuildSchemaType("gYearMonth", "anySimpleType");
            XsGYear         = BuildSchemaType("gYear", "anySimpleType");
            XsGMonthDay     = BuildSchemaType("gMonthDay", "anySimpleType");
            XsGDay          = BuildSchemaType("gDay", "anySimpleType");
            XsGMonth        = BuildSchemaType("gMonth", "anySimpleType");
            XsHexBinary     = BuildSchemaType("hexBinary", "anySimpleType");
            XsBase64Binary  = BuildSchemaType("base64Binary", "anySimpleType");
            XsAnyUri        = BuildSchemaType("anyURI", "anySimpleType");
            XsQName         = BuildSchemaType("QName", "anySimpleType");
            XsNotation      = BuildSchemaType("NOTATION", "anySimpleType");
            // derived types
            XsNormalizedString = BuildSchemaType("normalizedString", "string");
            XsToken            = BuildSchemaType("token", "normalizedString");
            XsLanguage         = BuildSchemaType("language", "token");
            XsNMToken          = BuildSchemaType("NMTOKEN", "token");
            XsName             = BuildSchemaType("Name", "token");
            XsNCName           = BuildSchemaType("NCName", "Name");

            XsID     = BuildSchemaType("ID", "NCName");
            XsIDRef  = BuildSchemaType("IDREF", "NCName");
            XsEntity = BuildSchemaType("ENTITY", "NCName");

            XsInteger            = BuildSchemaType("integer", "decimal");
            XsNonPositiveInteger = BuildSchemaType("nonPositiveInteger", "integer");
            XsNegativeInteger    = BuildSchemaType("negativeInteger", "nonPositiveInteger");
            XsLong  = BuildSchemaType("long", "integer");
            XsInt   = BuildSchemaType("int", "long");
            XsShort = BuildSchemaType("short", "int");
            XsByte  = BuildSchemaType("byte", "short");
            XsNonNegativeInteger = BuildSchemaType("nonNegativeInteger", "integer");
            XsUnsignedLong       = BuildSchemaType("unsignedLong", "nonNegativeInteger");
            XsUnsignedInt        = BuildSchemaType("unsignedInt", "unsignedLong");
            XsUnsignedShort      = BuildSchemaType("unsignedShort", "unsignedInt");
            XsUnsignedByte       = BuildSchemaType("unsignedByte", "unsignedShort");
            XsPositiveInteger    = BuildSchemaType("positiveInteger", "nonNegativeInteger");

            // xdt:*
            XdtAnyAtomicType     = BuildSchemaType("anyAtomicType", "anySimpleType", true, false);
            XdtUntypedAtomic     = BuildSchemaType("untypedAtomic", "anyAtomicType", true, true);
            XdtDayTimeDuration   = BuildSchemaType("dayTimeDuration", "duration", true, false);
            XdtYearMonthDuration = BuildSchemaType("yearMonthDuration", "duration", true, false);

            // NMTOKENS, IDREFS, ENTITIES - lists
            XsIDRefs = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeList sl = new XmlSchemaSimpleTypeList();
            sl.ItemType      = XsIDRef;
            XsIDRefs.Content = sl;
            XsEntities       = new XmlSchemaSimpleType();
            sl                 = new XmlSchemaSimpleTypeList();
            sl.ItemType        = XsEntity;
            XsEntities.Content = sl;
            XsNMTokens         = new XmlSchemaSimpleType();
            sl                 = new XmlSchemaSimpleTypeList();
            sl.ItemType        = XsNMToken;
            XsNMTokens.Content = sl;
#endif
        }
Esempio n. 59
0
        /// <summary>
        /// Gets the enum schema.
        /// </summary>
        /// <param name="t">The t.</param>
        /// <returns>schema info</returns>
        public static SchemaInfo GetEnumSchema(this Type t)
        {
            if (!t.IsEnum)
            {
                return null;
            }

            var schemaInfo = new SchemaInfo();
            var classType = new XmlSchemaSimpleType
                                {
                                    Name = t.Name
                                };

            var attribData = t.GetCustomAttributeDataOfType(typeof(DataContractAttribute));
            if (attribData.NamedArguments != null && attribData.NamedArguments.Count > 0)
            {
                foreach (var p1 in attribData.NamedArguments)
                {
                    switch (p1.MemberInfo.Name)
                    {
                        case "Namespace":
                            schemaInfo.Schema.TargetNamespace = p1.TypedValue.Value as string;
                            break;
                    }
                }
            }

            var content = new XmlSchemaSimpleTypeRestriction();
            classType.Content = content;

            content.BaseTypeName = typeof(string).XmlName();
            foreach (var e in t.GetEnumNames())
            {
                content.Facets.Add(new XmlSchemaEnumerationFacet
                                       {
                                           Value = e
                                       });
            }

            schemaInfo.Schema.Items.Add(classType);
            return schemaInfo;
        }
Esempio n. 60
0
        internal override int Validate(ValidationEventHandler h, XmlSchema schema)
        {
            // 3.14.6 Properties Correct.
            //
            // 1. Post Compilation Properties
            // {name}, {target namespace} => QNameInternal. Already Compile()d.
            // {base type definition} => baseSchemaTypeInternal
            // {final} => finalResolved. Already Compile()d.
            // {variety} => resolvedDerivedBy. Already Compile()d.
            //
            // 2. Should be checked by "recursed" field.

            if (IsValidated(schema.ValidationId))
            {
                return(errorCount);
            }

            if (recursed)
            {
                error(h, "Circular type reference was found.");
                return(errorCount);
            }
            recursed = true;

            CollectBaseType(h, schema);

            if (content != null)
            {
                errorCount += content.Validate(h, schema);
            }

            /*
             *                      // BaseSchemaType property
             *                      BaseXmlSchemaTypeInternal = content.ActualBaseSchemaType as XmlSchemaType;
             *                      if (this.BaseXmlSchemaTypeInternal == null)
             *                              this.DatatypeInternal = content.ActualBaseSchemaType as XmlSchemaDatatype;
             */

            // Datatype property
            XmlSchemaSimpleType simple = BaseXmlSchemaType as XmlSchemaSimpleType;

            if (simple != null)
            {
                this.DatatypeInternal = simple.Datatype;
            }
//			else
//				DatatypeInternal = BaseSchemaType as XmlSchemaDatatype;

            // 3.
            XmlSchemaSimpleType baseSType = BaseXmlSchemaType as XmlSchemaSimpleType;

            if (baseSType != null)
            {
                if ((baseSType.FinalResolved & this.resolvedDerivedBy) != 0)
                {
                    error(h, "Specified derivation is prohibited by the base simple type.");
                }
            }

            // {variety}
            if (this.resolvedDerivedBy == XmlSchemaDerivationMethod.Restriction &&
                baseSType != null)
            {
                this.variety = baseSType.Variety;
            }
            else
            {
                this.variety = this.resolvedDerivedBy;
            }

            // 3.14.6 Derivation Valid (Restriction, Simple)
            XmlSchemaSimpleTypeRestriction r = Content as XmlSchemaSimpleTypeRestriction;
            object baseType = BaseXmlSchemaType != null ? (object)BaseXmlSchemaType : Datatype;

            if (r != null)
            {
                ValidateDerivationValid(baseType, r.Facets, h, schema);
            }

            // TODO: describe which validation term this belongs to.
            XmlSchemaSimpleTypeList l = Content as XmlSchemaSimpleTypeList;

            if (l != null)
            {
                XmlSchemaSimpleType itemSimpleType = l.ValidatedListItemType as XmlSchemaSimpleType;
                if (itemSimpleType != null && itemSimpleType.Content is XmlSchemaSimpleTypeList)
                {
                    error(h, "List type must not be derived from another list type.");
                }
            }

            recursed     = false;
            ValidationId = schema.ValidationId;
            return(errorCount);
        }