Ejemplo n.º 1
0
		internal XmlSchemaInfo (IXmlSchemaInfo info)
		{
			isDefault = info.IsDefault;
			isNil = info.IsNil;
			memberType = info.MemberType;
			attr = info.SchemaAttribute;
			elem = info.SchemaElement;
			type = info.SchemaType;
			validity = info.Validity;
		}
Ejemplo n.º 2
0
        private static XmlSchema CreateFakeSoapEncodingSchema(string ns, string name)
        {
            XmlSchema schema1 = new XmlSchema();

            schema1.TargetNamespace = ns;
            XmlSchemaGroup group1 = new XmlSchemaGroup();

            group1.Name = "Array";
            XmlSchemaSequence sequence1 = new XmlSchemaSequence();
            XmlSchemaAny      any1      = new XmlSchemaAny();

            any1.MinOccurs = new decimal(0);
            any1.MaxOccurs = new decimal(-1, -1, -1, false, 0);
            sequence1.Items.Add(any1);
            any1.Namespace       = "##any";
            any1.ProcessContents = XmlSchemaContentProcessing.Lax;
            group1.Particle      = sequence1;
            schema1.Items.Add(group1);
            XmlSchemaComplexType type1 = new XmlSchemaComplexType();

            type1.Name = name;
            XmlSchemaGroupRef ref1 = new XmlSchemaGroupRef();

            ref1.RefName   = new XmlQualifiedName("Array", ns);
            type1.Particle = ref1;
            XmlSchemaAttribute attribute1 = new XmlSchemaAttribute();

            attribute1.RefName = new XmlQualifiedName("arrayType", ns);
            type1.Attributes.Add(attribute1);
            schema1.Items.Add(type1);
            attribute1      = new XmlSchemaAttribute();
            attribute1.Use  = XmlSchemaUse.None;
            attribute1.Name = "arrayType";
            schema1.Items.Add(attribute1);
            AddSimpleType(schema1, "base64", "base64Binary");
            AddElementAndType(schema1, "anyURI", ns);
            AddElementAndType(schema1, "base64Binary", ns);
            AddElementAndType(schema1, "boolean", ns);
            AddElementAndType(schema1, "byte", ns);
            AddElementAndType(schema1, "date", ns);
            AddElementAndType(schema1, "dateTime", ns);
            AddElementAndType(schema1, "decimal", ns);
            AddElementAndType(schema1, "double", ns);
            AddElementAndType(schema1, "duration", ns);
            AddElementAndType(schema1, "ENTITIES", ns);
            AddElementAndType(schema1, "ENTITY", ns);
            AddElementAndType(schema1, "float", ns);
            AddElementAndType(schema1, "gDay", ns);
            AddElementAndType(schema1, "gMonth", ns);
            AddElementAndType(schema1, "gMonthDay", ns);
            AddElementAndType(schema1, "gYear", ns);
            AddElementAndType(schema1, "gYearMonth", ns);
            AddElementAndType(schema1, "hexBinary", ns);
            AddElementAndType(schema1, "ID", ns);
            AddElementAndType(schema1, "IDREF", ns);
            AddElementAndType(schema1, "IDREFS", ns);
            AddElementAndType(schema1, "int", ns);
            AddElementAndType(schema1, "integer", ns);
            AddElementAndType(schema1, "language", ns);
            AddElementAndType(schema1, "long", ns);
            AddElementAndType(schema1, "Name", ns);
            AddElementAndType(schema1, "NCName", ns);
            AddElementAndType(schema1, "negativeInteger", ns);
            AddElementAndType(schema1, "NMTOKEN", ns);
            AddElementAndType(schema1, "NMTOKENS", ns);
            AddElementAndType(schema1, "nonNegativeInteger", ns);
            AddElementAndType(schema1, "nonPositiveInteger", ns);
            AddElementAndType(schema1, "normalizedString", ns);
            AddElementAndType(schema1, "positiveInteger", ns);
            AddElementAndType(schema1, "QName", ns);
            AddElementAndType(schema1, "short", ns);
            AddElementAndType(schema1, "string", ns);
            AddElementAndType(schema1, "time", ns);
            AddElementAndType(schema1, "token", ns);
            AddElementAndType(schema1, "unsignedByte", ns);
            AddElementAndType(schema1, "unsignedInt", ns);
            AddElementAndType(schema1, "unsignedLong", ns);
            AddElementAndType(schema1, "unsignedShort", ns);
            return(schema1);
        }
Ejemplo n.º 3
0
        void PopulatePluginType(XmlSchemaComplexType complexType, PluginElementAttribute pluginAttr)
        {
            if (pluginAttr.Named)
            {
                var nameAttr = new XmlSchemaAttribute();
                nameAttr.Name = "name";
                nameAttr.Annotate("{0} name.".Fmt(pluginAttr.PluginType.Name));
                nameAttr.Use = XmlSchemaUse.Optional;

                complexType.Attributes.Add(nameAttr);
            }

            var typeAttr = new XmlSchemaAttribute();

            typeAttr.Name = pluginAttr.AttributeName;
            typeAttr.Use  = XmlSchemaUse.Required;
            typeAttr.Annotate("Specify the class name of a Peach {0}. You can implement your own {1}s as needed.".Fmt(
                                  pluginAttr.PluginType.Name,
                                  pluginAttr.PluginType.Name.ToLower()
                                  ));

            var restrictEnum = new XmlSchemaSimpleTypeRestriction();

            restrictEnum.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);

            foreach (var item in ClassLoader.GetAllByAttribute <PluginAttribute>((t, a) => a.Type == pluginAttr.PluginType && a.IsDefault && !a.IsTest))
            {
                restrictEnum.Facets.Add(MakePluginFacet(item.Key, item.Value));
            }

            var enumType = new XmlSchemaSimpleType();

            enumType.Content = restrictEnum;

            var restrictLen = new XmlSchemaSimpleTypeRestriction();

            restrictLen.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);
            restrictLen.Facets.Add(new XmlSchemaMaxLengthFacet()
            {
                Value = "1024"
            });

            var userType = new XmlSchemaSimpleType();

            userType.Content = restrictLen;

            var union = new XmlSchemaSimpleTypeUnion();

            union.BaseTypes.Add(userType);
            union.BaseTypes.Add(enumType);

            var schemaType = new XmlSchemaSimpleType();

            schemaType.Content = union;

            typeAttr.SchemaType = schemaType;

            complexType.Attributes.Add(typeAttr);

            if (!objElemCache.ContainsKey(typeof(PluginParam)))
            {
                AddElement("Param", typeof(PluginParam), null);
            }


            var schemaElem = new XmlSchemaElement();

            schemaElem.RefName = new XmlQualifiedName("Param", schema.TargetNamespace);

            XmlSchemaGroupBase schemaParticle;

            if (pluginAttr.PluginType == typeof(Transformer))
            {
                schemaParticle = new XmlSchemaChoice();
                schemaParticle.MinOccursString = "0";
                schemaParticle.MaxOccursString = "unbounded";

                var transElem = new XmlSchemaElement();
                transElem.RefName = new XmlQualifiedName("Transformer", schema.TargetNamespace);
                schemaParticle.Items.Add(transElem);
            }
            else
            {
                schemaParticle             = new XmlSchemaSequence();
                schemaElem.MinOccursString = "0";
                schemaElem.MaxOccursString = "unbounded";
            }

            schemaParticle.Items.Add(schemaElem);

            complexType.Particle = schemaParticle;
        }
Ejemplo n.º 4
0
        XmlSchemaAttribute MakeAttribute(string name, PropertyInfo pi)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = pi.Name;
            }

            var defaultValue = pi.GetAttributes <DefaultValueAttribute>().FirstOrDefault();

            var attr = new XmlSchemaAttribute();

            attr.Name = name;
            attr.Annotate(pi);

            if (pi.PropertyType.IsEnum)
            {
                attr.SchemaType = GetEnumType(pi.PropertyType);
            }
            else
            {
                attr.SchemaTypeName = GetSchemaType(pi.PropertyType);
            }

            if (defaultValue != null)
            {
                attr.Use = XmlSchemaUse.Optional;

                if (defaultValue.Value != null)
                {
                    var valStr  = defaultValue.Value.ToString();
                    var valType = defaultValue.Value.GetType();

                    if (valType == typeof(bool))
                    {
                        valStr = XmlConvert.ToString((bool)defaultValue.Value);
                    }
                    else if (valType.IsEnum)
                    {
                        var enumType = valType.GetField(valStr);
                        var enumAttr = enumType.GetAttributes <XmlEnumAttribute>().FirstOrDefault();
                        if (enumAttr != null)
                        {
                            valStr = enumAttr.Name;
                        }
                    }

                    attr.DefaultValue = valStr;
                }
                else if (pi.PropertyType.IsEnum)
                {
                    var content = (XmlSchemaSimpleTypeRestriction)attr.SchemaType.Content;
                    var facet   = (XmlSchemaEnumerationFacet)content.Facets[0];
                    attr.DefaultValue = facet.Value;
                }
            }
            else
            {
                attr.Use = XmlSchemaUse.Required;
            }

            return(attr);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// If the attribute value found references another item in the schema
        /// return this instead of the attribute schema object. For example, if the
        /// user can select the attribute value and the code will work out the schema object pointed to by the ref
        /// or type attribute:
        ///
        /// xs:element ref="ref-name"
        /// xs:attribute type="type-name"
        /// </summary>
        /// <returns>
        /// The <paramref name="attribute"/> if no schema object was referenced.
        /// </returns>
        XmlSchemaObject GetSchemaObjectReferenced(XmlSchemaCompletionData currentSchemaCompletionData, XmlSchemaElement element, XmlSchemaAttribute attribute)
        {
            XmlSchemaObject schemaObject = null;

            if (IsXmlSchemaNamespace(element))
            {
                // Find attribute value.
                //fixme implement
                string attributeValue = "";// XmlParser.GetAttributeValueAtIndex(xml, index);
                if (attributeValue.Length == 0)
                {
                    return(attribute);
                }

                if (attribute.Name == "ref")
                {
                    schemaObject = FindSchemaObjectReference(attributeValue, currentSchemaCompletionData, element.Name);
                }
                else if (attribute.Name == "type")
                {
                    schemaObject = FindSchemaObjectType(attributeValue, currentSchemaCompletionData, element.Name);
                }
            }

            if (schemaObject != null)
            {
                return(schemaObject);
            }
            return(attribute);
        }
