private XmlSchemaElement CityName()
        {
            var cityNameElement = new XmlSchemaElement();

            cityNameElement.Name = "CityName";

            var cityNameType        = new XmlSchemaSimpleType();
            var cityNameRestriction = new XmlSchemaSimpleTypeRestriction();

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

            var maxLength = new XmlSchemaMaxLengthFacet();

            maxLength.Value = "15";
            var minLenght = new XmlSchemaMinLengthFacet();

            minLenght.Value = "4";

            cityNameRestriction.Facets.Add(maxLength);
            cityNameRestriction.Facets.Add(minLenght);
            cityNameType.Content = cityNameRestriction;

            cityNameElement.SchemaType = cityNameType;
            return(cityNameElement);
        }
Exemplo n.º 2
0
        public static XmlSchemaType MapNumber <T>(T e) where T : IElement, IRestrictable
        {
            XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType();

            simpleType.Name = e.Name;


            XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();

            restriction.BaseTypeName = new System.Xml.XmlQualifiedName("decimal", DefaultSchemaNamespace);

            var min = e.Restrictions.FirstOrDefault(r => r.Key == "min");
            var max = e.Restrictions.FirstOrDefault(r => r.Key == "max");

            XmlSchemaMinLengthFacet mMin = new XmlSchemaMinLengthFacet();

            mMin.Value = min is null ? "1" : min.Value;
            restriction.Facets.Add(mMin);

            XmlSchemaMaxLengthFacet mMax = new XmlSchemaMaxLengthFacet();

            mMax.Value = max is null ? "100" : max.Value;
            restriction.Facets.Add(mMax);

            simpleType.Content = restriction;
            return(simpleType);
        }
Exemplo n.º 3
0
        internal XSMaxLengthFacet(XmlSchemaMaxLengthFacet maxLengthFacet)
        {
            _facet = maxLengthFacet;

            if (_facet.Annotation is XmlSchemaAnnotation annotation)
            {
                _annotation = XMLSchemaSerializer.CreateXSAnnotation(annotation);
                _annotation.BindToContainer(RootContainer, this);
            }
        }
Exemplo n.º 4
0
        private static XmlSchema CreateCustomerSchema2()
        {
            var firstNameElement = new XmlSchemaElement();

            firstNameElement.Name = "FirstName";
            var lastNameElement = new XmlSchemaElement();

            lastNameElement.Name = "LastName";
            var idAttribute = new XmlSchemaAttribute();

            idAttribute.Name = "CustomerId";
            idAttribute.Use  = XmlSchemaUse.Required;

            // Create the simple type for LastName element
            XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();

            lastNameType.Name = "LastNameType";
            var lastNameRestriction = new XmlSchemaSimpleTypeRestriction();

            lastNameRestriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);
            var maxLength = new XmlSchemaMaxLengthFacet();

            maxLength.Value = "20";
            lastNameRestriction.Facets.Add(maxLength);
            lastNameType.Content = lastNameRestriction;

            firstNameElement.SchemaTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);
            // user defined
            lastNameElement.SchemaTypeName = new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
            idAttribute.SchemaTypeName     = new XmlQualifiedName("positiveInteger", XmlSchema.Namespace);

            // customer top level element
            XmlSchemaElement customerElement = new XmlSchemaElement {
                Name = "Customer"
            };
            var customerType = new XmlSchemaComplexType();
            var sequence     = new XmlSchemaSequence();

            sequence.Items.Add(firstNameElement);
            sequence.Items.Add(lastNameElement);
            customerType.Particle = sequence;
            customerType.Attributes.Add(idAttribute);

            customerElement.SchemaType = customerType;

            XmlSchema customerSchema = new XmlSchema();

            customerSchema.TargetNamespace = "http://www.tempuri.org";
            customerSchema.Items.Add(customerElement);
            customerSchema.Items.Add(lastNameType);

            return(customerSchema);
        }
Exemplo n.º 5
0
        public bool AddMaxLengthConstraint(int maxLen)
        {
            if (maxLen < 0)
            {
                return(false);
            }

            XmlSchemaMaxLengthFacet maxLenFacet = new XmlSchemaMaxLengthFacet();

            maxLenFacet.Value = maxLen.ToString();
            Common.addFacet(maxLenFacet, Common.getElementFromSchema(baseSchema));

            return(true);
        }
Exemplo n.º 6
0
    static string deref_simple(XmlSchemaSimpleType simp)
    {
        XmlSchemaSimpleTypeRestriction xsstr = (XmlSchemaSimpleTypeRestriction)simp.Content;

        foreach (object o in xsstr.Facets)
        {
            if (o.GetType() == typeof(XmlSchemaMaxLengthFacet))
            {
                XmlSchemaMaxLengthFacet fac = (XmlSchemaMaxLengthFacet)o;
                return(fac.Value);
            }
        }
        return("");
    }
Exemplo n.º 7
0
        public bool AddMaxLengthConstraint(string max_length)
        {
            int maxLen;

            if (!int.TryParse(max_length, out maxLen) || maxLen < 0)
            {
                return(false);
            }

            XmlSchemaMaxLengthFacet maxLenFacet = new XmlSchemaMaxLengthFacet();

            maxLenFacet.Value = max_length;

            Common.addFacet(maxLenFacet, Common.getElementFromSchema(baseSchema));

            return(true);
        }
