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);
        }
        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);
        }
        internal XSMinLengthFacet(XmlSchemaMinLengthFacet minLengthFacet)
        {
            _facet = minLengthFacet;

            if (_facet.Annotation is XmlSchemaAnnotation annotation)
            {
                _annotation = XMLSchemaSerializer.CreateXSAnnotation(annotation);
                _annotation.BindToContainer(RootContainer, this);
            }
        }
Esempio n. 4
0
        public bool AddMinLengthConstraint(int minLen)
        {
            if (minLen < 0)
            {
                return(false);
            }
            XmlSchemaMinLengthFacet minLenFacet = new XmlSchemaMinLengthFacet();

            minLenFacet.Value = minLen.ToString();
            Common.addFacet(minLenFacet, Common.getElementFromSchema(baseSchema));

            return(true);
        }
Esempio n. 5
0
        public bool AddMinLengthConstraint(string min_length)
        {
            int minLen;

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

            XmlSchemaMinLengthFacet minLenFacet = new XmlSchemaMinLengthFacet();

            minLenFacet.Value = minLen.ToString();
            Common.addFacet(minLenFacet, Common.getElementFromSchema(baseSchema));

            return(true);
        }
Esempio n. 6
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);
        }
    }
Esempio n. 7
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);
        }
Esempio n. 8
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);
        }
Esempio n. 9
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);
        }
Esempio n. 10
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);
        }
Esempio n. 11
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);
        }
Esempio n. 12
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!");
        }
Esempio n. 13
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);
    }
        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);
        }
Esempio n. 15
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;
        }
Esempio n. 16
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);
        }
 protected override void Visit(XmlSchemaMinLengthFacet facet)
 {
     AddLeaf(SimpleTypeStructureNodeType.FacetMinLength, 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);
        }
Esempio n. 19
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);
        }
Esempio n. 20
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;
            }
        }
Esempio n. 21
0
 protected virtual void Visit(XmlSchemaMinLengthFacet facet)
 {
 }