Ejemplo n.º 6
0
        static string GetSchemaItem(XmlSchemaObject o, string ns, string details)
        {
            if (o == null)
            {
                return(null);
            }
            while (o.Parent != null && !(o.Parent is XmlSchema))
            {
                o = o.Parent;
            }
            if (ns == null || ns.Length == 0)
            {
                XmlSchemaObject tmp = o;
                while (tmp.Parent != null)
                {
                    tmp = tmp.Parent;
                }
                if (tmp is XmlSchema)
                {
                    ns = ((XmlSchema)tmp).TargetNamespace;
                }
            }
            string item = null;

            if (o is XmlSchemaNotation)
            {
                item = Res.GetString(Res.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details);
            }
            else if (o is XmlSchemaGroup)
            {
                item = Res.GetString(Res.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details);
            }
            else if (o is XmlSchemaElement)
            {
                XmlSchemaElement e = ((XmlSchemaElement)o);
                if (e.Name == null || e.Name.Length == 0)
                {
                    XmlQualifiedName parentName = GetParentName(o);
                    // Element reference '{0}' declared in schema type '{1}' from namespace '{2}'
                    item = Res.GetString(Res.XmlSchemaElementReference, e.RefName.ToString(), parentName.Name, parentName.Namespace);
                }
                else
                {
                    item = Res.GetString(Res.XmlSchemaNamedItem, ns, "element", e.Name, details);
                }
            }
            else if (o is XmlSchemaType)
            {
                item = Res.GetString(Res.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", ((XmlSchemaType)o).Name, details);
            }
            else if (o is XmlSchemaAttributeGroup)
            {
                item = Res.GetString(Res.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details);
            }
            else if (o is XmlSchemaAttribute)
            {
                XmlSchemaAttribute a = ((XmlSchemaAttribute)o);
                if (a.Name == null || a.Name.Length == 0)
                {
                    XmlQualifiedName parentName = GetParentName(o);
                    // Attribure reference '{0}' declared in schema type '{1}' from namespace '{2}'
                    return(Res.GetString(Res.XmlSchemaAttributeReference, a.RefName.ToString(), parentName.Name, parentName.Namespace));
                }
                else
                {
                    item = Res.GetString(Res.XmlSchemaNamedItem, ns, "attribute", a.Name, details);
                }
            }
            else if (o is XmlSchemaContent)
            {
                XmlQualifiedName parentName = GetParentName(o);
                // Check content definition of schema type '{0}' from namespace '{1}'. {2}
                item = Res.GetString(Res.XmlSchemaContentDef, parentName.Name, parentName.Namespace, details);
            }
            else if (o is XmlSchemaExternal)
            {
                string itemType = o is XmlSchemaImport ? "import" : o is XmlSchemaInclude ? "include" : o is XmlSchemaRedefine ? "redefine" : o.GetType().Name;
                item = Res.GetString(Res.XmlSchemaItem, ns, itemType, details);
            }
            else if (o is XmlSchema)
            {
                item = Res.GetString(Res.XmlSchema, ns, details);
            }
            else
            {
                item = Res.GetString(Res.XmlSchemaNamedItem, ns, o.GetType().Name, null, details);
            }

            return(item);
        }
Ejemplo n.º 7
0
        private void WriteHeaderAttribute(XmlSchema schema, XmlSchemaComplexType rootType, CremaDataTable dataTable)
        {
            var baseNamespace = dataTable.DataSet != null ? dataTable.DataSet.Namespace : CremaSchema.BaseNamespace;

            foreach (var item in EnumerableUtility.Friends(dataTable, dataTable.Childs))
            {
                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.CreatedDateTimeExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(DateTime)),
                    Use            = XmlSchemaUse.Optional
                });

                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.CreatorExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(string)),
                    Use            = XmlSchemaUse.Optional
                });

                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.ModifiedDateTimeExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(DateTime)),
                    Use            = XmlSchemaUse.Optional
                });

                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.ModifierExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(string)),
                    Use            = XmlSchemaUse.Optional
                });

                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.CountExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(int)),
                    Use            = XmlSchemaUse.Optional
                });

                rootType.Attributes.Add(new XmlSchemaAttribute()
                {
                    Name           = item.Name + CremaSchema.IDExtension,
                    SchemaTypeName = GetSystemQualifiedName(typeof(string)),
                    Use            = XmlSchemaUse.Optional
                });
            }

            if (schema.TargetNamespace != baseNamespace)
            {
                {
                    var attribute = new XmlSchemaAttribute()
                    {
                        Name = CremaSchema.Creator
                    };
                    attribute.WriteDescription("xml 문서를 생성한 사람의 이름을 설정합니다. 이 값은 선택적입니다.");
                    attribute.Use            = XmlSchemaUse.Optional;
                    attribute.SchemaTypeName = GetSystemQualifiedName(typeof(string));
                    rootType.Attributes.Add(attribute);
                }

                {
                    var attribute = new XmlSchemaAttribute()
                    {
                        Name = CremaSchema.CreatedDateTime
                    };
                    attribute.WriteDescription("xml 문서를 생성한 시간을 설정합니다. 이 값은 선택적입니다.");
                    attribute.Use            = XmlSchemaUse.Optional;
                    attribute.SchemaTypeName = GetSystemQualifiedName(typeof(DateTime));
                    rootType.Attributes.Add(attribute);
                }
            }
        }
Ejemplo n.º 8
0
        private void GenerateAttributeWildCard(XmlSchemaComplexType ct, InstanceElement elem)
        {
            char[]             whitespace = new char[] { ' ', '\t', '\n', '\r' };
            InstanceAttribute  attr       = null;
            XmlSchemaAttribute anyAttr    = null;

            XmlSchemaAnyAttribute attributeWildCard = ct.AttributeWildcard;
            XmlSchemaObjectTable  attributes        = ct.AttributeUses;

            string namespaceList = attributeWildCard.Namespace;

            if (namespaceList == null)
            {
                namespaceList = "##any";
            }
            if (attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Skip || attributeWildCard.ProcessContents == XmlSchemaContentProcessing.Lax)
            {
                if (namespaceList == "##any" || namespaceList == "##targetNamespace")
                {
                    attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", rootTargetNamespace));
                }
                else if (namespaceList == "##local")
                {
                    attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", string.Empty));
                }
                else if (namespaceList == "##other")
                {
                    attr = new InstanceAttribute(new XmlQualifiedName("any_Attr", "otherNS"));
                }
                if (attr != null)
                {
                    attr.ValueGenerator = XmlValueGenerator.AnySimpleTypeGenerator;
                    elem.AddAttribute(attr);
                    return;
                }
            }
            switch (namespaceList)
            {
            case "##any":
            case "##targetNamespace":
                anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes);
                break;

            case "##other":
                XmlSchema anySchema = GetParentSchema(attributeWildCard);
                anyAttr = GetAttributeFromNS(anySchema.TargetNamespace, true, attributes);
                break;

            case "##local":      //Shd get local elements in some schema
                anyAttr = GetAttributeFromNS(string.Empty, attributes);
                break;

            default:
                foreach (string ns in attributeWildCard.Namespace.Split(whitespace))
                {
                    if (ns == "##local")
                    {
                        anyAttr = GetAttributeFromNS(string.Empty, attributes);
                    }
                    else if (ns == "##targetNamespace")
                    {
                        anyAttr = GetAttributeFromNS(rootTargetNamespace, attributes);
                    }
                    else
                    {
                        anyAttr = GetAttributeFromNS(ns, attributes);
                    }
                    if (anyAttr != null)       //Found match
                    {
                        break;
                    }
                }
                break;
            }
            if (anyAttr != null)
            {
                GenerateInstanceAttribute(anyAttr, elem);
            }
            else                              //Write comment in generated XML that match for wild card cd not be found.
            {
                if (elem.Comment.Length == 0) //For multiple attribute wildcards in the same element, generate comment only once
                {
                    elem.Comment.Append(" Attribute Wild card could not be matched. Generated XML may not be valid. ");
                }
            }
        }
Ejemplo n.º 9
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:complexType name="customerOrderType">
        XmlSchemaComplexType customerOrderType = new XmlSchemaComplexType();

        customerOrderType.Name = "customerOrderType";

        // <xs:sequence>
        XmlSchemaSequence sequence1 = new XmlSchemaSequence();

        // <xs:element name="item" minOccurs="0" maxOccurs="unbounded">
        XmlSchemaElement item = new XmlSchemaElement();

        item.MinOccurs       = 0;
        item.MaxOccursString = "unbounded";
        item.Name            = "item";

        // <xs:complexType>
        XmlSchemaComplexType ct1 = new XmlSchemaComplexType();

        // <xs:attribute name="itemID" type="xs:string"/>
        XmlSchemaAttribute itemID = new XmlSchemaAttribute();

        itemID.Name           = "itemID";
        itemID.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // </xs:complexType>
        ct1.Attributes.Add(itemID);

        // </xs:element>
        item.SchemaType = ct1;

        // </xs:sequence>
        sequence1.Items.Add(item);
        customerOrderType.Particle = sequence1;

        // <xs:attribute name="CustomerID" type="xs:string"/>
        XmlSchemaAttribute CustomerID = new XmlSchemaAttribute();

        CustomerID.Name           = "CustomerID";
        CustomerID.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        customerOrderType.Attributes.Add(CustomerID);

        // </xs:complexType>
        schema.Items.Add(customerOrderType);

        // <xs:element name="ordersByCustomer">
        XmlSchemaElement ordersByCustomer = new XmlSchemaElement();

        ordersByCustomer.Name = "ordersByCustomer";

        // <xs:complexType>
        XmlSchemaComplexType ct2 = new XmlSchemaComplexType();

        // <xs:sequence>
        XmlSchemaSequence sequence2 = new XmlSchemaSequence();

        // <xs:element name="customerOrders" type="customerOrderType" minOccurs="0" maxOccurs="unbounded" />
        XmlSchemaElement customerOrders = new XmlSchemaElement();

        customerOrders.MinOccurs       = 0;
        customerOrders.MaxOccursString = "unbounded";
        customerOrders.Name            = "customerOrders";
        customerOrders.SchemaTypeName  = new XmlQualifiedName("customerOrderType", "");

        // </xs:sequence>
        sequence2.Items.Add(customerOrders);

        // </xs:complexType>
        ct2.Particle = sequence2;
        ordersByCustomer.SchemaType = ct2;

        // <xs:unique name="oneCustomerOrdersforEachCustomerID">
        XmlSchemaUnique element_unique = new XmlSchemaUnique();

        element_unique.Name = "oneCustomerOrdersforEachCustomerID";

        // <xs:selector xpath="customerOrders"/>
        element_unique.Selector       = new XmlSchemaXPath();
        element_unique.Selector.XPath = "customerOrders";

        // <xs:field xpath="@customerID"/>
        XmlSchemaXPath field = new XmlSchemaXPath();

        field.XPath = "@customerID";

        // </xs:unique>
        element_unique.Fields.Add(field);
        ordersByCustomer.Constraints.Add(element_unique);

        // </xs:element>
        schema.Items.Add(ordersByCustomer);

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Ejemplo n.º 10
0
 public virtual void Check(ConformanceCheckContext ctx, XmlSchemaAttribute value)
 {
 }