Exemplo n.º 8
0
        public static XmlSchemaType MapDecimal <T>(T e) where T : IElement, INamable, IRestrictable
        {
            var simpleType = new XmlSchemaSimpleType();

            simpleType.Name = e.Name;


            var restriction = new XmlSchemaSimpleTypeRestriction();

            restriction.BaseTypeName = new System.Xml.XmlQualifiedName("decimal", DefaultSchemaNamespace);

            var min      = e.Restrictions.FirstOrDefault(r => r.Key == "min");
            var max      = e.Restrictions.FirstOrDefault(r => r.Key == "max");
            var decimals = e.Restrictions.FirstOrDefault(r => r.Key == "decimals");

            if (min != null)
            {
                var mMin = new XmlSchemaMinLengthFacet();
                mMin.Value = min is null ? "1" : min.Value;
                restriction.Facets.Add(mMin);
            }

            if (max != null)
            {
                var mMax = new XmlSchemaMaxLengthFacet();
                mMax.Value = max is null ? "100" : max.Value;
                restriction.Facets.Add(mMax);
            }

            if (decimals != null)
            {
                var mFractionDigits = new XmlSchemaFractionDigitsFacet
                {
                    Value = decimals is null ? "2" : decimals.Value
                };
                restriction.Facets.Add(mFractionDigits);
            }

            simpleType.Content = restriction;
            return(simpleType);
        }
    }
Exemplo n.º 9
0
        private void CreateSimpletypeLength(string length, string minLength, string maxLength, bool expected)
        {
            passed = true;

            XmlSchema schema = new XmlSchema();

            XmlSchemaSimpleType testType = new XmlSchemaSimpleType();

            testType.Name = "TestType";

            XmlSchemaSimpleTypeRestriction testTypeRestriction = new XmlSchemaSimpleTypeRestriction();

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

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

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

            Assert(
                (passed ? "Test passed, should have failed" : "Test failed, should have passed") +
                ": " + length + " " + minLength + " " + maxLength,
                expected == passed);
        }