Ejemplo n.º 11
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("Please enter file name");
                return;
            }

            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(textBox1.Text)))
            {
                MessageBox.Show("Invalid destination directory");
                return;
            }

            XmlSchema schema = new XmlSchema();

            //define NameSimpleType

            XmlSchemaSimpleType            nametype = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction nameRes  = new XmlSchemaSimpleTypeRestriction();

            nameRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
            XmlSchemaMinLengthFacet nameFacet1 = new XmlSchemaMinLengthFacet();

            nameFacet1.Value = "3";
            XmlSchemaMaxLengthFacet nameFacet2 = new XmlSchemaMaxLengthFacet();

            nameFacet2.Value = "255";
            nameRes.Facets.Add(nameFacet1);
            nameRes.Facets.Add(nameFacet2);
            nametype.Content = nameRes;

            //define PhoneSimpleType

            XmlSchemaSimpleType            phonetype = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction phoneRes  = new XmlSchemaSimpleTypeRestriction();

            phoneRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
            XmlSchemaMaxLengthFacet phoneFacet1 = new XmlSchemaMaxLengthFacet();

            phoneFacet1.Value = "20";
            phoneRes.Facets.Add(phoneFacet1);
            phonetype.Content = phoneRes;

            //define NotesSimpleType

            XmlSchemaSimpleType            notestype = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction notesRes  = new XmlSchemaSimpleTypeRestriction();

            notesRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
            XmlSchemaMaxLengthFacet notesFacet1 = new XmlSchemaMaxLengthFacet();

            notesFacet1.Value = "500";
            notesRes.Facets.Add(notesFacet1);
            notestype.Content = notesRes;

            //define EmployeeType complex type

            XmlSchemaComplexType employeetype = new XmlSchemaComplexType();
            XmlSchemaSequence    sequence     = new XmlSchemaSequence();
            XmlSchemaElement     firstname    = new XmlSchemaElement();

            firstname.Name       = "firstname";
            firstname.SchemaType = nametype;
            XmlSchemaElement lastname = new XmlSchemaElement();

            lastname.Name       = "lastname";
            lastname.SchemaType = nametype;
            XmlSchemaElement homephone = new XmlSchemaElement();

            homephone.Name       = "homephone";
            homephone.SchemaType = phonetype;
            XmlSchemaElement notes = new XmlSchemaElement();

            notes.Name       = "notes";
            notes.SchemaType = notestype;

            sequence.Items.Add(firstname);
            sequence.Items.Add(lastname);
            sequence.Items.Add(homephone);
            sequence.Items.Add(notes);

            employeetype.Particle = sequence;

            //define employeeid attribute

            XmlSchemaAttribute employeeid = new XmlSchemaAttribute();

            employeeid.Name           = "employeeid";
            employeeid.SchemaTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");
            employeeid.Use            = XmlSchemaUse.Required;

            employeetype.Attributes.Add(employeeid);

            //define top complex type

            XmlSchemaComplexType complextype = new XmlSchemaComplexType();
            XmlSchemaSequence    sq          = new XmlSchemaSequence();
            XmlSchemaElement     employee    = new XmlSchemaElement();

            employee.Name            = "employee";
            employee.SchemaType      = employeetype;
            employee.MinOccurs       = 0;
            employee.MaxOccursString = "unbounded";
            sq.Items.Add(employee);
            complextype.Particle = sq;

            //define <employees> element

            XmlSchemaElement employees = new XmlSchemaElement();

            employees.Name       = "employees";
            employees.SchemaType = complextype;

            schema.Items.Add(employees);

            //compile the schema
            try
            {
                XmlSchemaSet set = new XmlSchemaSet();
                set.Add(schema);
                set.Compile();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Schema compilation failed");
                return;
            }

            //save the schema
            XmlTextWriter writer = new XmlTextWriter(textBox1.Text, null);

            schema.Write(writer);
            writer.Close();
            MessageBox.Show("Schema Created Successfully!");
        }
Ejemplo n.º 12
0
        public Shape GenerateFromSchema(XmlSchemaElement xse)
        {
            XmlQualifiedName     xseName     = xse.QualifiedName;
            XmlSchemaType        schemaType  = xse.ElementSchemaType;
            XmlSchemaComplexType complexType = schemaType as XmlSchemaComplexType;

            if (null != complexType)
            {
                XmlSchemaParticle particle  = null;
                Shape             rootShape = null;

                XmlSchemaContentType contentType = complexType.ElementDecl.ContentValidator.ContentType;
                switch (contentType)
                {
                case XmlSchemaContentType.Mixed:
                case XmlSchemaContentType.TextOnly:
                    rootShape = new Shape(GenName(xseName) + "_Text", BindingType.Text);
                    rootShape.AddParticle(xse);
                    break;

                case XmlSchemaContentType.Empty:
                    rootShape = new Shape(null, BindingType.Sequence);
                    break;

                case XmlSchemaContentType.ElementOnly:
                    particle  = complexType.ContentTypeParticle;
                    rootShape = ProcessParticle(particle, null);
                    break;
                }

                Debug.Assert(rootShape != null);
                if (complexType.AttributeUses.Values.Count > 0)
                {
                    if (rootShape.BindingType != BindingType.Sequence)
                    {
                        Shape s = new Shape(null, BindingType.Sequence);
                        s.AddSubShape(rootShape);
                        rootShape = s;
                    }
                    int      pos   = 0;
                    string[] names = rootShape.SubShapeNames();

                    ICollection          attributes = complexType.AttributeUses.Values;
                    XmlSchemaAttribute[] xsaArray   = new XmlSchemaAttribute[attributes.Count];
                    attributes.CopyTo(xsaArray, 0);
                    Array.Sort(xsaArray, new XmlSchemaAttributeComparer());
                    foreach (XmlSchemaAttribute xsa in xsaArray)
                    {
                        string name      = GenAttrName(xsa.QualifiedName, names);
                        Shape  attrShape = new Shape(name, BindingType.Attribute);
                        attrShape.AddParticle(xsa);
                        rootShape.AddAttrShapeAt(attrShape, pos++);
                    }
                }

                if (rootShape.BindingType != BindingType.Text)
                {
                    rootShape.Name          = GenName(xseName);
                    rootShape.ContainerDecl = xse;
                }
                return(rootShape);
            }
            else   // simple type
            {
                Shape s = new Shape(GenName(xseName), BindingType.Text);
                s.AddParticle(xse);
                return(s);
            }
        }
Ejemplo n.º 13
0
        static XmlSchemaDefinition()
        {
            var xsStringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String);

            var calendarRestriction      = CreateEnumerationRestriction("calendar", xsStringType, CalendarSystem.Ids);
            var localDateRestriction     = CreatePatternRestriction("localDate", xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}");
            var localDateTimeRestriction = CreatePatternRestriction("localDateTime", xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}");
            var zoneIds = CreateEnumerationRestriction("zoneIds", xsStringType, XmlSerializationSettings.DateTimeZoneProvider.GetAllZones().Select(e => e.Id));
            // The "zoneIds" purpose is to document the known zone identifiers. The "zone" restriction is a union between known zone ids and
            // xs:string so that validation won't fail when a new zone identifier is added to the Time Zone Database.
            var zoneRestriction = QualifySchemaType(new XmlSchemaSimpleType
            {
                Name    = "zone",
                Content = new XmlSchemaSimpleTypeUnion {
                    MemberTypes = new[] { zoneIds.QualifiedName, xsStringType.QualifiedName }
                }
            });

            var calendarAttribute = new XmlSchemaAttribute {
                Name = "calendar", SchemaTypeName = calendarRestriction.QualifiedName
            };
            var zoneAttribute = new XmlSchemaAttribute {
                Name = "zone", SchemaTypeName = zoneRestriction.QualifiedName, Use = XmlSchemaUse.Required
            };

            AnnualDateSchemaType = CreatePatternRestriction <AnnualDate>(xsStringType, $"{MonthPattern}-{DayPattern}");
            DurationSchemaType   = CreatePatternRestriction <Duration>(xsStringType, DurationPattern);
            InstantSchemaType    = CreatePatternRestriction <Instant>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}Z");
            IntervalSchemaType   = new XmlSchemaComplexType
            {
                Name       = nameof(Interval),
                Attributes =
                {
                    new XmlSchemaAttribute {
                        Name = "start", SchemaTypeName = InstantSchemaType.QualifiedName
                    },
                    new XmlSchemaAttribute {
                        Name = "end", SchemaTypeName = InstantSchemaType.QualifiedName
                    }
                }
            };
            LocalDateSchemaType      = CreateSchemaTypeWithAttributes <LocalDate>(localDateRestriction, calendarAttribute);
            LocalDateTimeSchemaType  = CreateSchemaTypeWithAttributes <LocalDateTime>(localDateTimeRestriction, calendarAttribute);
            LocalTimeSchemaType      = CreatePatternRestriction <LocalTime>(xsStringType, TimePattern);
            OffsetSchemaType         = CreatePatternRestriction <Offset>(xsStringType, OffsetPattern);
            OffsetDateSchemaType     = CreatePatternRestriction <OffsetDate>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}{OffsetPattern}");
            OffsetDateTimeSchemaType = CreatePatternRestriction <OffsetDateTime>(xsStringType, $"{YearPattern}-{MonthPattern}-{DayPattern}T{TimePattern}{OffsetPattern}");
            OffsetTimeSchemaType     = CreatePatternRestriction <OffsetTime>(xsStringType, $"{TimePattern}{OffsetPattern}");
            PeriodBuilderSchemaType  = CreatePatternRestriction <PeriodBuilder>(xsStringType, PeriodBuilderPattern);
            YearMonthSchemaType      = CreatePatternRestriction <YearMonth>(xsStringType, $"{YearPattern}-{MonthPattern}");
            ZonedDateTimeSchemaType  = CreateSchemaTypeWithAttributes <ZonedDateTime>(OffsetDateTimeSchemaType, zoneAttribute, calendarAttribute);

            DependentSchemaTypes = new Dictionary <XmlSchemaType, IEnumerable <XmlSchemaType> >
            {
                [IntervalSchemaType]      = new[] { InstantSchemaType },
                [LocalDateSchemaType]     = new[] { localDateRestriction, calendarRestriction },
                [LocalDateTimeSchemaType] = new[] { localDateTimeRestriction, calendarRestriction },
                [ZonedDateTimeSchemaType] = new[] { OffsetDateTimeSchemaType, calendarRestriction, zoneRestriction, zoneIds },
            };

            NodaTimeXmlSchema = CreateNodaTimeXmlSchema();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes the column from an XmlSchemaElement or XmlSchemaAttribute.
        /// </summary>
        /// <param name="xmlSchemaAnnotated">An XmlSchema object containing the attributes of the column.</param>
        private void Initialize(XmlSchemaAnnotated xmlSchemaAnnotated)
        {
            // Extract the column properties from an XmlSchemaElement.
            if (xmlSchemaAnnotated is XmlSchemaElement)
            {
                // This element is used to describe the column.
                XmlSchemaElement xmlSchemaElement = xmlSchemaAnnotated as XmlSchemaElement;

                // This information is taken directly from the known XmlSchema attributes.  The rest of the information about the
                // column needs to be extracted using unhandled attributes and element facets.
                this.name       = xmlSchemaElement.Name;
                this.isNullable = xmlSchemaElement.MinOccurs == 0.0m;

                // Extract the string that contains the type information from the 'DataType' custom attribute.  This is a
                // Microsoft extension to the XML Schema definition.
                XmlAttribute dataTypeAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaElement, QualifiedName.DataType);
                if (dataTypeAttribute != null)
                {
                    // The type information is stored as a string.  This will rip apart the string to get the type,
                    // assembly, version, etc. information that can be used to access the type through reflection.
                    string   typeName = dataTypeAttribute.Value;
                    string[] parts    = typeName.Split(',');

                    // There's no a lot of fancy parsing going on here.  If it doesn't match the expected format, then
                    // reject the type.
                    if (parts.Length != 5)
                    {
                        throw new Exception(String.Format("Can't analyze the data type found on line {0}, {1}", xmlSchemaElement.LineNumber, typeName));
                    }

                    // This will load the assembly into memory and use reflection to get the data type that was specified
                    // in the XML file as a string.
                    string   assemblyFullName = String.Format("{0},{1},{2},{3}", parts[1], parts[2], parts[3], parts[4]);
                    Assembly assembly         = Assembly.Load(assemblyFullName);
                    if (assembly == null)
                    {
                        throw new Exception(String.Format("Unable to load the type {0} from assembly {1}", parts[0], assemblyFullName));
                    }
                    this.dataType = assembly.GetType(parts[0]);
                    if (this.dataType == null)
                    {
                        throw new Exception(String.Format("Unable to load the type {0} from assembly {1}", parts[0], assemblyFullName));
                    }
                }
                else
                {
                    // This will extract the simple data type and the maximum field length from the facets associated with the element.
                    if (xmlSchemaElement.ElementSchemaType is XmlSchemaSimpleType)
                    {
                        XmlSchemaSimpleType xmlSchemaSimpleType = xmlSchemaElement.ElementSchemaType as XmlSchemaSimpleType;
                        this.dataType = xmlSchemaSimpleType.Datatype.ValueType;
                        if (xmlSchemaSimpleType.Content is XmlSchemaSimpleTypeRestriction)
                        {
                            XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction = xmlSchemaSimpleType.Content as XmlSchemaSimpleTypeRestriction;
                            foreach (XmlSchemaFacet xmlSchemaFacet in xmlSchemaSimpleTypeRestriction.Facets)
                            {
                                if (xmlSchemaFacet is XmlSchemaMaxLengthFacet)
                                {
                                    XmlSchemaMaxLengthFacet xmlSchemaMaxLengthFacet = xmlSchemaFacet as XmlSchemaMaxLengthFacet;
                                    this.maximumLength = Convert.ToInt32(xmlSchemaMaxLengthFacet.Value);
                                }
                            }
                        }
                    }
                }

                // The defalt value can only be evaluated after the data type has been determined.  Otherwise, there's no way to
                // know to which data type the default value is converted.
                this.defaultValue = DataModelSchema.ConvertValue(this.dataType, xmlSchemaElement.DefaultValue);
            }

            // Extract the column properties from an Attribute.
            if (xmlSchemaAnnotated is XmlSchemaAttribute)
            {
                // This attribute describes the column.
                XmlSchemaAttribute xmlSchemaAttribute = xmlSchemaAnnotated as XmlSchemaAttribute;

                // This information is taken directly from the known XmlSchema attributes.  The rest of the information about the
                // column needs to be extracted using unhandled attributes and element facets.
                this.name         = xmlSchemaAttribute.Name;
                this.dataType     = xmlSchemaAttribute.AttributeSchemaType.Datatype.ValueType;
                this.defaultValue = DataModelSchema.ConvertValue(this.dataType, xmlSchemaAttribute.DefaultValue);
            }

            // Determine the IsEncryptedColumn property.
            XmlAttribute isColumnEncrytedAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaAnnotated,
                                                                                        QualifiedName.IsEncrypted);

            this.isEncrypted = isColumnEncrytedAttribute == null ? false : Convert.ToBoolean(isColumnEncrytedAttribute.Value);

            // Determine the IsIdentityColumn property.
            XmlAttribute autoIncrementAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaAnnotated,
                                                                                     QualifiedName.AutoIncrement);

            this.isAutoIncrement = autoIncrementAttribute == null ? false : Convert.ToBoolean(autoIncrementAttribute.Value);

            // Determine the IsPersistent property.
            XmlAttribute isColumnPersistentAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaAnnotated,
                                                                                          QualifiedName.IsPersistent);

            this.isPersistent = isColumnPersistentAttribute == null ? true : Convert.ToBoolean(isColumnPersistentAttribute.Value);

            // Determine the AutoIncrementSeed property.
            XmlAttribute autoIncrementSeedAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaAnnotated,
                                                                                         QualifiedName.AutoIncrementSeed);

            this.autoIncrementSeed = autoIncrementSeedAttribute == null ? 0 : Convert.ToInt32(autoIncrementSeedAttribute.Value);

            // Determine the AutoIncrementStop property
            XmlAttribute autoIncrementStepAttribute = ObjectSchema.GetUnhandledAttribute(xmlSchemaAnnotated,
                                                                                         QualifiedName.AutoIncrementStep);

            this.autoIncrementStep = autoIncrementStepAttribute == null ? 0 : Convert.ToInt32(autoIncrementStepAttribute.Value);
        }
Ejemplo n.º 15
0
    } //WriteExampleAttributes()

    // Write a single example attribute
    public static void WriteExampleAttribute(XmlSchemaAttribute attribute, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartAttribute(attribute.QualifiedName.Name, attribute.QualifiedName.Namespace);
      // The examples value
      WriteExampleValue(attribute.AttributeType, myXmlTextWriter);
      myXmlTextWriter.WriteEndAttribute();
    } //WriteExampleAttribute()