Exemplo n.º 10
0
        public bool AddRangeLengthConstraint(string sMinLen, string sMaxLen)
        {
            int minLen, maxLen;

            if (!int.TryParse(sMinLen, out minLen) ||
                !int.TryParse(sMaxLen, out maxLen) ||
                maxLen < 0 || minLen < 0 || minLen > maxLen)                            // FIXME
            {
                return(false);
            }

            XmlSchemaMaxLengthFacet maxLenFacet = new XmlSchemaMaxLengthFacet();

            maxLenFacet.Value = maxLen.ToString();
            Common.addFacet(maxLenFacet, Common.getElementFromSchema(baseSchema));
            XmlSchemaMinLengthFacet minLenFacet = new XmlSchemaMinLengthFacet();

            minLenFacet.Value = minLen.ToString();
            Common.addFacet(minLenFacet, Common.getElementFromSchema(baseSchema));
            return(true);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     Returns a simple type which extends the basic datatype and
        ///     restricts is using the string validator
        /// </summary>
        public override XmlSchemaSimpleType GetSimpleType(string attributeDataType)
        {
            var retVal      = base.GetSimpleType(attributeDataType);
            var restriction = (XmlSchemaSimpleTypeRestriction)retVal.Content;

            var sva = (StringValidatorAttribute)Attribute;

            if (!string.IsNullOrEmpty(sva.InvalidCharacters))
            {
                var pFacet = new XmlSchemaPatternFacet {
                    Value = sva.InvalidCharacters
                };
                // TODO: convert this to a regex that excludes the characters
                pFacet.Value = string.Format(
                    "[^{0}]*",
                    pFacet.Value
                    .Replace(@"\", @"\\")
                    .Replace(@"[", @"\[")
                    .Replace(@"]", @"\]"));

                restriction.Facets.Add(pFacet);
            }

            var minFacet = new XmlSchemaMinLengthFacet {
                Value = sva.MinLength.ToString()
            };

            restriction.Facets.Add(minFacet);

            var maxFacet = new XmlSchemaMaxLengthFacet {
                Value = sva.MaxLength.ToString()
            };

            restriction.Facets.Add(maxFacet);

            return(retVal);
        }
Exemplo n.º 12
0
        public static XmlSchemaType MapString <T>(T e) where T : IElement, INamable, IRestrictable
        {
            var simpleType = new XmlSchemaSimpleType();

            simpleType.Name = e.Name;


            var restriction = new XmlSchemaSimpleTypeRestriction();

            restriction.BaseTypeName = new System.Xml.XmlQualifiedName("string", DefaultSchemaNamespace);

            var min     = e.Restrictions.FirstOrDefault(r => r.Key == "min");
            var max     = e.Restrictions.FirstOrDefault(r => r.Key == "max");
            var pattern = e.Restrictions.FirstOrDefault(r => r.Key == "pattern");

            var mMin = new XmlSchemaMinLengthFacet();

            mMin.Value = min is null ? "1" : min.Value;
            restriction.Facets.Add(mMin);

            var mMax = new XmlSchemaMaxLengthFacet();

            mMax.Value = max is null ? "100" : max.Value;
            restriction.Facets.Add(mMax);

            if (pattern != null)
            {
                var mPattern = new XmlSchemaMaxLengthFacet();
                mPattern.Value = mPattern?.Value ?? "";
                restriction.Facets.Add(mPattern);
            }


            simpleType.Content = restriction;
            return(simpleType);
        }
 protected override void Visit(XmlSchemaMaxLengthFacet facet)
 {
     AddLeaf(SimpleTypeStructureNodeType.FacetMaxLength, facet);
 }
        internal string GenerateSimpleType(
            XmlSchemaSimpleType type,
            CodeCompileUnit compileUnit,
            CodeNamespace mainNamespace,
            CodeGenerationOptions options,
            CodeDomProvider codeProvider)
        {
            CodeTypeDeclaration codeClass = CodeDomHelper.CreateClassDeclaration(type);

            mainNamespace.Types.Add(codeClass);

            CodeDomHelper.GenerateXmlTypeAttribute(codeClass, type.QualifiedName.Name, type.QualifiedName.Namespace);

            XmlSchemaSimpleTypeRestriction restriction = type.Content as XmlSchemaSimpleTypeRestriction;

            Type            baseType = XsdToClrPrimitive(restriction.BaseTypeName);
            CodeMemberField field    = CodeDomHelper.AddField(codeClass, "value", baseType);

            CodeMemberProperty prop = CodeDomHelper.AddPropertyDeclaration(codeClass, field, "Value", baseType);

            CodeDomHelper.AddTextAttribute(prop.CustomAttributes);

            CodeDomHelper.AddCtor(codeClass);
            CodeDomHelper.AddCtor(codeClass, prop);

            // for each facet we support, add validation to the setter
            foreach (object facet in restriction.Facets)
            {
                XmlSchemaLengthFacet length = facet as XmlSchemaLengthFacet;
                if (length != null)
                {
                    int?value = ToInt32(length.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength             = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("length", value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaPatternFacet pattern = facet as XmlSchemaPatternFacet;
                if (pattern != null)
                {
                    // TODO: might want ot validate the pattern value here to make sure that it is a valid Regex.
                    if (!string.IsNullOrEmpty(pattern.Value))
                    {
                        CodeExpression patternMatch =
                            CodeDomHelper.MethodCall(
                                CodeDomHelper.TypeExpr(typeof(Regex)), "IsMatch", new CodeExpression[] { CodeDomHelper.Value(), CodeDomHelper.Primitive(pattern.Value) });

                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(patternMatch, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("pattern", pattern.Value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaMinLengthFacet minLength = facet as XmlSchemaMinLengthFacet;
                if (minLength != null)
                {
                    int?value = ToInt32(minLength.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength             = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("minLength", value) }, new CodeStatement[0]));
                    }
                    continue;
                }

                XmlSchemaMaxLengthFacet maxLength = facet as XmlSchemaMaxLengthFacet;
                if (maxLength != null)
                {
                    int?value = ToInt32(maxLength.Value);
                    if (value.HasValue)
                    {
                        CodeExpression valueLength             = CodeDomHelper.Property(CodeDomHelper.Value(), "Length");
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(valueLength, CodeBinaryOperatorType.GreaterThan, new CodePrimitiveExpression(value));
                        prop.SetStatements.Add(new CodeConditionStatement(condition, new CodeStatement[] { CodeDomHelper.ThrowFacetViolation("maxLength", value) }, new CodeStatement[0]));
                    }
                    continue;
                }
            }

            //add ToSrting() Overload and implicit and explicit Cast operators for compatibilty woth previously generated code

            CodeMemberMethod toString = CodeDomHelper.MethodDecl(typeof(string), "ToString", MemberAttributes.Public | MemberAttributes.Override);

            toString.Statements.Add(CodeDomHelper.Return(CodeDomHelper.Property("value")));
            codeClass.Members.Add(toString);

            // Unfortunately CodeDom does not support operators, so we have to use CodeSnippet to generate the Cast operators
            // CodeSnippet is not language aware, so we have to use different snippets for different providers
            // this version only support c# syntax
            if (codeProvider is Microsoft.CSharp.CSharpCodeProvider)
            {
                string implicitCast = string.Format("    public static implicit operator {0}({1} x) {{ return new {0}(x); }}", codeClass.Name, baseType.FullName);
                CodeSnippetTypeMember implicitOp = new CodeSnippetTypeMember(implicitCast);
                codeClass.Members.Add(implicitOp);

                string explicitCast = string.Format("    public static explicit operator {1}({0} x) {{ return x.Value; }}", codeClass.Name, baseType.FullName);
                CodeSnippetTypeMember explicitOp = new CodeSnippetTypeMember(explicitCast);
                codeClass.Members.Add(explicitOp);
            }

            return(codeClass.Name);
        }
Exemplo n.º 15
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:maxLength value="10"/>
        XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();

        maxLength.Value = "10";
        restriction.Facets.Add(maxLength);

        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);
    }
Exemplo n.º 16
0
        /// <summary>
        /// Render field-criteria such as max length and patterns.
        /// </summary>
        /// <param name="restrictions">XSD restriction object to receive the facets.</param>
        /// <param name="fieldEntity">The field being described.</param>
        /// <param name="fieldTypeAlias">The XSD type string for the field type. E.g. 'string'.</param>
        private void AddFieldRestrictions(XmlSchemaSimpleTypeRestriction restrictions, Entity fieldEntity, string fieldTypeAlias)
        {
            switch (fieldTypeAlias)
            {
            // Int constraints
            case "intField":
                int?minValue = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MinInt);
                if (minValue != null)
                {
                    var minFacet = new XmlSchemaMinInclusiveFacet()
                    {
                        Value = minValue.ToString()
                    };
                    restrictions.Facets.Add(minFacet);
                }
                int?maxValue = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MaxInt);
                if (maxValue != null)
                {
                    var maxFacet = new XmlSchemaMaxInclusiveFacet()
                    {
                        Value = maxValue.ToString()
                    };
                    restrictions.Facets.Add(maxFacet);
                }
                break;

            // String constraints
            case "stringField":
                int?minLength = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MinLength);
                if (minLength != null)
                {
                    var minFacet = new XmlSchemaMinLengthFacet()
                    {
                        Value = minLength.ToString()
                    };
                    restrictions.Facets.Add(minFacet);
                }
                int?maxLength = _schemaManager.GetIntFieldValue(fieldEntity, Aliases2.MaxLength);
                if (maxLength != null)
                {
                    var maxFacet = new XmlSchemaMaxLengthFacet()
                    {
                        Value = maxLength.ToString()
                    };
                    restrictions.Facets.Add(maxFacet);
                }
                var stringPattern = _schemaManager.GetRelationshipsFromEntity(fieldEntity, A(Aliases2.Pattern)).FirstOrDefault();
                if (stringPattern != null)
                {
                    string sRegex = _schemaManager.GetStringFieldValue(stringPattern, Aliases2.Regex);
                    if (sRegex != null)
                    {
                        var regexFacet = new XmlSchemaPatternFacet()
                        {
                            Value = sRegex
                        };
                        restrictions.Facets.Add(regexFacet);
                    }
                }
                break;

            // String constraints
            case "aliasField":
                // optional namespace prefix, followed by lower-case alpha, alphanumeric
                string aliasRegex      = @"([_a-zA-Z][_a-zA-Z0-9]*\:)?[_a-zA-Z][_a-zA-Z0-9]{0,99}";
                var    aliasRegexFacet = new XmlSchemaPatternFacet()
                {
                    Value = aliasRegex
                };
                restrictions.Facets.Add(aliasRegexFacet);
                break;
            }
        }
Exemplo n.º 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            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!");
        }