Ejemplo n.º 16
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:simpleType name="ZipCodeType">
        XmlSchemaSimpleType ZipCodeType = new XmlSchemaSimpleType();

        ZipCodeType.Name = "ZipCodeType";

        // <xs:restriction base="xs:string">
        XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();

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

        // <xs:minLength value="5"/>
        XmlSchemaMinLengthFacet minLength = new XmlSchemaMinLengthFacet();

        minLength.Value = "5";
        restriction.Facets.Add(minLength);

        ZipCodeType.Content = restriction;

        schema.Items.Add(ZipCodeType);

        // <xs:element name="Address">
        XmlSchemaElement element = new XmlSchemaElement();

        element.Name = "Address";

        // <xs:complexType>
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();

        // <xs:attribute name="ZipCode" type="ZipCodeType"/>
        XmlSchemaAttribute ZipCodeAttribute = new XmlSchemaAttribute();

        ZipCodeAttribute.Name           = "ZipCode";
        ZipCodeAttribute.SchemaTypeName = new XmlQualifiedName("ZipCodeType", "");
        complexType.Attributes.Add(ZipCodeAttribute);

        element.SchemaType = complexType;

        schema.Items.Add(element);

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Ejemplo n.º 17
0
    } //WriteXSDSchema()

    /// <summary>
    /// This method writes out an XML schema attribute.
    /// </summary>
    /// <param name="attribute">XML schema attribute to be output.</param>
    /// <param name="myXmlTextWriter">XmlTextWriter to write output to.</param>
    public static void WriteXmlSchemaAttribute(XmlSchemaAttribute attribute, XmlTextWriter myXmlTextWriter)
    {
      myXmlTextWriter.WriteStartElement("attribute", XmlSchema.Namespace);
      if (attribute.Name != null)
      {
        myXmlTextWriter.WriteAttributeString("name", attribute.Name);
      } //if

      if (!attribute.RefName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("ref", null);
        myXmlTextWriter.WriteQualifiedName(attribute.RefName.Name, attribute.RefName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (!attribute.SchemaTypeName.IsEmpty)
      {
        myXmlTextWriter.WriteStartAttribute("type", null);
        myXmlTextWriter.WriteQualifiedName(attribute.SchemaTypeName.Name, attribute.SchemaTypeName.Namespace);
        myXmlTextWriter.WriteEndAttribute();
      } //if

      if (attribute.SchemaType != null)
      {
        WriteXmlSchemaSimpleType(attribute.SchemaType, myXmlTextWriter);
      } //if

      myXmlTextWriter.WriteEndElement();
    } //WriteXmlSchemaAttribute()
Ejemplo n.º 18
0
        /// <summary>
        /// Create a description of a column in a data model.
        /// </summary>
        /// <param name="dataModelSchema">The Schema of the entire data model.</param>
        /// <param name="xmlSchemaObject">The schema of the column.</param>
        public ColumnSchema(DataModelSchema dataModelSchema, XmlSchemaObject xmlSchemaObject) :
            base(dataModelSchema, xmlSchemaObject)
        {
            // Initialize the object
            this.dataModelSchema = dataModelSchema;
            this.Name            = string.Empty;
            this.QualifiedName   = XmlQualifiedName.Empty;
            this.DataType        = typeof(System.Object);
            this.MinOccurs       = 0.0M;
            this.DefaultValue    = null;
            this.FixedValue      = null;

            // Extract the column properties from an Element.
            if (xmlSchemaObject is XmlSchemaElement)
            {
                XmlSchemaElement xmlSchemaElement = xmlSchemaObject as XmlSchemaElement;
                this.Name          = xmlSchemaElement.Name;
                this.QualifiedName = xmlSchemaElement.QualifiedName;
                this.DataType      = xmlSchemaElement.ElementSchemaType.Datatype.ValueType;
                this.MinOccurs     = xmlSchemaElement.MinOccurs;
                this.DefaultValue  = ConvertValue(xmlSchemaElement.DefaultValue);
                this.FixedValue    = ConvertValue(xmlSchemaElement.FixedValue);
            }

            // Extract the column properties from an Attribute.
            if (xmlSchemaObject is XmlSchemaAttribute)
            {
                XmlSchemaAttribute xmlSchemaAttribute = xmlSchemaObject as XmlSchemaAttribute;
                this.Name          = xmlSchemaAttribute.Name;
                this.QualifiedName = xmlSchemaAttribute.QualifiedName;
                this.DataType      = xmlSchemaAttribute.AttributeSchemaType.Datatype.ValueType;
                this.DefaultValue  = ConvertValue(xmlSchemaAttribute.DefaultValue);
                this.FixedValue    = ConvertValue(xmlSchemaAttribute.FixedValue);
            }

            // Determine the IsIdentityColumn property.
            object autoIncrementAttribute = GetUnhandledAttribute(xmlSchemaObject, "AutoIncrement");

            this.IsAutoIncrement = autoIncrementAttribute == null ? false : Convert.ToBoolean(autoIncrementAttribute);

            // Determine the IsPersistent property.
            object isColumnPersistentAttribute = GetUnhandledAttribute(xmlSchemaObject, "IsPersistent");

            this.IsPersistent = isColumnPersistentAttribute == null ? true : Convert.ToBoolean(isColumnPersistentAttribute);

            // Determine the AutoIncrementSeed property.
            object autoIncrementSeedAttribute = GetUnhandledAttribute(xmlSchemaObject, "AutoIncrementSeed");

            this.AutoIncrementSeed = autoIncrementSeedAttribute == null ? 0 : Convert.ToInt32(autoIncrementSeedAttribute);

            // Determine the AutoIncrementStop property
            object autoIncrementStepAttribute = GetUnhandledAttribute(xmlSchemaObject, "AutoIncrementStep");

            this.AutoIncrementStep = autoIncrementStepAttribute == null ? 0 : Convert.ToInt32(autoIncrementStepAttribute);

            // In an object oriented architecture it is important to know at which level of the hierarchy a column is initially
            // declared.  Just like the equivalent in the object oriented languages, this field indicates which table actually owns
            // the data of a given column.
            XmlSchemaObject parentObject = xmlSchemaObject.Parent;

            while (!(parentObject is XmlSchemaComplexContentExtension) && !(parentObject is XmlSchemaComplexType))
            {
                parentObject = parentObject.Parent;
            }
            this.DeclaringType = FindDeclaringType(parentObject, xmlSchemaObject);
        }
Ejemplo n.º 19
0
 public bool Test(XmlSchemaAttribute at)
 {
     return(true);
 }
Ejemplo n.º 20
0
        void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor accessor, bool valueTypeOptional, string ns)
        {
            if (accessor == null)
            {
                return;
            }
            XmlSchemaObjectCollection attributes;

            if (type.ContentModel != null)
            {
                if (type.ContentModel.Content is XmlSchemaComplexContentRestriction)
                {
                    attributes = ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Attributes;
                }
                else if (type.ContentModel.Content is XmlSchemaComplexContentExtension)
                {
                    attributes = ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Attributes;
                }
                else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension)
                {
                    attributes = ((XmlSchemaSimpleContentExtension)type.ContentModel.Content).Attributes;
                }
                else
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInvalidContent, type.ContentModel.Content.GetType().Name));
                }
            }
            else
            {
                attributes = type.Attributes;
            }

            if (accessor.IsSpecialXmlNamespace)
            {
                // add <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
                AddSchemaImport(XmlReservedNs.NsXml, ns);

                // generate <xsd:attribute ref="xml:lang" use="optional" />
                XmlSchemaAttribute attribute = new XmlSchemaAttribute();
                attribute.Use     = XmlSchemaUse.Optional;
                attribute.RefName = new XmlQualifiedName(accessor.Name, XmlReservedNs.NsXml);
                attributes.Add(attribute);
            }
            else if (accessor.Any)
            {
                if (type.ContentModel == null)
                {
                    type.AnyAttribute = new XmlSchemaAnyAttribute();
                }
                else
                {
                    XmlSchemaContent content = type.ContentModel.Content;
                    if (content is XmlSchemaComplexContentExtension)
                    {
                        XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content;
                        extension.AnyAttribute = new XmlSchemaAnyAttribute();
                    }
                    else if (content is XmlSchemaComplexContentRestriction)
                    {
                        XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)content;
                        restriction.AnyAttribute = new XmlSchemaAnyAttribute();
                    }
                }
            }
            else
            {
                XmlSchemaAttribute attribute = new XmlSchemaAttribute();
                attribute.Use = XmlSchemaUse.None;
                if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping.TypeDesc.IsValueType)
                {
                    attribute.Use = XmlSchemaUse.Required;
                }
                attribute.Name = accessor.Name;
                if (accessor.Namespace == null || accessor.Namespace == ns)
                {
                    // determine the form attribute value
                    XmlSchema schema = schemas[ns];
                    if (schema == null)
                    {
                        attribute.Form = accessor.Form == attributeFormDefault ? XmlSchemaForm.None : accessor.Form;
                    }
                    else
                    {
                        attribute.Form = accessor.Form == schema.AttributeFormDefault ? XmlSchemaForm.None : accessor.Form;
                    }
                    attributes.Add(attribute);
                }
                else
                {
                    // we are going to add the attribute to the top-level items. "use" attribute should not be set
                    attribute.Use  = XmlSchemaUse.None;
                    attribute.Form = accessor.Form;
                    AddSchemaItem(attribute, accessor.Namespace, ns);
                    XmlSchemaAttribute refAttribute = new XmlSchemaAttribute();
                    refAttribute.Use     = XmlSchemaUse.None;
                    refAttribute.RefName = new XmlQualifiedName(accessor.Name, accessor.Namespace);
                    attributes.Add(refAttribute);
                }
                if (accessor.Mapping is PrimitiveMapping)
                {
                    PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping;
                    if (pm.IsList)
                    {
                        // create local simple type for the list-like attributes
                        XmlSchemaSimpleType     dataType = new XmlSchemaSimpleType();
                        XmlSchemaSimpleTypeList list     = new XmlSchemaSimpleTypeList();
                        list.ItemTypeName    = ExportPrimitiveMapping(pm, accessor.Namespace == null ? ns : accessor.Namespace);
                        dataType.Content     = list;
                        attribute.SchemaType = dataType;
                    }
                    else
                    {
                        attribute.SchemaTypeName = ExportPrimitiveMapping(pm, accessor.Namespace == null ? ns : accessor.Namespace);
                    }
                }
                else if (!(accessor.Mapping is SpecialMapping))
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInternalError));
                }

                if (accessor.HasDefault && accessor.Mapping.TypeDesc.HasDefaultSupport)
                {
                    attribute.DefaultValue = ExportDefaultValue(accessor.Mapping, accessor.Default);
                }
            }
        }
Ejemplo n.º 21
0
        private void WriteDataTable(XmlSchema schema, CremaDataTable dataTable)
        {
            var tableNamespace = schema.TargetNamespace;
            var complexType    = new XmlSchemaComplexType()
            {
                Name = dataTable.TableTypeName
            };

            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.Creator, dataTable.CreationInfo.ID, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.CreatedDateTime, dataTable.CreationInfo.DateTime, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.Modifier, dataTable.ModificationInfo.ID, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.ModifiedDateTime, dataTable.ModificationInfo.DateTime, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.Tags, dataTable.Tags, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.ID, dataTable.TableID, tableNamespace);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.CategoryPath, dataTable.CategoryPath, tableNamespace, PathUtility.Separator);
            complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.IgnoreCaseSensitive, dataTable.IgnoreCaseSensitive, tableNamespace, false);

            if (dataTable.TemplateNamespace != string.Empty)
            {
                complexType.WriteAppInfo(CremaSchema.TableInfo, CremaSchema.TemplateNamespace, dataTable.TemplateNamespace, tableNamespace);
            }

            complexType.WriteDescription(dataTable.Comment);

            if (this.itemName != null || dataTable.TemplateNamespace == string.Empty || dataTable.TemplatedParent == null)
            {
                var sequence = new XmlSchemaSequence();

                foreach (var item in dataTable.Attributes)
                {
                    if (item.IsVisible == false)
                    {
                        continue;
                    }
                    this.WriteAttribute(schema, complexType, item);
                }

                foreach (var item in dataTable.Columns)
                {
                    this.WriteDataColumn(schema, item);
                    this.WriteElement(schema, sequence, item);
                }

                if (dataTable.RelationColumn != null && dataTable.Parent == null)
                {
                    var attribute = new XmlSchemaAttribute()
                    {
                        Name           = CremaSchema.RelationID,
                        SchemaTypeName = GetSystemQualifiedName(typeof(string))
                    };
                    complexType.Attributes.Add(attribute);
                }

                foreach (var item in dataTable.Childs)
                {
                    this.WriteElement(schema, sequence, item);
                    this.WriteDataTable(schema, item);
                }

                complexType.Particle = sequence;
            }
            else
            {
                var content   = new XmlSchemaComplexContent();
                var extension = new XmlSchemaComplexContentExtension()
                {
                    BaseTypeName = new XmlQualifiedName(dataTable.TemplateTypeName, tableNamespace)
                };
                content.Content          = extension;
                complexType.ContentModel = content;
            }

            schema.Items.Add(complexType);
        }
Ejemplo n.º 22
0
        XmlSchemaAttribute GetSchemaAttribute(XmlSchema currentSchema, XmlTypeMapMemberAttribute attinfo, bool isTypeMember)
        {
            XmlSchemaAttribute sat = new XmlSchemaAttribute();

            if (attinfo.DefaultValue != System.DBNull.Value)
            {
                sat.DefaultValue = ExportDefaultValue(attinfo.TypeData,
                                                      attinfo.MappedType, attinfo.DefaultValue);
            }
            else
            {
                if (!attinfo.IsOptionalValueType && attinfo.TypeData.IsValueType)
                {
                    sat.Use = XmlSchemaUse.Required;
                }
            }

            ImportNamespace(currentSchema, attinfo.Namespace);

            XmlSchema memberSchema;

            if (attinfo.Namespace.Length == 0 && attinfo.Form != XmlSchemaForm.Qualified)
            {
                memberSchema = currentSchema;
            }
            else
            {
                memberSchema = GetSchema(attinfo.Namespace);
            }

            if (currentSchema == memberSchema || encodedFormat)
            {
                sat.Name = attinfo.AttributeName;
                if (isTypeMember)
                {
                    sat.Form = attinfo.Form;
                }
                if (attinfo.TypeData.SchemaType == SchemaTypes.Enum)
                {
                    ImportNamespace(currentSchema, attinfo.DataTypeNamespace);
                    ExportEnumSchema(attinfo.MappedType);
                    sat.SchemaTypeName = new XmlQualifiedName(attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);
                }
                else if (attinfo.TypeData.SchemaType == SchemaTypes.Array && TypeTranslator.IsPrimitive(attinfo.TypeData.ListItemType))
                {
                    sat.SchemaType = GetSchemaSimpleListType(attinfo.TypeData);
                }
                else
                {
                    sat.SchemaTypeName = new XmlQualifiedName(attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);
                };
            }
            else
            {
                sat.RefName = new XmlQualifiedName(attinfo.AttributeName, attinfo.Namespace);
                foreach (XmlSchemaObject ob in memberSchema.Items)
                {
                    if (ob is XmlSchemaAttribute && ((XmlSchemaAttribute)ob).Name == attinfo.AttributeName)
                    {
                        return(sat);
                    }
                }

                memberSchema.Items.Add(GetSchemaAttribute(memberSchema, attinfo, false));
            }
            return(sat);
        }
Ejemplo n.º 23
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:simpleType name="WaitQueueLengthType">
        XmlSchemaSimpleType WaitQueueLengthType = new XmlSchemaSimpleType();

        WaitQueueLengthType.Name = "WaitQueueLengthType";

        // <xs:restriction base="xs:int">
        XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();

        restriction.BaseTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");

        // <xs:maxExclusive value="5"/>
        XmlSchemaMaxExclusiveFacet maxExclusive = new XmlSchemaMaxExclusiveFacet();

        maxExclusive.Value = "5";
        restriction.Facets.Add(maxExclusive);

        WaitQueueLengthType.Content = restriction;

        schema.Items.Add(WaitQueueLengthType);

        // <xs:element name="Lobby">
        XmlSchemaElement element = new XmlSchemaElement();

        element.Name = "Lobby";

        // <xs:complexType>
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();

        // <xs:attribute name="WaitQueueLength" type="WaitQueueLengthType"/>
        XmlSchemaAttribute WaitQueueLengthAttribute = new XmlSchemaAttribute();

        WaitQueueLengthAttribute.Name           = "WaitQueueLength";
        WaitQueueLengthAttribute.SchemaTypeName = new XmlQualifiedName("WaitQueueLengthType", "");
        complexType.Attributes.Add(WaitQueueLengthAttribute);

        element.SchemaType = complexType;

        schema.Items.Add(element);

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Ejemplo n.º 24
0
        XmlQualifiedName ExportArraySchema(XmlTypeMapping map, string defaultNamespace)
        {
            ListMap lmap = (ListMap)map.ObjectMap;

            if (encodedFormat)
            {
                string name, ns, schemaNs;
                lmap.GetArrayType(-1, out name, out ns);
                if (ns == XmlSchema.Namespace)
                {
                    schemaNs = defaultNamespace;
                }
                else
                {
                    schemaNs = ns;
                }

                if (IsMapExported(map))
                {
                    return(new XmlQualifiedName(lmap.GetSchemaArrayName(), schemaNs));
                }
                SetMapExported(map);

                XmlSchema            schema = GetSchema(schemaNs);
                XmlSchemaComplexType stype  = new XmlSchemaComplexType();
                stype.Name = lmap.GetSchemaArrayName();
                schema.Items.Add(stype);

                XmlSchemaComplexContent content = new XmlSchemaComplexContent();
                content.IsMixed    = false;
                stype.ContentModel = content;

                XmlSchemaComplexContentRestriction rest = new XmlSchemaComplexContentRestriction();
                content.Content   = rest;
                rest.BaseTypeName = new XmlQualifiedName("Array", XmlSerializer.EncodingNamespace);
                XmlSchemaAttribute at = new XmlSchemaAttribute();
                rest.Attributes.Add(at);
                at.RefName = new XmlQualifiedName("arrayType", XmlSerializer.EncodingNamespace);

                XmlAttribute arrayType = Document.CreateAttribute("arrayType", XmlSerializer.WsdlNamespace);
                arrayType.Value        = ns + (ns != "" ? ":" : "") + name;
                at.UnhandledAttributes = new XmlAttribute [] { arrayType };
                ImportNamespace(schema, XmlSerializer.WsdlNamespace);

                XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo)lmap.ItemInfo[0];
                if (einfo.MappedType != null)
                {
                    switch (einfo.TypeData.SchemaType)
                    {
                    case SchemaTypes.Enum:
                        ExportEnumSchema(einfo.MappedType);
                        break;

                    case SchemaTypes.Array:
                        ExportArraySchema(einfo.MappedType, schemaNs);
                        break;

                    case SchemaTypes.Class:
                        ExportClassSchema(einfo.MappedType);
                        break;
                    }
                }

                return(new XmlQualifiedName(lmap.GetSchemaArrayName(), schemaNs));
            }
            else
            {
                if (IsMapExported(map))
                {
                    return(new XmlQualifiedName(map.XmlType, map.XmlTypeNamespace));
                }

                SetMapExported(map);
                XmlSchema            schema = GetSchema(map.XmlTypeNamespace);
                XmlSchemaComplexType stype  = new XmlSchemaComplexType();
                stype.Name = map.ElementName;
                schema.Items.Add(stype);

                XmlSchemaParticle spart = GetSchemaArrayElement(schema, lmap.ItemInfo);
                if (spart is XmlSchemaChoice)
                {
                    stype.Particle = spart;
                }
                else
                {
                    XmlSchemaSequence seq = new XmlSchemaSequence();
                    seq.Items.Add(spart);
                    stype.Particle = seq;
                }

                return(new XmlQualifiedName(map.XmlType, map.XmlTypeNamespace));
            }
        }
Ejemplo n.º 25
0
            protected XmlSchemaComplexType FindOrCreateComplexType(Type t)
            {
                XmlSchemaComplexType ct;
                string typeId = GenerateIDFromType(t);

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

                ct      = new XmlSchemaComplexType();
                ct.Name = typeId;

                // Force mixed attribute for tasks names in the mixedTaskNames array.  Fixes Bug#: 3058913
                if (Array.IndexOf(mixedTaskNames, ct.Name) != -1)
                {
                    ct.IsMixed = true;
                }

                // add complex type to collection immediately to avoid stack
                // overflows, when we allow a type to be nested
                _nantComplexTypes.Add(typeId, ct);

#if NOT_IMPLEMENTED
                //
                // TODO - add task/type documentation in the future
                //

                ct.Annotation = new XmlSchemaAnnotation();
                XmlSchemaDocumentation doc = new XmlSchemaDocumentation();
                ct.Annotation.Items.Add(doc);
                doc.Markup = ...;
#endif

                XmlSchemaSequence         group1 = null;
                XmlSchemaObjectCollection attributesCollection = ct.Attributes;

                foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (memInfo.DeclaringType.Equals(typeof(object)))
                    {
                        continue;
                    }

                    //Check for any return type that is derived from Element

                    // add Attributes
                    TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute)
                                                          Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute),
                                                                                       false);
                    BuildElementAttribute buildElemAttr = (BuildElementAttribute)
                                                          Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute),
                                                                                       false);

                    if (taskAttrAttr != null)
                    {
                        XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required);
                        attributesCollection.Add(newAttr);
                    }
                    else if (buildElemAttr != null)
                    {
                        // Create individial choice for any individual child Element
                        Decimal min = 0;

                        if (buildElemAttr.Required)
                        {
                            min = 1;
                        }

                        XmlSchemaElement childElement = new XmlSchemaElement();
                        childElement.MinOccurs = min;
                        childElement.MaxOccurs = 1;
                        childElement.Name      = buildElemAttr.Name;

                        //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue);

                        Type childType;

                        // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class
                        if (memInfo is PropertyInfo)
                        {
                            childType = ((PropertyInfo)memInfo).PropertyType;
                        }
                        else if (memInfo is FieldInfo)
                        {
                            childType = ((FieldInfo)memInfo).FieldType;
                        }
                        else if (memInfo is MethodInfo)
                        {
                            MethodInfo method = (MethodInfo)memInfo;
                            if (method.GetParameters().Length == 1)
                            {
                                childType = method.GetParameters()[0].ParameterType;
                            }
                            else
                            {
                                throw new ApplicationException("Method should have one parameter.");
                            }
                        }
                        else
                        {
                            throw new ApplicationException("Member Type != Field/Property/Method");
                        }

                        BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute)
                                                                                Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false);

                        // determine type of child elements

                        if (buildElementArrayAttribute != null)
                        {
                            if (buildElementArrayAttribute.ElementType == null)
                            {
                                if (childType.IsArray)
                                {
                                    childType = childType.GetElementType();
                                }
                                else
                                {
                                    Type elementType = null;

                                    // locate Add method with 1 parameter, type of that parameter is parameter type
                                    foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                                    {
                                        if (method.Name == "Add" && method.GetParameters().Length == 1)
                                        {
                                            ParameterInfo parameter = method.GetParameters()[0];
                                            elementType = parameter.ParameterType;
                                            break;
                                        }
                                    }

                                    childType = elementType;
                                }
                            }
                            else
                            {
                                childType = buildElementArrayAttribute.ElementType;
                            }

                            if (childType == null || !typeof(Element).IsAssignableFrom(childType))
                            {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                                       ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name));
                            }
                        }

                        BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute)Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false);
                        if (buildElementCollectionAttribute != null)
                        {
                            XmlSchemaComplexType collectionType = new XmlSchemaComplexType();
                            XmlSchemaSequence    sequence       = new XmlSchemaSequence();
                            collectionType.Particle = sequence;

                            sequence.MinOccurs       = 0;
                            sequence.MaxOccursString = "unbounded";

                            XmlSchemaElement itemType = new XmlSchemaElement();
                            itemType.Name           = buildElementCollectionAttribute.ChildElementName;
                            itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName;

                            sequence.Items.Add(itemType);

                            childElement.SchemaType = collectionType;
                        }
                        else
                        {
                            childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName;
                        }

                        // lazy init of sequence
                        if (group1 == null)
                        {
                            group1      = CreateXsdSequence(0, Decimal.MaxValue);
                            ct.Particle = group1;
                        }

                        group1.Items.Add(childElement);
                    }
                }

                // allow attributes from other namespace
                ct.AnyAttribute                 = new XmlSchemaAnyAttribute();
                ct.AnyAttribute.Namespace       = "##other";
                ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip;

                Schema.Items.Add(ct);
                Compile();

                return(ct);
            }