Exemplo n.º 18
0
        private XmlSchemaSimpleTypeRestriction ExtractStringFacets(JsonSchema jSchema)
        {
            XmlSchemaSimpleTypeRestriction content = new XmlSchemaSimpleTypeRestriction
            {
                BaseTypeName = new XmlQualifiedName("string", XML_SCHEMA_NS),
            };

            EnumKeyword enumKeyword = jSchema.Get<EnumKeyword>();
            if (enumKeyword != null)
            {
                foreach (JsonValue enumValue in GetterExtensions.Enum(jSchema))
                {
                    XmlSchemaEnumerationFacet enumFacet = new XmlSchemaEnumerationFacet
                    {
                        Value = enumValue.String,
                    };
                    content.Facets.Add(enumFacet);
                }
            }

            MinLengthKeyword minLength = jSchema.Get<MinLengthKeyword>();
            MaxLengthKeyword maxLength = jSchema.Get<MaxLengthKeyword>();

            if (minLength != null && maxLength != null && minLength.Value == maxLength.Value)
            {
                // special rule that maps equal min and max lengths to xsd length facet
                XmlSchemaLengthFacet lengthFacet = new XmlSchemaLengthFacet
                {
                    Value = minLength.Value.ToString(),
                };
                content.Facets.Add(lengthFacet);
            }
            else
            {
                if (minLength != null)
                {
                    XmlSchemaMinLengthFacet minLengthFacet = new XmlSchemaMinLengthFacet
                    {
                        Value = minLength.Value.ToString(),
                    };
                    content.Facets.Add(minLengthFacet);
                }

                if (maxLength != null)
                {
                    XmlSchemaMaxLengthFacet maxLengthFacet = new XmlSchemaMaxLengthFacet
                    {
                        Value = maxLength.Value.ToString(),
                    };
                    content.Facets.Add(maxLengthFacet);
                }
            }

            PatternKeyword pattern = jSchema.Get<PatternKeyword>();
            if (pattern != null)
            {
                XmlSchemaPatternFacet patternFacet = new XmlSchemaPatternFacet
                {
                    Value = pattern.Value.ToString(),
                };

                content.Facets.Add(patternFacet);
            }

            FormatKeyword format = jSchema.Get<FormatKeyword>();
            if (format != null && format.Value != null && !string.IsNullOrEmpty(format.Value.Key))
            {
                content.BaseTypeName = ExtractBaseTypeNameFromFormat(format.Value.Key);
            }

            return content;
        }