Ejemplo n.º 26
0
            public void InitializeChildren(SchemaObject theObject, XmlSchemaObject xmlObject)
            {
                XmlSchemaComplexType complexType = xmlObject as XmlSchemaComplexType;

                if (complexType == null && xmlObject is XmlSchemaElement)
                {
                    complexType = ((XmlSchemaElement)xmlObject).ElementSchemaType as XmlSchemaComplexType;
                }

                // if we don't have a complex type, we don't have any children to work with
                if (complexType == null)
                {
                    theObject.IsInitialized = true;
                    return;
                }

                XmlSchemaComplexType baseComplexType = complexType.BaseXmlSchemaType as XmlSchemaComplexType;

                // Load the base type info
                if (baseComplexType != null)
                {
                    InitializeChildren(theObject, baseComplexType);
                }

                theObject.IsInitialized = true;

                XmlSchemaObjectCollection attributes          = complexType.Attributes;
                XmlSchemaSequence         complexTypeSequence = complexType.ContentTypeParticle as XmlSchemaSequence;
                XmlSchemaChoice           complexTypeChoice   = complexType.ContentTypeParticle as XmlSchemaChoice;

                // Add attributes
                XmlSchemaComplexContentRestriction restriction    = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentRestriction : null;
                XmlSchemaComplexContentExtension   extension      = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentExtension : null;
                XmlSchemaObjectCollection          baseAttributes = null;

                if (restriction != null)
                {
                    baseAttributes = restriction.Attributes;
                }
                else if (extension != null)
                {
                    baseAttributes = extension.Attributes;
                }

                if (baseAttributes != null)
                {
                    foreach (XmlSchemaObject cObject in baseAttributes)
                    {
                        XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                        // TODO: Do something more complicated when cObject is an attribute group reference
                        if (cAttribute == null)
                        {
                            continue;
                        }

                        var foundChild = theObject.Children.SingleOrDefault(y => y.Name == cAttribute.Name);
                        var newChild   = new SchemaObject(theObject.simpleSchema, cAttribute)
                        {
                            Parent = theObject,
                            Name   = this.SimpleSchema.GetName(cAttribute.QualifiedName, cAttribute.RefName),
                            Type   = ObjectTypes.Attribute
                        };

                        if (foundChild != null && restriction != null)
                        {
                            var foundIndex = theObject.Children.IndexOf(foundChild);
                            theObject.Children.RemoveAt(foundIndex);
                            theObject.Children.Insert(foundIndex, newChild);
                        }
                        else if (foundChild == null)
                        {
                            theObject.Children.Add(newChild);
                        }
                    }
                }

                foreach (XmlSchemaObject cObject in complexType.Attributes)
                {
                    XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute;

                    // TODO: More complicated logic to determine if a restriction is being applied
                    if (cAttribute != null && !theObject.Children.Exists(y => y.Name == cAttribute.Name))
                    {
                        theObject.Children.Add(
                            new SchemaObject(theObject.simpleSchema, cAttribute)
                        {
                            Parent = theObject,
                            Name   = this.SimpleSchema.GetName(cAttribute.QualifiedName, cAttribute.RefName),
                            Type   = ObjectTypes.Attribute
                        });
                    }
                }

                bool update = extension != null || restriction != null;

                // Add child elements (un-initialized)
                if (complexTypeSequence != null)
                {
                    InitializeXmlSequence(theObject, complexTypeSequence, update);
                }

                // Add all choice items
                if (complexTypeChoice != null)
                {
                    InitializeXmlChoice(theObject, complexTypeChoice, update);
                }
            }
Ejemplo n.º 27
0
        void CombinePluginType(XmlSchemaComplexType complexType, PluginElementAttribute pluginAttr)
        {
            var addedAttrs = new Dictionary <string, XmlSchemaAttribute>();
            var addedElems = new Dictionary <string, XmlSchemaElement>();

            var schemaParticle = new XmlSchemaChoice();

            schemaParticle.MinOccursString = "0";
            schemaParticle.MaxOccursString = "unbounded";

            var restrictEnum = new XmlSchemaSimpleTypeRestriction();

            restrictEnum.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);

            foreach (var item in ClassLoader.GetAllByAttribute <PluginAttribute>((t, a) => a.Type == pluginAttr.PluginType && a.IsDefault && !a.IsTest))
            {
                restrictEnum.Facets.Add(MakePluginFacet(item.Key, item.Value));

                foreach (var pi in item.Value.GetProperties())
                {
                    var attrAttr = pi.GetAttributes <XmlAttributeAttribute>().FirstOrDefault();
                    if (attrAttr != null)
                    {
                        var attr = MakeAttribute(attrAttr.AttributeName, pi);
                        if (!addedAttrs.ContainsKey(attr.Name))
                        {
                            complexType.Attributes.Add(attr);
                            addedAttrs.Add(attr.Name, attr);
                        }
                        continue;
                    }

                    var elemAttr = pi.GetAttributes <XmlElementAttribute>().FirstOrDefault();
                    if (elemAttr != null)
                    {
                        var elems = MakeElement(elemAttr.ElementName, null, pi, null);
                        foreach (var elem in elems)
                        {
                            var key = elem.Name ?? elem.RefName.Name;
                            if (!addedElems.ContainsKey(key))
                            {
                                elem.MinOccursString = null;
                                elem.MaxOccursString = null;
                                schemaParticle.Items.Add(elem);
                                addedElems.Add(key, elem);
                            }
                        }
                    }

                    var anyAttr = pi.GetAttributes <XmlAnyAttributeAttribute>().FirstOrDefault();
                    if (anyAttr != null)
                    {
                        complexType.AnyAttribute = new XmlSchemaAnyAttribute()
                        {
                            ProcessContents = XmlSchemaContentProcessing.Skip
                        };
                        continue;
                    }
                }

                foreach (var prop in item.Value.GetAttributes <ParameterAttribute>())
                {
                    var attr = MakeAttribute(prop.name, prop);
                    if (!addedAttrs.ContainsKey(attr.Name))
                    {
                        complexType.Attributes.Add(attr);
                        addedAttrs.Add(attr.Name, attr);
                    }
                }
            }

            var enumType = new XmlSchemaSimpleType();

            enumType.Content = restrictEnum;

            var typeAttr = new XmlSchemaAttribute();

            typeAttr.Name       = pluginAttr.AttributeName;
            typeAttr.Use        = XmlSchemaUse.Required;
            typeAttr.SchemaType = enumType;
            typeAttr.Annotate("Specify the {0} of a Peach {1}.".Fmt(
                                  pluginAttr.AttributeName,
                                  pluginAttr.PluginType.Name.ToLower()
                                  ));

            complexType.Attributes.Add(typeAttr);

            if (schemaParticle.Items.Count > 0)
            {
                complexType.Particle = schemaParticle;
            }
        }
Ejemplo n.º 28
0
        public static XmlSchemaComplexType GetTypedTableSchema(XmlSchemaSet xs)
        {
            XmlSchemaComplexType type2    = new XmlSchemaComplexType();
            XmlSchemaSequence    sequence = new XmlSchemaSequence();
            Baze         baze             = new Baze();
            XmlSchemaAny item             = new XmlSchemaAny {
                Namespace = "http://www.w3.org/2001/XMLSchema"
            };
            decimal num = new decimal(0);

            item.MinOccurs       = num;
            item.MaxOccurs       = 79228162514264337593543950335M;
            item.ProcessContents = XmlSchemaContentProcessing.Lax;
            sequence.Items.Add(item);
            XmlSchemaAny any2 = new XmlSchemaAny {
                Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
            };

            num                  = new decimal(1);
            any2.MinOccurs       = num;
            any2.ProcessContents = XmlSchemaContentProcessing.Lax;
            sequence.Items.Add(any2);
            XmlSchemaAttribute attribute = new XmlSchemaAttribute {
                Name       = "namespace",
                FixedValue = baze.Namespace
            };

            type2.Attributes.Add(attribute);
            XmlSchemaAttribute attribute2 = new XmlSchemaAttribute {
                Name       = "tableTypeName",
                FixedValue = "PodaciDataTable"
            };

            type2.Attributes.Add(attribute2);
            type2.Particle = sequence;
            XmlSchema schemaSerializable = baze.GetSchemaSerializable();

            if (xs.Contains(schemaSerializable.TargetNamespace))
            {
                MemoryStream stream  = new MemoryStream();
                MemoryStream stream2 = new MemoryStream();
                try
                {
                    XmlSchema current = null;
                    schemaSerializable.Write(stream);
                    IEnumerator enumerator = xs.Schemas(schemaSerializable.TargetNamespace).GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        current = (XmlSchema)enumerator.Current;
                        stream2.SetLength(0L);
                        current.Write(stream2);
                        if (stream.Length == stream2.Length)
                        {
                            stream.Position  = 0L;
                            stream2.Position = 0L;
                            while ((stream.Position != stream.Length) && (stream.ReadByte() == stream2.ReadByte()))
                            {
                            }
                            if (stream.Position == stream.Length)
                            {
                                return(type2);
                            }
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (stream2 != null)
                    {
                        stream2.Close();
                    }
                }
            }
            xs.Add(schemaSerializable);
            return(type2);
        }
Ejemplo n.º 29
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        XmlSchemaElement thing1 = new XmlSchemaElement();

        thing1.Name           = "thing1";
        thing1.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        schema.Items.Add(thing1);

        XmlSchemaElement thing2 = new XmlSchemaElement();

        thing2.Name           = "thing2";
        thing2.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        schema.Items.Add(thing2);

        XmlSchemaElement thing3 = new XmlSchemaElement();

        thing3.Name           = "thing3";
        thing3.SchemaTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        schema.Items.Add(thing3);

        XmlSchemaElement thing4 = new XmlSchemaElement();

        thing4.Name           = "thing4";
        thing4.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        schema.Items.Add(thing4);

        XmlSchemaAttribute myAttribute = new XmlSchemaAttribute();

        myAttribute.Name           = "myAttribute";
        myAttribute.SchemaTypeName = new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema");
        schema.Items.Add(myAttribute);

        XmlSchemaComplexType myComplexType = new XmlSchemaComplexType();

        myComplexType.Name = "myComplexType";

        XmlSchemaAll complexType_all = new XmlSchemaAll();

        XmlSchemaElement complexType_all_thing1 = new XmlSchemaElement();

        complexType_all_thing1.RefName = new XmlQualifiedName("thing1", "");
        complexType_all.Items.Add(complexType_all_thing1);

        XmlSchemaElement complexType_all_thing2 = new XmlSchemaElement();

        complexType_all_thing2.RefName = new XmlQualifiedName("thing2", "");
        complexType_all.Items.Add(complexType_all_thing2);

        XmlSchemaElement complexType_all_thing3 = new XmlSchemaElement();

        complexType_all_thing3.RefName = new XmlQualifiedName("thing3", "");
        complexType_all.Items.Add(complexType_all_thing3);

        XmlSchemaElement complexType_all_thing4 = new XmlSchemaElement();

        complexType_all_thing4.RefName = new XmlQualifiedName("thing4", "");
        complexType_all.Items.Add(complexType_all_thing4);

        myComplexType.Particle = complexType_all;

        XmlSchemaAttribute complexType_myAttribute = new XmlSchemaAttribute();

        complexType_myAttribute.RefName = new XmlQualifiedName("myAttribute", "");
        myComplexType.Attributes.Add(complexType_myAttribute);

        schema.Items.Add(myComplexType);

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Ejemplo n.º 30
0
        private static XmlSchemaElement CaseSchema()
        {
            XmlSchemaComplexType type      = new XmlSchemaComplexType();
            XmlSchemaAll         allSchema = new XmlSchemaAll();

            type.Particle = allSchema;

            //When
            XmlSchemaComplexType subType = new XmlSchemaComplexType();
            XmlSchemaAny         any     = new XmlSchemaAny();

            any.MinOccurs       = 1;
            any.MaxOccursString = "unbounded";
            any.ProcessContents = XmlSchemaContentProcessing.Strict;
            any.Namespace       = "##local";

            XmlSchemaSequence sequence = new XmlSchemaSequence();

            subType.Particle = sequence;
            sequence.Items.Add(any);

            XmlSchemaElement subElement = new XmlSchemaElement();

            subElement.Name       = "when";
            subElement.SchemaType = subType;
            allSchema.Items.Add(subElement);

            //Then
            subType             = new XmlSchemaComplexType();
            any                 = new XmlSchemaAny();
            any.MinOccurs       = 1;
            any.MaxOccursString = "unbounded";
            any.ProcessContents = XmlSchemaContentProcessing.Strict;
            any.Namespace       = "##local";

            sequence         = new XmlSchemaSequence();
            subType.Particle = sequence;
            sequence.Items.Add(any);

            subElement            = new XmlSchemaElement();
            subElement.Name       = "then";
            subElement.SchemaType = subType;
            allSchema.Items.Add(subElement);

            //Else
            subType             = new XmlSchemaComplexType();
            any                 = new XmlSchemaAny();
            any.MinOccurs       = 1;
            any.MaxOccurs       = 1;
            any.ProcessContents = XmlSchemaContentProcessing.Strict;
            any.Namespace       = "##local";

            sequence         = new XmlSchemaSequence();
            subType.Particle = sequence;
            sequence.Items.Add(any);

            subElement            = new XmlSchemaElement();
            subElement.Name       = "else";
            subElement.SchemaType = subType;
            allSchema.Items.Add(subElement);

            XmlSchemaAttribute attrib = new XmlSchemaAttribute();

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

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

            XmlSchemaElement element = new XmlSchemaElement();

            element.Name       = "case";
            element.SchemaType = type;

            return(element);
        }
Ejemplo n.º 31
0
        private async Task <Tuple <string, object> > InternalReadContentAsObjectTupleAsync(bool unwrapTypedValue)
        {
            Tuple <string, object> tuple;
            string originalStringValue;

            XmlNodeType nodeType = this.NodeType;

            if (nodeType == XmlNodeType.Attribute)
            {
                originalStringValue = this.Value;
                if (_attributePSVI != null && _attributePSVI.typedAttributeValue != null)
                {
                    if (_validationState == ValidatingReaderState.OnDefaultAttribute)
                    {
                        XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute !;
                        originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue !;
                    }

                    tuple = new Tuple <string, object>(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType !, unwrapTypedValue));
                    return(tuple);
                }
                else
                {
                    // return string value
                    tuple = new Tuple <string, object>(originalStringValue, this.Value);
                    return(tuple);
                }
            }
            else if (nodeType == XmlNodeType.EndElement)
            {
                if (_atomicValue != null)
                {
                    Debug.Assert(_originalAtomicValueString != null);
                    originalStringValue = _originalAtomicValueString;

                    tuple = new Tuple <string, object>(originalStringValue, _atomicValue);
                    return(tuple);
                }
                else
                {
                    originalStringValue = string.Empty;

                    tuple = new Tuple <string, object>(originalStringValue, string.Empty);
                    return(tuple);
                }
            }
            else
            {
                // Positioned on text, CDATA, PI, Comment etc
                if (_validator.CurrentContentType == XmlSchemaContentType.TextOnly)
                {
                    // if current element is of simple type
                    object?value = ReturnBoxedValue(await ReadTillEndElementAsync().ConfigureAwait(false), _xmlSchemaInfo.XmlType !, unwrapTypedValue);
                    Debug.Assert(value != null);

                    Debug.Assert(_originalAtomicValueString != null);
                    originalStringValue = _originalAtomicValueString;

                    tuple = new Tuple <string, object>(originalStringValue, value);
                    return(tuple);
                }
                else
                {
                    XsdCachingReader?cachingReader = _coreReader as XsdCachingReader;
                    if (cachingReader != null)
                    {
                        originalStringValue = cachingReader.ReadOriginalContentAsString();
                    }
                    else
                    {
                        originalStringValue = await InternalReadContentAsStringAsync().ConfigureAwait(false);
                    }

                    tuple = new Tuple <string, object>(originalStringValue, originalStringValue);
                    return(tuple);
                }
            }
        }
Ejemplo n.º 32
0
        private ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns)
        {
            ArrayMapping arrayMapping;

            if (type.Name == Soap.Array && ns == Soap.Encoding)
            {
                arrayMapping = new ArrayMapping();
                TypeMapping     mapping      = GetRootMapping();
                ElementAccessor itemAccessor = new ElementAccessor();
                itemAccessor.IsSoap     = true;
                itemAccessor.Name       = Soap.UrType;
                itemAccessor.Namespace  = ns;
                itemAccessor.Mapping    = mapping;
                itemAccessor.IsNullable = true;
                itemAccessor.Form       = XmlSchemaForm.None;

                arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);
                return(arrayMapping);
            }
            if (!(type.DerivedFrom.Name == Soap.Array && type.DerivedFrom.Namespace == Soap.Encoding))
            {
                return(null);
            }

            // the type should be a XmlSchemaComplexType
            XmlSchemaContentModel model = ((XmlSchemaComplexType)type).ContentModel;

            // the Content  should be an restriction
            if (!(model.Content is XmlSchemaComplexContentRestriction))
            {
                return(null);
            }

            arrayMapping = new ArrayMapping();

            XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)model.Content;

            for (int i = 0; i < restriction.Attributes.Count; i++)
            {
                XmlSchemaAttribute attribute = restriction.Attributes[i] as XmlSchemaAttribute;
                if (attribute != null && attribute.RefName.Name == Soap.ArrayType && attribute.RefName.Namespace == Soap.Encoding)
                {
                    // read the value of the wsdl:arrayType attribute
                    string arrayType = null;

                    if (attribute.UnhandledAttributes != null)
                    {
                        foreach (XmlAttribute a in attribute.UnhandledAttributes)
                        {
                            if (a.LocalName == Wsdl.ArrayType && a.NamespaceURI == Wsdl.Namespace)
                            {
                                arrayType = a.Value;
                                break;
                            }
                        }
                    }
                    if (arrayType != null)
                    {
                        string           dims;
                        XmlQualifiedName typeName = TypeScope.ParseWsdlArrayType(arrayType, out dims, attribute);

                        TypeMapping mapping;
                        TypeDesc    td = Scope.GetTypeDesc(typeName.Name, typeName.Namespace);
                        if (td != null && td.IsPrimitive)
                        {
                            mapping          = new PrimitiveMapping();
                            mapping.TypeDesc = td;
                            mapping.TypeName = td.DataType.Name;
                        }
                        else
                        {
                            mapping = ImportType(typeName, false);
                        }
                        ElementAccessor itemAccessor = new ElementAccessor();
                        itemAccessor.IsSoap     = true;
                        itemAccessor.Name       = typeName.Name;
                        itemAccessor.Namespace  = ns;
                        itemAccessor.Mapping    = mapping;
                        itemAccessor.IsNullable = true;
                        itemAccessor.Form       = XmlSchemaForm.None;

                        arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                        arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                        arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);

                        return(arrayMapping);
                    }
                }
            }

            XmlSchemaParticle particle = restriction.Particle;

            if (particle is XmlSchemaAll || particle is XmlSchemaSequence)
            {
                XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
                if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaElement))
                {
                    return(null);
                }
                XmlSchemaElement itemElement = (XmlSchemaElement)group.Items[0];
                if (!itemElement.IsMultipleOccurrence)
                {
                    return(null);
                }
                ElementAccessor itemAccessor = ImportElement(itemElement, ns);
                arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc();
            }
            else
            {
                return(null);
            }
            return(arrayMapping);
        }
        public XmlSchemaElement GetSchema()
        {
            var type = new XmlSchemaComplexType();

            var attrib = new XmlSchemaAttribute
            {
                Name           = "device",
                Use            = XmlSchemaUse.Required,
                SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
            };

            type.Attributes.Add(attrib);

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

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

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

            restriction.Facets.Add(new XmlSchemaEnumerationFacet
            {
                Value = QCStatusEnum.Passed.Description
            });
            restriction.Facets.Add(new XmlSchemaEnumerationFacet
            {
                Value = QCStatusEnum.Failed.Description
            });
            restriction.Facets.Add(new XmlSchemaEnumerationFacet
            {
                Value = QCStatusEnum.Incomplete.Description
            });
            restriction.Facets.Add(new XmlSchemaEnumerationFacet
            {
                Value = QCStatusEnum.NA.Description
            });
            var qcStatusType = new XmlSchemaSimpleType
            {
                Content = restriction
            };

            attrib = new XmlSchemaAttribute
            {
                Name       = "qcStatus",
                Use        = XmlSchemaUse.Optional,
                SchemaType = qcStatusType
            };
            type.Attributes.Add(attrib);

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

            var element = new XmlSchemaElement
            {
                Name       = "study-auto-route",
                SchemaType = type
            };

            return(element);
        }
Ejemplo n.º 34
0
	public void DumpAttribute (XmlSchemaAttribute a)
	{
		depth++;

		IndentLine ("**Attribute**");
		IndentLine ("QualifiedName: " + a.QualifiedName);
		IndentLine ("RefName: " + a.RefName);
		IndentLine ("AttributeType:");
		DumpType (a.AttributeType);

		depth--;
	}