Exemplo n.º 19
0
        public static IEnumerable <XmlSchemaFacet> createXmlFacets(IEnumerable <ICctsFacet> facets)
        {
            var xmlFacets = new List <XmlSchemaFacet>();

            foreach (var facet in facets)
            {
                XmlSchemaFacet xmlFacet = null;
                switch (facet.name)
                {
                case "fractionDigit":
                    xmlFacet = new XmlSchemaFractionDigitsFacet();
                    break;

                case "length":
                    xmlFacet = new XmlSchemaLengthFacet();
                    break;

                case "maxExclusive":
                    xmlFacet = new XmlSchemaMaxExclusiveFacet();
                    break;

                case "maxInclusive":
                    xmlFacet = new XmlSchemaMaxInclusiveFacet();
                    break;

                case "maxLength":
                    xmlFacet = new XmlSchemaMaxLengthFacet();
                    break;

                case "minExclusive":
                    xmlFacet = new XmlSchemaMinExclusiveFacet();
                    break;

                case "minInclusive":
                    xmlFacet = new XmlSchemaMinInclusiveFacet();
                    break;

                case "minLength":
                    xmlFacet = new XmlSchemaMinLengthFacet();
                    break;

                case "pattern":
                    xmlFacet = new XmlSchemaPatternFacet();
                    break;

                case "totalDigits":
                    xmlFacet = new XmlSchemaTotalDigitsFacet();
                    break;

                case "whiteSpace":
                    xmlFacet = new XmlSchemaWhiteSpaceFacet();
                    break;

                case "enumeration":
                    foreach (var enumValue in facet.content.Split('|'))
                    {
                        var enumerationFacet = new XmlSchemaEnumerationFacet();
                        enumerationFacet.Value = enumValue;
                        xmlFacets.Add(enumerationFacet);
                    }
                    break;
                }
                if (xmlFacet != null)
                {
                    xmlFacet.Value = facet.content;
                    xmlFacets.Add(xmlFacet);
                }
            }
            return(xmlFacets);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Запись в новый XSD файл содержимого класса SeSchemaItem
        /// </summary>
        /// <param name="newXSDElement">Новый элемент в схеме</param>
        /// <param name="xs">Новый экземпляр схемы</param>
        public void SaveXSD(XmlSchemaElement newXSDElement, XmlSchema xs)
        {
            SetProperties(newXSDElement);
            if (Type == "")
            {
                XmlSchemaComplexType newSchemaType = new XmlSchemaComplexType();
                newXSDElement.SchemaType = newSchemaType;
                XmlSchemaAll newAll = new XmlSchemaAll();
                if (Properties != null)
                {
                    Properties.SetPropAll(newAll);
                }
                newSchemaType.Particle = newAll;
                foreach (SeSchemaItem ssi in SchemaItemsChildren)
                {
                    XmlSchemaElement newElement = new XmlSchemaElement();
                    newElement.Name = ssi.Name;
                    ssi.SetProperties(newElement);
                    if (ssi.Description != null && ssi.Description != "")
                    {
                        newElement.Annotation = SetAnnotation(ssi);
                    }
                    if (ssi.SchemaItemsChildren != null && ssi.SchemaItemsChildren.Count != 0)
                    {
                        if (ssi.SchemaItemsChildren[0].Name == "SimpleType")
                        {
                            XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType();
                            newElement.SchemaType = simpleType;
                            XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                            simpleType.Content       = restriction;
                            restriction.BaseTypeName = new XmlQualifiedName(ssi.Type, "http://www.w3.org/2001/XMLSchema");
                            foreach (SeSchemaItem sstc in ssi.SchemaItemsChildren)
                            {
                                string facetName  = sstc.Description.Split('-')[0];
                                string facetValue = sstc.Description.Split('-')[1];
                                if (facetName == "XmlSchemaMaxLengthFacet")
                                {
                                    XmlSchemaMaxLengthFacet ml = new XmlSchemaMaxLengthFacet();
                                    restriction.Facets.Add(ml);
                                    ml.Value = facetValue;
                                }
                                if (facetName == "XmlSchemaTotalDigitsFacet")
                                {
                                    XmlSchemaTotalDigitsFacet ml = new XmlSchemaTotalDigitsFacet();
                                    restriction.Facets.Add(ml);
                                    ml.Value = facetValue;
                                }
                                if (facetName == "XmlSchemaFractionDigitsFacet")
                                {
                                    XmlSchemaFractionDigitsFacet ml = new XmlSchemaFractionDigitsFacet();
                                    restriction.Facets.Add(ml);
                                    ml.Value = facetValue;
                                }
                            }
                        }

                        else
                        {
                            if (ssi.CheckToCommonTypes() == true)
                            {
                                newElement.SchemaTypeName = new XmlQualifiedName(ssi.Type, "http://www.w3.org/2001/XMLSchema");
                            }
                            else
                            {
                                newElement.SchemaTypeName = new XmlQualifiedName(ssi.Type);
                            };
                        }
                    }
                    else
                    {
                        if (ssi.CheckToCommonTypes() == true)
                        {
                            newElement.SchemaTypeName = new XmlQualifiedName(ssi.Type, "http://www.w3.org/2001/XMLSchema");
                        }
                        else
                        {
                            newElement.SchemaTypeName = new XmlQualifiedName(ssi.Type);
                        }
                    }
                    newAll.Items.Add(newElement);
                }
            }
            else
            {
                if (CheckToCommonTypes() == true)
                {
                    newXSDElement.SchemaTypeName = new XmlQualifiedName(Type, "http://www.w3.org/2001/XMLSchema");
                }
                else
                {
                    newXSDElement.SchemaTypeName = new XmlQualifiedName(Type);
                };
            }
        }
Exemplo n.º 21
0
    static void Main(string[] args)
    {
        //<snippet2>
        // Create the FirstName and LastName elements.
        XmlSchemaElement firstNameElement = new XmlSchemaElement();

        firstNameElement.Name = "FirstName";
        XmlSchemaElement lastNameElement = new XmlSchemaElement();

        lastNameElement.Name = "LastName";

        // Create CustomerId attribute.
        XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();

        idAttribute.Name = "CustomerId";
        idAttribute.Use  = XmlSchemaUse.Required;
        //</snippet2>

        //<snippet3>
        // Create the simple type for the LastName element.
        XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();

        lastNameType.Name = "LastNameType";
        XmlSchemaSimpleTypeRestriction lastNameRestriction =
            new XmlSchemaSimpleTypeRestriction();

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

        maxLength.Value = "20";
        lastNameRestriction.Facets.Add(maxLength);
        lastNameType.Content = lastNameRestriction;

        // Associate the elements and attributes with their types.
        // Built-in type.
        firstNameElement.SchemaTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        // User-defined type.
        lastNameElement.SchemaTypeName =
            new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
        // Built-in type.
        idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger",
                                                          "http://www.w3.org/2001/XMLSchema");

        // Create the top-level Customer element.
        XmlSchemaElement customerElement = new XmlSchemaElement();

        customerElement.Name = "Customer";

        // Create an anonymous complex type for the Customer element.
        XmlSchemaComplexType customerType = new XmlSchemaComplexType();
        XmlSchemaSequence    sequence     = new XmlSchemaSequence();

        sequence.Items.Add(firstNameElement);
        sequence.Items.Add(lastNameElement);
        customerType.Particle = sequence;

        // Add the CustomerId attribute to the complex type.
        customerType.Attributes.Add(idAttribute);

        // Set the SchemaType of the Customer element to
        // the anonymous complex type created above.
        customerElement.SchemaType = customerType;
        //</snippet3>

        //<snippet4>
        // Create an empty schema.
        XmlSchema customerSchema = new XmlSchema();

        customerSchema.TargetNamespace = "http://www.tempuri.org";

        // Add all top-level element and types to the schema
        customerSchema.Items.Add(customerElement);
        customerSchema.Items.Add(lastNameType);

        // Create an XmlSchemaSet to compile the customer schema.
        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add(customerSchema);
        schemaSet.Compile();

        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Write the complete schema to the Console.
        customerSchema.Write(Console.Out);
        //</snippet4>
    }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
0
        public XsdSimpleRestrictionType(RelaxngDatatype primitive, RelaxngParamList parameters)
        {
            type = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction r =
                new XmlSchemaSimpleTypeRestriction();

            type.Content = r;
            string ns = primitive.NamespaceURI;

            // Remap XML Schema datatypes namespace -> XML Schema namespace.
            if (ns == "http://www.w3.org/2001/XMLSchema-datatypes")
            {
                ns = XSchema.Namespace;
            }
            r.BaseTypeName = new XmlQualifiedName(primitive.Name, ns);
            foreach (RelaxngParam p in parameters)
            {
                XmlSchemaFacet f     = null;
                string         value = p.Value;
                switch (p.Name)
                {
                case "maxExclusive":
                    f = new XmlSchemaMaxExclusiveFacet();
                    break;

                case "maxInclusive":
                    f = new XmlSchemaMaxInclusiveFacet();
                    break;

                case "minExclusive":
                    f = new XmlSchemaMinExclusiveFacet();
                    break;

                case "minInclusive":
                    f = new XmlSchemaMinInclusiveFacet();
                    break;

                case "pattern":
                    f = new XmlSchemaPatternFacet();
                    // .NET/Mono Regex has a bug that it does not support "IsLatin-1Supplement"
                    // (it somehow breaks at '-').
                    value = value.Replace("\\p{IsLatin-1Supplement}", "[\\x80-\\xFF]");
                    break;

                case "whiteSpace":
                    f = new XmlSchemaWhiteSpaceFacet();
                    break;

                case "length":
                    f = new XmlSchemaLengthFacet();
                    break;

                case "maxLength":
                    f = new XmlSchemaMaxLengthFacet();
                    break;

                case "minLength":
                    f = new XmlSchemaMinLengthFacet();
                    break;

                case "fractionDigits":
                    f = new XmlSchemaFractionDigitsFacet();
                    break;

                case "totalDigits":
                    f = new XmlSchemaTotalDigitsFacet();
                    break;

                default:
                    throw new RelaxngException(String.Format("XML Schema facet {0} is not recognized or not supported.", p.Name));
                }
                f.Value = value;
                r.Facets.Add(f);
            }

            // Now we create XmlSchema to handle simple-type
            // based validation (since there is no other way,
            // because of sucky XmlSchemaSimpleType design).
            schema = new XSchema();
            XmlSchemaElement el = new XmlSchemaElement();

            el.Name       = "root";
            el.SchemaType = type;
            schema.Items.Add(el);
            schema.Compile(null);
        }
        private XmlSchemaSimpleType SetSchemaFacets(XmlSchemaSimpleType simpleType, List <MessagePart> MessageParts)
        {
            Debug.Assert(!(simpleType.Content is XmlSchemaSimpleTypeUnion), "Cannot apply restrictions to unions.");
            Debug.Assert(!(simpleType.Content is XmlSchemaSimpleTypeList), "Cannot apply restrictions to lists.");

            XmlSchemaSimpleTypeRestriction oldRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction;
            XmlSchemaSimpleTypeRestriction restriction    = new XmlSchemaSimpleTypeRestriction();

            //preserve existing facets
            if (oldRestriction != null)
            {
                foreach (XmlSchemaObject restrictionFacet in oldRestriction.Facets)
                {
                    if (!(restrictionFacet is XmlSchemaMaxLengthFacet) && !(restrictionFacet is XmlSchemaMinLengthFacet))
                    {
                        restriction.Facets.Add(restrictionFacet);
                    }
                }
            }

            foreach (MessagePart messagePart in MessageParts)
            {
                StringLengthMessagePart stringLengthMessagePart = messagePart as StringLengthMessagePart;
                RegexMessagePart        regexMessagePart        = messagePart as RegexMessagePart;
                RangeMessagePart        rangeMessagePart        = messagePart as RangeMessagePart;

                if (stringLengthMessagePart != null)
                {
                    if (stringLengthMessagePart.MaxLength > 0)
                    {
                        XmlSchemaMaxLengthFacet maxLengthFacet = new XmlSchemaMaxLengthFacet();
                        maxLengthFacet.Value = stringLengthMessagePart.MaxLength.ToString();
                        restriction.Facets.Add(maxLengthFacet);
                    }
                    if (stringLengthMessagePart.MinLength > 0)
                    {
                        XmlSchemaMinLengthFacet minLengthFacet = new XmlSchemaMinLengthFacet();
                        minLengthFacet.Value = stringLengthMessagePart.MinLength.ToString();
                        restriction.Facets.Add(minLengthFacet);
                    }
                }

                if (regexMessagePart != null)
                {
                    XmlSchemaPatternFacet patternFacet = new XmlSchemaPatternFacet();
                    patternFacet.Value = regexMessagePart.Regex;
                    restriction.Facets.Add(patternFacet);
                }

                if (rangeMessagePart != null)
                {
                    XmlSchemaMinInclusiveFacet minInclusiveFacet = new XmlSchemaMinInclusiveFacet();
                    minInclusiveFacet.Value = rangeMessagePart.Min.ToString();
                    restriction.Facets.Add(minInclusiveFacet);

                    XmlSchemaMaxInclusiveFacet maxInclusiveFacet = new XmlSchemaMaxInclusiveFacet();
                    maxInclusiveFacet.Value = rangeMessagePart.Max.ToString();
                    restriction.Facets.Add(maxInclusiveFacet);
                }
            }

            restriction.BaseTypeName = simpleType.QualifiedName;

            XmlSchemaSimpleType newType = new XmlSchemaSimpleType();

            newType.Content = restriction;

            return(newType);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the Aggregate Schema associated with the GML objects served by the WMS/WFS Servers
        /// </summary>
        /// <param name="WmsLayer"></param>
        /// <returns></returns>
        public static XmlSchema GetFeatureSchema(ViewContext context, bool includeGMLBaseReference)
        {
            XmlSchema schema = new XmlSchema();

            schema.Version = "1.0.0";
            schema.Namespaces.Add(Declarations.Wfs100DefaultPrefix, Declarations.Wfs100DefaultNameSpace);
            schema.Namespaces.Add(Declarations.DefaultPrefix, Declarations.DefaultNameSpace);
            schema.Namespaces.Add(Declarations.GmlPrefix, Declarations.GmlNameSpace);
            schema.Namespaces.Add(Declarations.GmlSfPrefix, Declarations.GmlSfNameSpace);
            schema.Namespaces.Add(Declarations.XlinkPrefix, Declarations.XlinkNameSpace);
            schema.TargetNamespace    = Declarations.DefaultNameSpace;
            schema.ElementFormDefault = XmlSchemaForm.Qualified;

            XmlSchemaImport schemaImport = new XmlSchemaImport();

            schema.Includes.Add(schemaImport);
            schemaImport.Namespace      = Declarations.GmlNameSpace;
            schemaImport.SchemaLocation = Declarations.GmlSchemaLocation;

            schemaImport = new XmlSchemaImport();
            schema.Includes.Add(schemaImport);
            schemaImport.Namespace      = Declarations.GmlSfNameSpace;
            schemaImport.SchemaLocation = Declarations.GmlSfLevelsSchemaLocation;

            XmlSchemaElement                 schemaElement                 = null;
            XmlSchemaComplexType             schemaComplexType             = null;
            XmlSchemaComplexContent          schemaComplexContent          = null;
            XmlSchemaComplexContentExtension schemaComplexContentExtension = null;
            XmlSchemaSequence                schemaSequence                = null;
            XmlDocument document = null;

            if (includeGMLBaseReference)
            {
                XmlSchemaAnnotation schemaAnnotation = new XmlSchemaAnnotation();
                schema.Items.Add(schemaAnnotation);
                XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo();
                schemaAnnotation.Items.Add(appInfo);
                appInfo.Source = Declarations.GmlSfLevelsSchemaLocation;

                XmlNode[] markupNodes = new XmlNode[2];
                appInfo.Markup = markupNodes;

                document                 = new XmlDocument();
                markupNodes[0]           = document.CreateNode(XmlNodeType.Element, "ComplianceLevel", Declarations.DefaultNameSpace);
                markupNodes[0].InnerText = "0";
                markupNodes[1]           = document.CreateNode(XmlNodeType.Element, "GMLProfileSchema", Declarations.DefaultNameSpace);
                markupNodes[1].InnerText = Declarations.GmlSfProfileSchemaLocation;

                schemaElement = new XmlSchemaElement();
                schema.Items.Add(schemaElement);
                schemaElement.Name              = "FeatureCollection";
                schemaElement.SchemaTypeName    = new XmlQualifiedName("FeatureCollectionType", Declarations.DefaultNameSpace);
                schemaElement.SubstitutionGroup = new XmlQualifiedName("_GML", Declarations.GmlNameSpace);

                schemaComplexType = new XmlSchemaComplexType();
                schema.Items.Add(schemaComplexType);
                schemaComplexType.Name = "FeatureCollectionType";

                schemaComplexContent                       = new XmlSchemaComplexContent();
                schemaComplexType.ContentModel             = schemaComplexContent;
                schemaComplexContentExtension              = new XmlSchemaComplexContentExtension();
                schemaComplexContent.Content               = schemaComplexContentExtension;
                schemaComplexContentExtension.BaseTypeName = new XmlQualifiedName("AbstractFeatureType", Declarations.GmlNameSpace);

                schemaSequence = new XmlSchemaSequence();
                schemaComplexContentExtension.Particle = schemaSequence;
                schemaSequence.MinOccurs       = 0;
                schemaSequence.MaxOccursString = "unbounded";

                schemaElement = new XmlSchemaElement();
                schemaSequence.Items.Add(schemaElement);
                schemaElement.Name = "featureMember";

                schemaComplexType          = new XmlSchemaComplexType();
                schemaElement.SchemaType   = schemaComplexType;
                schemaSequence             = new XmlSchemaSequence();
                schemaComplexType.Particle = schemaSequence;

                schemaElement = new XmlSchemaElement();
                schemaSequence.Items.Add(schemaElement);
                schemaElement.RefName = new XmlQualifiedName("_Feature", Declarations.GmlNameSpace);
            }

            string         geometryPropertyType = string.Empty;
            string         featureTypeName      = string.Empty;
            FeatureDataRow thisFeature          = null;

            foreach (GeospatialServices.Ogc.Wmc.Layer wmcLayer in context.Layers)
            {
                thisFeature = wmcLayer.GetFeatureDataRow(0);
                if (thisFeature != null)
                {
                    schemaElement = new XmlSchemaElement();
                    schema.Items.Add(schemaElement);
                    schemaElement.Name = wmcLayer.Name;

                    featureTypeName = wmcLayer.Name + "Type";

                    schemaElement.SchemaTypeName    = new XmlQualifiedName(featureTypeName, Declarations.DefaultNameSpace);
                    schemaElement.SubstitutionGroup = new XmlQualifiedName("_Feature", Declarations.GmlNameSpace);

                    schemaComplexType = new XmlSchemaComplexType();
                    schema.Items.Add(schemaComplexType);
                    schemaComplexType.Name = featureTypeName;

                    schemaComplexContent                       = new XmlSchemaComplexContent();
                    schemaComplexType.ContentModel             = schemaComplexContent;
                    schemaComplexContentExtension              = new XmlSchemaComplexContentExtension();
                    schemaComplexContent.Content               = schemaComplexContentExtension;
                    schemaComplexContentExtension.BaseTypeName = new XmlQualifiedName("AbstractFeatureType", Declarations.GmlNameSpace);

                    schemaSequence = new XmlSchemaSequence();
                    schemaComplexContentExtension.Particle = schemaSequence;

                    XmlSchemaSimpleType     schemaSimpleType = null;
                    XmlSchemaMaxLengthFacet maxLengthFacet   = null;

                    foreach (DataColumn thisColumn in thisFeature.Table.Columns)
                    {
                        schemaElement = new XmlSchemaElement();
                        schemaSequence.Items.Add(schemaElement);

                        schemaElement.Name      = thisColumn.ColumnName;
                        schemaElement.MinOccurs = thisColumn.AllowDBNull ? 0 : 1;

                        schemaSimpleType         = new XmlSchemaSimpleType();
                        schemaElement.SchemaType = schemaSimpleType;

                        XmlSchemaSimpleTypeRestriction schemaSimpleTypeRestriction = new XmlSchemaSimpleTypeRestriction();
                        schemaSimpleType.Content = schemaSimpleTypeRestriction;
                        schemaSimpleTypeRestriction.BaseTypeName = new XmlQualifiedName(OgcUtilities.GetGmlSfType(thisColumn), Declarations.XsNameSpace);

                        if (thisColumn.MaxLength > -1)
                        {
                            maxLengthFacet       = new XmlSchemaMaxLengthFacet();
                            maxLengthFacet.Value = thisColumn.MaxLength.ToString();
                            schemaSimpleTypeRestriction.Facets.Add(maxLengthFacet);
                        }
                    }
                    // Geometry
                    schemaElement = new XmlSchemaElement();
                    schemaSequence.Items.Add(schemaElement);
                    schemaElement.Name           = GMLDeclarations.GeometryFeatureElementName;
                    geometryPropertyType         = OgcUtilities.GetGmlSfGeometricPropertyType(thisFeature.Geometry);
                    schemaElement.SchemaTypeName = new XmlQualifiedName(geometryPropertyType, Declarations.GmlNameSpace);
                    schemaElement.MinOccurs      = 0;
                }
            }
            return(schema);
        }
Exemplo n.º 26
0
        private XmlAttributeType GetAttributeType(XmlSchemaSimpleType simpleType)
        {
            XmlAttributeType attributeType;

            if (!m_attributeTypes.TryGetValue(simpleType.QualifiedName.ToString(), out attributeType))
            {
                bool simpleList = simpleType.Content is XmlSchemaSimpleTypeList;
                int  length     = 1;
                if (simpleList)
                {
                    length = Int32.MaxValue; // unbounded, until restricted
                }
                List <AttributeRule>           rules       = null;
                XmlSchemaSimpleTypeRestriction restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction;
                if (restriction != null)
                {
                    if (restriction.BaseTypeName != null)
                    {
                        XmlAttributeType baseType;
                        m_attributeTypes.TryGetValue(restriction.BaseTypeName.ToString(), out baseType);
                        if (baseType != null)
                        {
                            length = baseType.Length;
                        }
                    }

                    foreach (XmlSchemaFacet facet in restriction.Facets)
                    {
                        XmlSchemaLengthFacet lengthFacet = facet as XmlSchemaLengthFacet;
                        if (lengthFacet != null)
                        {
                            Int32.TryParse(lengthFacet.Value, out length);
                            continue;
                        }
                        // also handle minLength, maxLength facets in a limited fashion, ie. either one
                        //  will specify the array length
                        XmlSchemaMinLengthFacet minLengthFacet = facet as XmlSchemaMinLengthFacet;
                        if (minLengthFacet != null)
                        {
                            int minLength;
                            if (Int32.TryParse(minLengthFacet.Value, out minLength))
                            {
                                length = Math.Max(length, minLength);
                            }
                            continue;
                        }
                        XmlSchemaMaxLengthFacet maxLengthFacet = facet as XmlSchemaMaxLengthFacet;
                        if (maxLengthFacet != null)
                        {
                            int maxLength;
                            if (Int32.TryParse(maxLengthFacet.Value, out maxLength))
                            {
                                length = Math.Max(length, maxLength);
                            }
                            continue;
                        }
                    }

                    rules = GetRules(restriction);
                }

                string typeName = simpleType.QualifiedName.ToString();

                // if xs:IDREF, then the attribute type should be DomNode as this is a reference
                Type        valueType   = simpleType.Datatype.ValueType;
                XmlTypeCode xmlTypeCode = simpleType.Datatype.TypeCode;
                if (xmlTypeCode == XmlTypeCode.Idref)
                {
                    if (valueType.IsArray)
                    {
                        valueType = typeof(string[]);
                    }
                    else
                    {
                        valueType = typeof(DomNode);
                    }
                }

                // map xs:integer to xs:int (ATGI schema uses xs:integer, which we don't want to map to System.Decimal)
                if (xmlTypeCode == XmlTypeCode.Integer)
                {
                    if (valueType.IsArray)
                    {
                        valueType = typeof(Int32[]);
                    }
                    else
                    {
                        valueType = typeof(Int32);
                    }
                    xmlTypeCode = XmlTypeCode.Int;
                }
                else if (xmlTypeCode == XmlTypeCode.NonNegativeInteger)
                {
                    if (valueType.IsArray)
                    {
                        valueType = typeof(UInt32[]);
                    }
                    else
                    {
                        valueType = typeof(UInt32);
                    }
                    xmlTypeCode = XmlTypeCode.UnsignedInt;
                }

                // create our extended attribute type
                attributeType = new XmlAttributeType(typeName, valueType, length, xmlTypeCode);

                m_annotations.Add(attributeType, GetAnnotation(simpleType));

                if (rules != null)
                {
                    foreach (AttributeRule rule in rules)
                    {
                        attributeType.AddRule(rule);
                    }
                }

                if (!string.IsNullOrEmpty(typeName))
                {
                    m_attributeTypes.Add(typeName, attributeType);
                }
            }

            return(attributeType);
        }
Exemplo n.º 27
0
 protected virtual void Visit(XmlSchemaMaxLengthFacet facet)
 {
 }