private void WriteXMLForCultures(CultureInfo[] cultures) { StreamWriter writer = File.CreateText("CultureSchema.xml"); XmlSchema schema; XmlSchemaElement element; XmlSchemaComplexType complexType; XmlSchemaSequence sequence; schema = new XmlSchema(); element = new XmlSchemaElement(); schema.Items.Add(element); element.Name = "Table"; complexType = new XmlSchemaComplexType(); element.SchemaType = complexType; sequence = new XmlSchemaSequence(); complexType.Particle = sequence; element = new XmlSchemaElement(); element.Name = "CultureName"; element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); sequence.Items.Add(element); schema.Compile(new ValidationEventHandler(ValidationCallbackOne)); schema.Write(writer); writer.Close(); writer = File.CreateText("CultureData.xml"); XmlTextWriter myXmlTextWriter = new XmlTextWriter(writer); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); for(int j=0; j<cultures.Length; j++) { myXmlTextWriter.WriteStartElement("Table"); myXmlTextWriter.WriteElementString("CultureName", cultures[j].LCID.ToString()); myXmlTextWriter.WriteEndElement(); } myXmlTextWriter.WriteEndElement(); myXmlTextWriter.Flush(); myXmlTextWriter.Close(); }
static void Check(ConformanceCheckContext ctx, ConformanceChecker checker, Hashtable visitedObjects, XmlSchemaObject value) { if (value == null) { return; } if (visitedObjects.Contains(value)) { return; } visitedObjects.Add(value, value); if (value is XmlSchemaImport) { XmlSchemaImport so = (XmlSchemaImport)value; checker.Check(ctx, so); } else if (value is XmlSchemaAll) { XmlSchemaAll so = (XmlSchemaAll)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Items); } else if (value is XmlSchemaAnnotation) { XmlSchemaAnnotation so = (XmlSchemaAnnotation)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Items); } else if (value is XmlSchemaAttribute) { XmlSchemaAttribute so = (XmlSchemaAttribute)value; checker.Check(ctx, so); } else if (value is XmlSchemaAttributeGroup) { XmlSchemaAttributeGroup so = (XmlSchemaAttributeGroup)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); Check(ctx, checker, visitedObjects, so.RedefinedAttributeGroup); } else if (value is XmlSchemaAttributeGroupRef) { XmlSchemaAttributeGroupRef so = (XmlSchemaAttributeGroupRef)value; checker.Check(ctx, so); } else if (value is XmlSchemaChoice) { XmlSchemaChoice so = (XmlSchemaChoice)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Items); } else if (value is XmlSchemaComplexContent) { XmlSchemaComplexContent so = (XmlSchemaComplexContent)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Content); } else if (value is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension so = (XmlSchemaComplexContentExtension)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Particle); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); } else if (value is XmlSchemaComplexContentRestriction) { XmlSchemaComplexContentRestriction so = (XmlSchemaComplexContentRestriction)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Particle); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); } else if (value is XmlSchemaComplexType) { XmlSchemaComplexType so = (XmlSchemaComplexType)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.ContentModel); Check(ctx, checker, visitedObjects, so.Particle); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); Check(ctx, checker, visitedObjects, so.ContentTypeParticle); Check(ctx, checker, visitedObjects, so.AttributeWildcard); } else if (value is XmlSchemaElement) { XmlSchemaElement so = (XmlSchemaElement)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.SchemaType); CheckObjects(ctx, checker, visitedObjects, so.Constraints); } else if (value is XmlSchemaGroup) { XmlSchemaGroup so = (XmlSchemaGroup)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Particle); } else if (value is XmlSchemaGroupRef) { XmlSchemaGroupRef so = (XmlSchemaGroupRef)value; checker.Check(ctx, so); } else if (value is XmlSchemaIdentityConstraint) { XmlSchemaIdentityConstraint so = (XmlSchemaIdentityConstraint)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Fields); Check(ctx, checker, visitedObjects, so.Selector); } else if (value is XmlSchemaKeyref) { XmlSchemaKeyref so = (XmlSchemaKeyref)value; checker.Check(ctx, so); } else if (value is XmlSchemaRedefine) { XmlSchemaRedefine so = (XmlSchemaRedefine)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Items); } else if (value is XmlSchemaSequence) { XmlSchemaSequence so = (XmlSchemaSequence)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Items); } else if (value is XmlSchemaSimpleContent) { XmlSchemaSimpleContent so = (XmlSchemaSimpleContent)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Content); } else if (value is XmlSchemaSimpleContentExtension) { XmlSchemaSimpleContentExtension so = (XmlSchemaSimpleContentExtension)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); } else if (value is XmlSchemaSimpleContentRestriction) { XmlSchemaSimpleContentRestriction so = (XmlSchemaSimpleContentRestriction)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Attributes); Check(ctx, checker, visitedObjects, so.AnyAttribute); CheckObjects(ctx, checker, visitedObjects, so.Facets); } else if (value is XmlSchemaSimpleType) { XmlSchemaSimpleType so = (XmlSchemaSimpleType)value; checker.Check(ctx, so); Check(ctx, checker, visitedObjects, so.Content); } else if (value is XmlSchemaSimpleTypeList) { XmlSchemaSimpleTypeList so = (XmlSchemaSimpleTypeList)value; checker.Check(ctx, so); } else if (value is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction so = (XmlSchemaSimpleTypeRestriction)value; checker.Check(ctx, so); CheckObjects(ctx, checker, visitedObjects, so.Facets); } else if (value is XmlSchemaSimpleTypeUnion) { XmlSchemaSimpleTypeUnion so = (XmlSchemaSimpleTypeUnion)value; checker.Check(ctx, so); } }
private void InitializeChildren(XmlSchemaComplexType complexType, SimplifiedSchemaObject element, bool initializingComplexType) { if (complexType == null) { return; } XmlSchemaComplexContentRestriction restriction = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentRestriction : null; XmlSchemaComplexContentExtension extension = complexType.ContentModel != null ? complexType.ContentModel.Content as XmlSchemaComplexContentExtension : null; XmlSchemaObjectCollection baseAttributes = null; if (restriction != null) { baseAttributes = restriction.Attributes; } else if (extension != null) { baseAttributes = extension.Attributes; } if (baseAttributes != null) { foreach (XmlSchemaObject cObject in baseAttributes) { XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute; if (cAttribute != null) { element.Children.Add( new SimplifiedSchemaObject(element, cAttribute)); } } } foreach (XmlSchemaObject cObject in complexType.Attributes) { XmlSchemaAttribute cAttribute = cObject as XmlSchemaAttribute; if (cAttribute != null) { element.Children.Add( new SimplifiedSchemaObject(element, cAttribute)); } } //if (element.ToString() == "ClinicalDocument/recordTarget/patientRole") // Console.WriteLine("Test"); if (complexType.ContentTypeParticle is XmlSchemaSequence) { XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence; foreach (XmlSchemaObject cObject in sequence.Items) { // Check here if this element's name is the same as it's parent or grand-parents XmlSchemaElement cElement = cObject as XmlSchemaElement; XmlSchemaChoice cChoice = cObject as XmlSchemaChoice; if (cElement != null) { InitializeLevel(element, cElement, initializingComplexType); } else if (cChoice != null) { foreach (XmlSchemaObject cChoiceObject in cChoice.Items) { XmlSchemaElement cChoiceElement = cChoiceObject as XmlSchemaElement; if (cChoiceElement != null) { InitializeLevel(element, cChoiceElement, initializingComplexType); } } } } } }
public static XmlSchemaComplexType GetTypedTableSchema(XmlSchemaSet xs) { XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); dsDB ds = new dsDB(); XmlSchemaAny any1 = new XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); XmlSchemaAny any2 = new XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); XmlSchemaAttribute attribute1 = new XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); XmlSchemaAttribute attribute2 = new XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "MovimentiDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { MemoryStream s1 = new MemoryStream(); MemoryStream s2 = new MemoryStream(); try { XmlSchema schema = null; dsSchema.Write(s1); for (IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
/// <summary> /// Creates a new instance of the <see cref="NAntSchemaGenerator" /> /// class. /// </summary> /// <param name="tasks">Tasks for which a schema should be generated.</param> /// <param name="dataTypes">Data Types for which a schema should be generated.</param> /// <param name="targetNS">The namespace to use. /// <example> http://tempuri.org/nant.xsd </example> /// </param> public NAntSchemaGenerator(Type[] tasks, Type[] dataTypes, string targetNS) { //setup namespace stuff if (targetNS != null) { _nantSchema.TargetNamespace = targetNS; _nantSchema.Namespaces.Add("nant", _nantSchema.TargetNamespace); } // add XSD namespace so that all xsd elements are prefix'd _nantSchema.Namespaces.Add("xs", XmlSchema.Namespace); _nantSchema.ElementFormDefault = XmlSchemaForm.Qualified; // initialize stuff _nantComplexTypes = new HybridDictionary(tasks.Length + dataTypes.Length); XmlSchemaAnnotation schemaAnnotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation schemaDocumentation = new XmlSchemaDocumentation(); string doc = String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SchemaGenerated"), DateTime.Now); schemaDocumentation.Markup = TextToNodeArray(doc); schemaAnnotation.Items.Add(schemaDocumentation); _nantSchema.Items.Add(schemaAnnotation); // create temp list of taskcontainer Complex Types ArrayList taskContainerComplexTypes = new ArrayList(4); XmlSchemaComplexType containerCT = FindOrCreateComplexType(typeof(TaskContainer)); if (containerCT.Particle == null) { // just create empty sequence to which elements will // be added later containerCT.Particle = CreateXsdSequence(0, Decimal.MaxValue); } taskContainerComplexTypes.Add(containerCT); // create temp list of task Complex Types ArrayList dataTypeComplexTypes = new ArrayList(dataTypes.Length); foreach (Type t in dataTypes) { dataTypeComplexTypes.Add(FindOrCreateComplexType(t)); } foreach (Type t in tasks) { XmlSchemaComplexType taskCT = FindOrCreateComplexType(t); // allow any tasks... if (t.IsSubclassOf(typeof(TaskContainer))) { taskContainerComplexTypes.Add(taskCT); } } Compile(); // update the taskcontainerCTs to allow any other task and the // list of tasks generated foreach (XmlSchemaComplexType ct in taskContainerComplexTypes) { XmlSchemaSequence seq = ct.Particle as XmlSchemaSequence; if (seq != null) { seq.Items.Add(CreateTaskListComplexType(tasks).Particle); } else { logger.Error("Unable to fixup complextype with children. Particle is not XmlSchemaSequence"); } } Compile(); // create target ComplexType _targetCT = CreateTaskListComplexType(tasks, dataTypes, false); _targetCT.Name = "Target"; // name attribute _targetCT.Attributes.Add(CreateXsdAttribute("name", true)); // depends attribute _targetCT.Attributes.Add(CreateXsdAttribute("depends", false)); // description attribute _targetCT.Attributes.Add(CreateXsdAttribute("description", false)); // if attribute _targetCT.Attributes.Add(CreateXsdAttribute("if", false)); // unless attribute _targetCT.Attributes.Add(CreateXsdAttribute("unless", false)); _nantSchema.Items.Add(_targetCT); Compile(); // Generate project Element and ComplexType XmlSchemaElement projectElement = new XmlSchemaElement(); projectElement.Name = "project"; XmlSchemaComplexType projectCT = CreateTaskListComplexType(tasks, dataTypes, true); projectElement.SchemaType = projectCT; //name attribute projectCT.Attributes.Add(CreateXsdAttribute("name", true)); //default attribute projectCT.Attributes.Add(CreateXsdAttribute("default", false)); //basedir attribute projectCT.Attributes.Add(CreateXsdAttribute("basedir", false)); _nantSchema.Items.Add(projectElement); Compile(); }
/// <summary> /// Process an IFCXML schema file /// </summary> /// <param name="ifcxmlSchemaFile">the IfcXML schema file info</param> /// <param name="theTree">the IFC Entity tree</param> public static bool ProcessIFCSchema(FileInfo ifcxmlSchemaFile, ref IfcSchemaEntityTree theTree) { string loadedSchema = Path.GetFileNameWithoutExtension(ifcxmlSchemaFile.Name); XmlTextReader reader = new XmlTextReader(ifcxmlSchemaFile.FullName); XmlSchema theSchema = XmlSchema.Read(reader, ValidationCallback); foreach (XmlSchemaObject item in theSchema.Items) { if (item is XmlSchemaComplexType) { XmlSchemaComplexType ct = item as XmlSchemaComplexType; string entityName = ct.Name; if (string.Compare(entityName, 0, "Ifc", 0, 3, ignoreCase: true) != 0) { continue; } string parentName = string.Empty; if (ct.ContentModel == null) { continue; } if (ct.ContentModel.Parent == null) { continue; } string predefTypeEnum = null; if (ct.ContentModel.Parent is XmlSchemaComplexType) { XmlSchemaComplexType parent = ct.ContentModel.Parent as XmlSchemaComplexType; XmlSchemaSimpleContentExtension parentSimpleType = parent.ContentModel.Content as XmlSchemaSimpleContentExtension; XmlSchemaComplexContentExtension parentComplexType = parent.ContentModel.Content as XmlSchemaComplexContentExtension; if (parentSimpleType != null) { parentName = parentSimpleType.BaseTypeName.Name; foreach (XmlSchemaAttribute attr in parentSimpleType.Attributes) { if (attr.Name != null && attr.Name.Equals("PredefinedType", StringComparison.InvariantCultureIgnoreCase)) { predefTypeEnum = attr.SchemaTypeName.Name; } } } if (parentComplexType != null) { parentName = parentComplexType.BaseTypeName.Name; foreach (XmlSchemaAttribute attr in parentComplexType.Attributes) { if (attr.Name != null && attr.Name.Equals("PredefinedType", StringComparison.InvariantCultureIgnoreCase)) { predefTypeEnum = attr.SchemaTypeName.Name; break; } } if (string.IsNullOrEmpty(predefTypeEnum) && parentComplexType.Particle != null) { XmlSchemaSequence seq = parentComplexType.Particle as XmlSchemaSequence; if (seq != null) { foreach (XmlSchemaElement elem in seq.Items) { if (elem.Name != null && elem.Name.Equals("PredefinedType", StringComparison.InvariantCultureIgnoreCase)) { predefTypeEnum = elem.SchemaTypeName.Name; break; } } } } } } theTree.Add(entityName, parentName, predefTypeEnum, isAbstract: ct.IsAbstract); } else if (item is XmlSchemaSimpleType) { XmlSchemaSimpleType st = item as XmlSchemaSimpleType; if (st.Name.StartsWith("Ifc", StringComparison.InvariantCultureIgnoreCase) && st.Name.EndsWith("Enum", StringComparison.InvariantCultureIgnoreCase)) { string enumName = st.Name; XmlSchemaSimpleTypeRestriction enums = st.Content as XmlSchemaSimpleTypeRestriction; if (enums != null) { IList <string> enumValueList = new List <string>(); foreach (XmlSchemaEnumerationFacet enumFacet in enums.Facets) { if (theTree.PredefinedTypeEnumDict.ContainsKey(enumName)) { theTree.PredefinedTypeEnumDict[enumName].Add(enumFacet.Value.ToUpper()); } else { enumValueList.Add(enumFacet.Value.ToUpper()); } } if (enumValueList.Count > 0) { theTree.PredefinedTypeEnumDict.Add(enumName, enumValueList); } } } } } return(true); }
void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) { ClassMap cmap = (ClassMap)xmlMembersMapping.ObjectMap; if (xmlMembersMapping.HasWrapperElement && exportEnclosingType) { XmlSchema schema = GetSchema(xmlMembersMapping.Namespace); XmlSchemaComplexType stype = new XmlSchemaComplexType(); XmlSchemaSequence particle; XmlSchemaAnyAttribute anyAttribute; ExportMembersMapSchema(schema, cmap, null, stype.Attributes, out particle, out anyAttribute); stype.Particle = particle; stype.AnyAttribute = anyAttribute; if (encodedFormat) { stype.Name = xmlMembersMapping.ElementName; schema.Items.Add(stype); } else { XmlSchemaElement selem = new XmlSchemaElement(); selem.Name = xmlMembersMapping.ElementName; selem.SchemaType = stype; schema.Items.Add(selem); } } else { ICollection members = cmap.ElementMembers; if (members != null) { foreach (XmlTypeMapMemberElement member in members) { if (member is XmlTypeMapMemberAnyElement && member.TypeData.IsListType) { XmlSchema mschema = GetSchema(xmlMembersMapping.Namespace); XmlSchemaParticle par = GetSchemaArrayElement(mschema, member.ElementInfo); if (par is XmlSchemaAny) { XmlSchemaComplexType ct = FindComplexType(mschema.Items, "any"); if (ct != null) { continue; } ct = new XmlSchemaComplexType(); ct.Name = "any"; ct.IsMixed = true; XmlSchemaSequence seq = new XmlSchemaSequence(); ct.Particle = seq; seq.Items.Add(par); mschema.Items.Add(ct); continue; } } XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo)member.ElementInfo [0]; XmlSchema schema; if (encodedFormat) { schema = GetSchema(xmlMembersMapping.Namespace); ImportNamespace(schema, XmlSerializer.EncodingNamespace); } else { schema = GetSchema(einfo.Namespace); } XmlSchemaElement exe = FindElement(schema.Items, einfo.ElementName); XmlSchemaElement elem; XmlSchemaObjectContainer container = null; // In encoded format, the schema elements are not needed if (!encodedFormat) { container = new XmlSchemaObjectContainer(schema); } Type memType = member.GetType(); if (member is XmlTypeMapMemberFlatList) { throw new InvalidOperationException("Unwrapped arrays not supported as parameters"); } else if (memType == typeof(XmlTypeMapMemberElement)) { elem = (XmlSchemaElement)GetSchemaElement(schema, einfo, member.DefaultValue, false, container); } else { elem = (XmlSchemaElement)GetSchemaElement(schema, einfo, false, container); } if (exe != null) { if (exe.SchemaTypeName.Equals(elem.SchemaTypeName)) { schema.Items.Remove(elem); } else { string s = "The XML element named '" + einfo.ElementName + "' "; s += "from namespace '" + schema.TargetNamespace + "' references distinct types " + elem.SchemaTypeName.Name + " and " + exe.SchemaTypeName.Name + ". "; s += "Use XML attributes to specify another XML name or namespace for the element or types."; throw new InvalidOperationException(s); } } } } } CompileSchemas(); }
public static XmlSchemaComplexType GetTypedTableSchema(XmlSchemaSet xs) { XmlSchemaComplexType xmlSchemaComplexType; XmlSchema xmlSchema; XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); guard_profiles_dbDataSet ds = new guard_profiles_dbDataSet(); XmlSchemaAny any1 = new XmlSchemaAny() { Namespace = "http://www.w3.org/2001/XMLSchema", MinOccurs = new decimal(0), MaxOccurs = new decimal(-1, -1, -1, false, 0), ProcessContents = XmlSchemaContentProcessing.Lax }; sequence.Items.Add(any1); XmlSchemaAny any2 = new XmlSchemaAny() { Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1", MinOccurs = new decimal(1), ProcessContents = XmlSchemaContentProcessing.Lax }; sequence.Items.Add(any2); XmlSchemaAttribute attribute1 = new XmlSchemaAttribute() { Name = "namespace", FixedValue = ds.Namespace }; type.Attributes.Add(attribute1); XmlSchemaAttribute attribute2 = new XmlSchemaAttribute() { Name = "tableTypeName", FixedValue = "Tbl_sg_profilesDataTable" }; type.Attributes.Add(attribute2); type.Particle = sequence; XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { MemoryStream s1 = new MemoryStream(); MemoryStream s2 = new MemoryStream(); try { XmlSchema schema = null; dsSchema.Write(s1); IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); while (schemas.MoveNext()) { schema = (XmlSchema)schemas.Current; s2.SetLength((long)0); schema.Write(s2); if (s1.Length != s2.Length) { continue; } s1.Position = (long)0; s2.Position = (long)0; while (s1.Position != s1.Length && s1.ReadByte() == s2.ReadByte()) { } if (s1.Position != s1.Length) { continue; } xmlSchemaComplexType = type; return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); } finally { if (s1 != null) { s1.Close(); } if (s2 != null) { s2.Close(); } } return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); }
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> }
private void WalkParticle(XmlSchemaParticle particle, DomNodeType nodeType) { XmlSchemaElement element = particle as XmlSchemaElement; if (element != null) { XmlSchemaSimpleType simpleType = element.ElementSchemaType as XmlSchemaSimpleType; if (simpleType != null && element.MaxOccurs == 1) { XmlAttributeType attributeType = GetAttributeType(simpleType); string fieldName = GetFieldName(element.QualifiedName); XmlAttributeInfo attributeInfo = new XmlAttributeInfo(fieldName, attributeType); nodeType.Define(attributeInfo); m_annotations.Add(attributeInfo, GetAnnotation(element)); attributeInfo.IsElement = true; if (element.DefaultValue != null) { if (element.FixedValue != null) { throw new InvalidOperationException(string.Format("Schema element {0} cannot have both a default value and a fixed value", element.QualifiedName)); } attributeInfo.DefaultValue = attributeType.Convert(element.DefaultValue); } else if (element.FixedValue != null) { attributeInfo.DefaultValue = attributeType.Convert(element.FixedValue); } } else { DomNodeType childNodeType = null; if (simpleType != null) { childNodeType = WrapSimpleType(simpleType); // Add the value attribute XmlAttributeType valueAttributeType = GetAttributeType(simpleType); var valueAttributeInfo = new XmlAttributeInfo(string.Empty, valueAttributeType); childNodeType.Define(valueAttributeInfo); } else { XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType; if (complexType != null) { childNodeType = GetNodeType(complexType, element); } } if (childNodeType != null) { int minOccurs; int maxOccurs; // If <xs:choice> is within a <xs:sequence>, choose the most relaxed constraints. if (particle.Parent is XmlSchemaChoice) { var parent = (XmlSchemaChoice)particle.Parent; minOccurs = (int)Math.Min(Math.Min(element.MinOccurs, parent.MinOccurs), Int32.MaxValue); maxOccurs = (int)Math.Min(Math.Max(element.MaxOccurs, parent.MaxOccurs), Int32.MaxValue); } else if (particle.Parent is XmlSchemaSequence) { var parent = (XmlSchemaSequence)particle.Parent; minOccurs = (int)Math.Min(Math.Min(element.MinOccurs, parent.MinOccurs), Int32.MaxValue); maxOccurs = (int)Math.Min(Math.Max(element.MaxOccurs, parent.MaxOccurs), Int32.MaxValue); } else { minOccurs = (int)Math.Min(element.MinOccurs, Int32.MaxValue); maxOccurs = (int)Math.Min(element.MaxOccurs, Int32.MaxValue); } ChildInfo childInfo = new ChildInfo(GetFieldName(element.QualifiedName), childNodeType, maxOccurs > 1); if (minOccurs > 0 || maxOccurs < Int32.MaxValue) { childInfo.AddRule(new ChildCountRule(minOccurs, maxOccurs)); } // Check for substitution groups if (!element.RefName.IsEmpty) { m_refElements.Add(childInfo, element.RefName); } nodeType.Define(childInfo); m_annotations.Add(childInfo, GetAnnotation(element)); } } } else { // if sequence, continue collecting elements XmlSchemaSequence sequence = particle as XmlSchemaSequence; if (sequence != null) { foreach (XmlSchemaParticle subParticle in sequence.Items) { WalkParticle(subParticle, nodeType); } } else { XmlSchemaChoice choice = particle as XmlSchemaChoice; if (choice != null) { // for now, treat choice as if it were a sequence foreach (XmlSchemaParticle subParticle in choice.Items) { WalkParticle(subParticle, nodeType); } } } } }
public static XmlSchemaComplexType GetTypedDataSetSchema(XmlSchemaSet xs) { XmlSchemaComplexType xmlSchemaComplexType; XmlSchema xmlSchema; guard_profiles_dbDataSet ds = new guard_profiles_dbDataSet(); XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny() { Namespace = ds.Namespace }; sequence.Items.Add(any); type.Particle = sequence; XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { MemoryStream s1 = new MemoryStream(); MemoryStream s2 = new MemoryStream(); try { XmlSchema schema = null; dsSchema.Write(s1); IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); while (schemas.MoveNext()) { schema = (XmlSchema)schemas.Current; s2.SetLength((long)0); schema.Write(s2); if (s1.Length != s2.Length) { continue; } s1.Position = (long)0; s2.Position = (long)0; while (s1.Position != s1.Length && s1.ReadByte() == s2.ReadByte()) { } if (s1.Position != s1.Length) { continue; } xmlSchemaComplexType = type; return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); } finally { if (s1 != null) { s1.Close(); } if (s2 != null) { s2.Close(); } } return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); }
private static XmlSchemaElement CaseSchema() { XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaAll allSchema = new XmlSchemaAll(); type.Particle = allSchema; //When XmlSchemaComplexType subType = new XmlSchemaComplexType(); XmlSchemaAny any = new XmlSchemaAny(); any.MinOccurs = 1; any.MaxOccursString = "unbounded"; any.ProcessContents = XmlSchemaContentProcessing.Strict; any.Namespace = "##local"; XmlSchemaSequence sequence = new XmlSchemaSequence(); subType.Particle = sequence; sequence.Items.Add(any); XmlSchemaElement subElement = new XmlSchemaElement(); subElement.Name = "when"; subElement.SchemaType = subType; allSchema.Items.Add(subElement); //Then subType = new XmlSchemaComplexType(); any = new XmlSchemaAny(); any.MinOccurs = 1; any.MaxOccursString = "unbounded"; any.ProcessContents = XmlSchemaContentProcessing.Strict; any.Namespace = "##local"; sequence = new XmlSchemaSequence(); subType.Particle = sequence; sequence.Items.Add(any); subElement = new XmlSchemaElement(); subElement.Name = "then"; subElement.SchemaType = subType; allSchema.Items.Add(subElement); //Else subType = new XmlSchemaComplexType(); any = new XmlSchemaAny(); any.MinOccurs = 1; any.MaxOccurs = 1; any.ProcessContents = XmlSchemaContentProcessing.Strict; any.Namespace = "##local"; sequence = new XmlSchemaSequence(); subType.Particle = sequence; sequence.Items.Add(any); subElement = new XmlSchemaElement(); subElement.Name = "else"; subElement.SchemaType = subType; allSchema.Items.Add(subElement); XmlSchemaAttribute attrib = new XmlSchemaAttribute(); attrib.Name = "expressionLanguage"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); type.Attributes.Add(attrib); attrib = new XmlSchemaAttribute(); attrib.Name = "failMessage"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); type.Attributes.Add(attrib); XmlSchemaElement element = new XmlSchemaElement(); element.Name = "case"; element.SchemaType = type; return(element); }
QName ExportParameters(MessageBodyDescription msgbody, string name, string ns) { XmlSchema xs = GetSchema(ns); //FIXME: Extract to a HasElement method ? foreach (XmlSchemaObject o in xs.Items) { XmlSchemaElement e = o as XmlSchemaElement; if (e == null) { continue; } if (e.Name == name) { throw new InvalidOperationException(String.Format( "Message element named '{0}:{1}' has already been exported.", ns, name)); } } //Create the element for "parameters" XmlSchemaElement schema_element = new XmlSchemaElement(); schema_element.Name = name; XmlSchemaComplexType complex_type = new XmlSchemaComplexType(); //Generate Sequence representing the message/parameters //FIXME: MessageContractAttribute XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaElement element = null; if (msgbody.ReturnValue == null) { //parameters foreach (MessagePartDescription part in msgbody.Parts) { if (part.Type == null) { //FIXME: Eg. when WsdlImporter is used to import a wsdl throw new NotImplementedException(); } element = GetSchemaElementForPart(part, xs); sequence.Items.Add(element); } } else { //ReturnValue if (msgbody.ReturnValue.Type != typeof(void)) { element = GetSchemaElementForPart(msgbody.ReturnValue, xs); sequence.Items.Add(element); } } complex_type.Particle = sequence; schema_element.SchemaType = complex_type; xs.Items.Add(schema_element); GeneratedXmlSchemas.Reprocess(xs); return(new QName(schema_element.Name, xs.TargetNamespace)); }
internal static XmlSchema BuildSchema(DiscoveryVersion version) { var schema = new XmlSchema() { TargetNamespace = version.Namespace }; var anyAttr = new XmlSchemaAnyAttribute() { Namespace = "##other", ProcessContents = XmlSchemaContentProcessing.Lax }; var probePart = new XmlSchemaSequence(); probePart.Items.Add(new XmlSchemaElement() { RefName = new XmlQualifiedName("Types", version.Namespace), MinOccurs = 0 }); probePart.Items.Add(new XmlSchemaElement() { RefName = new XmlQualifiedName("Scopes", version.Namespace), MinOccurs = 0 }); probePart.Items.Add(new XmlSchemaElement() { RefName = new XmlQualifiedName("XAddrs", version.Namespace), MinOccurs = 0 }); probePart.Items.Add(new XmlSchemaElement() { RefName = new XmlQualifiedName("MetadataVersion", version.Namespace), MinOccurs = 0 }); probePart.Items.Add(new XmlSchemaAny() { MinOccurs = 0, MaxOccursString = "unbounded", Namespace = "##other", ProcessContents = XmlSchemaContentProcessing.Lax }); var ct = new XmlSchemaComplexType() { Name = "ProbeMatchType", Particle = probePart, AnyAttribute = anyAttr }; schema.Items.Add(ct); schema.Items.Add(new XmlSchemaSimpleType() { Name = "QNameListType", Content = new XmlSchemaSimpleTypeList() { ItemTypeName = new XmlQualifiedName("QName", XmlSchema.Namespace) } }); var scr = new XmlSchemaSimpleContentRestriction() { BaseTypeName = new XmlQualifiedName("UriListType", version.Namespace), AnyAttribute = anyAttr }; scr.Attributes.Add(new XmlSchemaAttribute() { Name = "matchBy", SchemaTypeName = new XmlQualifiedName("anyURI", XmlSchema.Namespace) }); schema.Items.Add(new XmlSchemaComplexType() { Name = "ScopesType", ContentModel = new XmlSchemaSimpleContent() { Content = scr } }); schema.Items.Add(new XmlSchemaSimpleType() { Name = "UriListType", Content = new XmlSchemaSimpleTypeList() { ItemTypeName = new XmlQualifiedName("anyURI", XmlSchema.Namespace) } }); schema.Items.Add(new XmlSchemaElement() { Name = "Types", SchemaTypeName = new XmlQualifiedName("QNameListType", version.Namespace) }); schema.Items.Add(new XmlSchemaElement() { Name = "Scopes", SchemaTypeName = new XmlQualifiedName("ScopesType", version.Namespace) }); schema.Items.Add(new XmlSchemaElement() { Name = "XAddrs", SchemaTypeName = new XmlQualifiedName("UriListType", version.Namespace) }); schema.Items.Add(new XmlSchemaElement() { Name = "MetadataVersion", SchemaTypeName = new XmlQualifiedName("unisgnedInt", XmlSchema.Namespace) }); return(schema); }
private XmlQualifiedName AddComplexTypeContent(XmlSchemaComplexType schemaType, string schemaNamespace, TypeDefinition typeDefinition, IDictionary <XmlQualifiedName, XmlSchemaType> referencedTypes) { var contentParticle = new XmlSchemaSequence(); var propertyDefinitions = GetDescriptionProperties(typeDefinition).ToList(); foreach (var propertyDefinition in propertyDefinitions) { if (propertyDefinition.MergeContent && propertyDefinitions.Count > 1 && propertyDefinition.ArrayItemDefinition == null) { throw new Exception($"Property {propertyDefinition} of type {typeDefinition} cannot be merged, because there are more than 1 properties present."); } var contentElement = CreateContentElement(propertyDefinition, schemaNamespace, referencedTypes); if (!propertyDefinition.MergeContent || propertyDefinition.ArrayItemDefinition != null) { contentParticle.Items.Add(contentElement); continue; } if (!contentElement.SchemaTypeName.IsEmpty) { return(contentElement.SchemaTypeName); } var particle = ((XmlSchemaComplexType)contentElement.SchemaType)?.Particle; if (particle != null) { schemaType.Particle = particle; } var content = ((XmlSchemaComplexType)contentElement.SchemaType)?.ContentModel; if (content != null) { schemaType.ContentModel = content; } return(null); } if (typeDefinition.Type.GetTypeInfo().BaseType == typeof(XRoadSerializable)) { schemaType.Particle = contentParticle; } else { var extension = new XmlSchemaComplexContentExtension { BaseTypeName = GetSchemaTypeName(typeDefinition.Type.GetTypeInfo().BaseType, schemaNamespace), Particle = contentParticle }; if (!referencedTypes.ContainsKey(extension.BaseTypeName)) { referencedTypes.Add(extension.BaseTypeName, null); } schemaType.ContentModel = new XmlSchemaComplexContent { Content = extension }; } return(null); }
public static void Main() { ServiceDescription myServiceDescription = new ServiceDescription(); myServiceDescription.Name = "StockQuote"; myServiceDescription.TargetNamespace = "http://www.contoso.com/stockquote.wsdl"; // Generate the 'Types' element. XmlSchema myXmlSchema = new XmlSchema(); myXmlSchema.AttributeFormDefault = XmlSchemaForm.Qualified; myXmlSchema.ElementFormDefault = XmlSchemaForm.Qualified; myXmlSchema.TargetNamespace = "http://www.contoso.com/stockquote.wsdl"; //XmlSchemaElement myXmlSchemaElement; XmlSchemaComplexType myXmlSchemaComplexType = new XmlSchemaComplexType(); myXmlSchemaComplexType.Name = "GetTradePriceInputType"; XmlSchemaSequence myXmlSchemaSequence = new XmlSchemaSequence(); myXmlSchemaSequence.Items.Add(CreateComplexTypeXmlElement("1", "1", "tickerSymbol", true, new XmlQualifiedName("s:string"))); myXmlSchemaSequence.Items.Add(CreateComplexTypeXmlElement("1", "1", "time", true, new XmlQualifiedName("s:string"))); myXmlSchemaComplexType.Particle = myXmlSchemaSequence; myXmlSchema.Items.Add(myXmlSchemaComplexType); myXmlSchemaComplexType = new XmlSchemaComplexType(); myXmlSchemaComplexType.Name = "GetTradePriceOutputType"; myXmlSchemaSequence = new XmlSchemaSequence(); myXmlSchemaSequence.Items.Add(CreateComplexTypeXmlElement("1", "1", "result", true, new XmlQualifiedName("s:string"))); myXmlSchemaComplexType.Particle = myXmlSchemaSequence; myXmlSchema.Items.Add(myXmlSchemaComplexType); myXmlSchemaComplexType = new XmlSchemaComplexType(); myXmlSchemaComplexType.Name = "GetTradePriceStringFaultType"; myXmlSchemaSequence = new XmlSchemaSequence(); myXmlSchemaSequence.Items.Add(CreateComplexTypeXmlElement("1", "1", "error", true, new XmlQualifiedName("s:string"))); myXmlSchemaComplexType.Particle = myXmlSchemaSequence; myXmlSchema.Items.Add(myXmlSchemaComplexType); myXmlSchemaComplexType = new XmlSchemaComplexType(); myXmlSchemaComplexType.Name = "GetTradePriceStringIntType"; myXmlSchemaSequence = new XmlSchemaSequence(); myXmlSchemaSequence.Items.Add(CreateComplexTypeXmlElement("1", "1", "error", true, new XmlQualifiedName("s:int"))); myXmlSchemaComplexType.Particle = myXmlSchemaSequence; myXmlSchema.Items.Add(myXmlSchemaComplexType); myXmlSchema.Items.Add(CreateOtherXmlElement("GetTradePriceSoapIn", new XmlQualifiedName("s0:GetTradePriceInputType"))); myXmlSchema.Items.Add(CreateOtherXmlElement("GetTradePriceSoapOut", new XmlQualifiedName("s0:GetTradePriceOutputType"))); myXmlSchema.Items.Add(CreateOtherXmlElement("GetTradePriceSoapStringFault", new XmlQualifiedName("s0:GetTradePriceStringFaultType"))); myXmlSchema.Items.Add(CreateOtherXmlElement("GetTradePriceSoapIntFault", new XmlQualifiedName("s0:GetTradePriceIntFaultType"))); myServiceDescription.Types.Schemas.Add(myXmlSchema); // Generate the 'Message' element. MessageCollection myMessageCollection = myServiceDescription.Messages; myMessageCollection.Add(CreateMessage("GetTradePriceInput", "parameters", "GetTradePriceSoapIn", myServiceDescription.TargetNamespace)); myMessageCollection.Add(CreateMessage("GetTradePriceOutput", "parameters", "GetTradePriceSoapOut", myServiceDescription.TargetNamespace)); myMessageCollection.Add(CreateMessage("GetTradePriceStringFault", "parameters", "GetTradePriceStringSoapFault", myServiceDescription.TargetNamespace)); myMessageCollection.Add(CreateMessage("GetTradePriceIntFault", "parameters", "GetTradePriceIntSoapFault", myServiceDescription.TargetNamespace)); // Generate the 'Port Type' element. PortTypeCollection myPortTypeCollection = myServiceDescription.PortTypes; PortType myPortType = new PortType(); myPortType.Name = "StockQuotePortType"; OperationCollection myOperationCollection = myPortType.Operations; Operation myOperation = new Operation(); myOperation.Name = "GetTradePrice"; OperationMessage myOperationMessage; OperationMessageCollection myOperationMessageCollection = myOperation.Messages; myOperationMessage = (OperationMessage) new OperationInput(); myOperationMessage.Message = new XmlQualifiedName("s0:GetTradePriceInput"); myOperationMessageCollection.Add(myOperationMessage); myOperationMessage = (OperationMessage) new OperationOutput(); myOperationMessage.Message = new XmlQualifiedName("s0:GetTradePriceOutput"); myOperationMessageCollection.Add(myOperationMessage); OperationFault myOperationFault = new OperationFault(); myOperationFault.Name = "ErrorString"; myOperationFault.Message = new XmlQualifiedName("s0:GetTradePriceStringFault"); myOperation.Faults.Add(myOperationFault); myOperationFault = new OperationFault(); myOperationFault.Name = "ErrorInt"; myOperationFault.Message = new XmlQualifiedName("s0:GetTradePriceIntFault"); myOperation.Faults.Add(myOperationFault); myOperationCollection.Add(myOperation); myPortTypeCollection.Add(myPortType); // Generate the 'Binding' element. ServiceDescriptionFormatExtensionCollection myExtensions; BindingCollection myBindingCollection = myServiceDescription.Bindings; Binding myBinding = new Binding(); myBinding.Name = "StockQuoteSoapBinding"; myBinding.Type = new XmlQualifiedName("s0:StockQuotePortType"); myExtensions = myBinding.Extensions; SoapBinding mySoapBinding = new SoapBinding(); mySoapBinding.Style = SoapBindingStyle.Document; mySoapBinding.Transport = "http://schemas.xmlsoap.org/soap/http"; myExtensions.Add(mySoapBinding); OperationBindingCollection myOperationBindingCollection = myBinding.Operations; OperationBinding myOperationBinding = new OperationBinding(); myExtensions = myOperationBinding.Extensions; SoapOperationBinding mySoapBindingOperation = new SoapOperationBinding(); mySoapBindingOperation.SoapAction = "http://www.contoso.com/GetTradePrice"; myExtensions.Add(mySoapBindingOperation); myOperationBinding.Name = "GetTradePrice"; myOperationBinding.Input = new InputBinding(); myExtensions = myOperationBinding.Input.Extensions; SoapBodyBinding mySoapBodyBinding = new SoapBodyBinding(); mySoapBodyBinding.Use = SoapBindingUse.Literal; mySoapBodyBinding.Namespace = "http://www.contoso.com/stockquote"; myExtensions.Add(mySoapBodyBinding); myOperationBinding.Output = new OutputBinding(); myExtensions = myOperationBinding.Output.Extensions; mySoapBodyBinding = new SoapBodyBinding(); mySoapBodyBinding.Use = SoapBindingUse.Literal; mySoapBodyBinding.Namespace = "http://www.contoso.com/stockquote"; myExtensions.Add(mySoapBodyBinding); // <Snippet1> // <Snippet2> // <Snippet3> FaultBindingCollection myFaultBindingCollection = myOperationBinding.Faults; FaultBinding myFaultBinding = new FaultBinding(); myFaultBinding.Name = "ErrorString"; // Associate SOAP fault binding to the fault binding of the operation. myExtensions = myFaultBinding.Extensions; SoapFaultBinding mySoapFaultBinding = new SoapFaultBinding(); mySoapFaultBinding.Use = SoapBindingUse.Literal; mySoapFaultBinding.Namespace = "http://www.contoso.com/stockquote"; myExtensions.Add(mySoapFaultBinding); myFaultBindingCollection.Add(myFaultBinding); // </Snippet3> // </Snippet2> // </Snippet1> myFaultBinding = new FaultBinding(); myFaultBinding.Name = "ErrorInt"; // Associate SOAP fault binding to the fault binding of the operation. myExtensions = myFaultBinding.Extensions; mySoapFaultBinding = new SoapFaultBinding(); mySoapFaultBinding.Use = SoapBindingUse.Literal; mySoapFaultBinding.Namespace = "http://www.contoso.com/stockquote"; myExtensions.Add(mySoapFaultBinding); myFaultBindingCollection.Add(myFaultBinding); myOperationBindingCollection.Add(myOperationBinding); myBindingCollection.Add(myBinding); // Generate the 'Service' element. ServiceCollection myServiceCollection = myServiceDescription.Services; // <Snippet4> Service myService = new Service(); // Add a simple documentation for the service to ease the readability of the generated WSDL file. myService.Documentation = "A Simple Stock Quote Service"; myService.Name = "StockQuoteService"; PortCollection myPortCollection = myService.Ports; Port myPort = new Port(); myPort.Name = "StockQuotePort"; myPort.Binding = new XmlQualifiedName("s0:StockQuoteSoapBinding"); myExtensions = myPort.Extensions; SoapAddressBinding mySoapAddressBinding = new SoapAddressBinding(); mySoapAddressBinding.Location = "http://www.contoso.com/stockquote"; myExtensions.Add(mySoapAddressBinding); myPortCollection.Add(myPort); // </Snippet4> myServiceCollection.Add(myService); // Display the WSDL generated to the console. myServiceDescription.Write(Console.Out); }
private List <string> OutputElements(XmlSchemaParticle particle) { List <string> outList = new List <string>(); XmlSchemaSequence sequence = particle as XmlSchemaSequence; XmlSchemaChoice choice = particle as XmlSchemaChoice; XmlSchemaAll all = particle as XmlSchemaAll; if (sequence != null) { Console.Out.WriteLine(" Sequence"); for (int i = 0; i < sequence.Items.Count; i++) { XmlSchemaElement childElement = sequence.Items[i] as XmlSchemaElement; XmlSchemaSequence innerSequence = sequence.Items[i] as XmlSchemaSequence; XmlSchemaChoice innerChoice = sequence.Items[i] as XmlSchemaChoice; XmlSchemaAll innerAll = sequence.Items[i] as XmlSchemaAll; if (childElement != null) { Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name); outList.Add(childElement.Name); } else { OutputElements(sequence.Items[i] as XmlSchemaParticle); } } return(outList); } else if (choice != null) // хз - надо ли?! { Console.Out.WriteLine(" Choice"); for (int i = 0; i < choice.Items.Count; i++) { XmlSchemaElement childElement = choice.Items[i] as XmlSchemaElement; XmlSchemaSequence innerSequence = choice.Items[i] as XmlSchemaSequence; XmlSchemaChoice innerChoice = choice.Items[i] as XmlSchemaChoice; XmlSchemaAll innerAll = choice.Items[i] as XmlSchemaAll; if (childElement != null) { Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name); } else { OutputElements(choice.Items[i] as XmlSchemaParticle); } } Console.Out.WriteLine(); } else if (all != null) // хз - надо ли?! { Console.Out.WriteLine(" All"); for (int i = 0; i < all.Items.Count; i++) { XmlSchemaElement childElement = all.Items[i] as XmlSchemaElement; XmlSchemaSequence innerSequence = all.Items[i] as XmlSchemaSequence; XmlSchemaChoice innerChoice = all.Items[i] as XmlSchemaChoice; XmlSchemaAll innerAll = all.Items[i] as XmlSchemaAll; if (childElement != null) { Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name); } else { OutputElements(all.Items[i] as XmlSchemaParticle); } } Console.Out.WriteLine(); } return(null); }
void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string ns, bool hasSimpleContent) { XmlSchemaGroupBase seq = new XmlSchemaSequence(); TypeMapping textMapping = null; for (int i = 0; i < members.Length; i++) { MemberMapping member = members[i]; if (member.Ignore) { continue; } if (member.Text != null) { if (textMapping != null) { throw new InvalidOperationException(Res.GetString(Res.XmlIllegalMultipleText, name)); } textMapping = member.Text.Mapping; } if (member.Elements.Length > 0) { bool repeats = member.TypeDesc.IsArrayLike && !(member.Elements.Length == 1 && member.Elements[0].Mapping is ArrayMapping); bool valueTypeOptional = member.CheckSpecified || member.CheckShouldPersist; ExportElementAccessors(seq, member.Elements, repeats, valueTypeOptional, ns); } } if (seq.Items.Count > 0) { if (type.ContentModel != null) { if (type.ContentModel.Content is XmlSchemaComplexContentRestriction) { ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Particle = seq; } else if (type.ContentModel.Content is XmlSchemaComplexContentExtension) { ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq; } else { throw new InvalidOperationException(Res.GetString(Res.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); } } else { type.Particle = seq; } } if (textMapping != null) { if (hasSimpleContent) { if (textMapping is PrimitiveMapping && seq.Items.Count == 0) { PrimitiveMapping pm = (PrimitiveMapping)textMapping; if (pm.IsList) { type.IsMixed = true; } else { // Create simpleContent XmlSchemaSimpleContent model = new XmlSchemaSimpleContent(); XmlSchemaSimpleContentExtension ex = new XmlSchemaSimpleContentExtension(); model.Content = ex; type.ContentModel = model; ex.BaseTypeName = ExportPrimitiveMapping(pm, ns); } } } else { type.IsMixed = true; } } for (int i = 0; i < members.Length; i++) { ExportAttributeAccessor(type, members[i].Attribute, ns); } }
void ExportMembersMapSchema(XmlSchema schema, ClassMap map, XmlTypeMapping baseMap, XmlSchemaObjectCollection outAttributes, out XmlSchemaSequence particle, out XmlSchemaAnyAttribute anyAttribute) { particle = null; XmlSchemaSequence seq = new XmlSchemaSequence(); ICollection members = map.ElementMembers; if (members != null && !map.HasSimpleContent) { foreach (XmlTypeMapMemberElement member in members) { if (baseMap != null && DefinedInBaseMap(baseMap, member)) { continue; } Type memType = member.GetType(); if (memType == typeof(XmlTypeMapMemberFlatList)) { XmlSchemaParticle part = GetSchemaArrayElement(schema, member.ElementInfo); if (part != null) { seq.Items.Add(part); } } else if (memType == typeof(XmlTypeMapMemberAnyElement)) { seq.Items.Add(GetSchemaArrayElement(schema, member.ElementInfo)); } else if (memType == typeof(XmlTypeMapMemberElement)) { GetSchemaElement(schema, (XmlTypeMapElementInfo)member.ElementInfo [0], member.DefaultValue, true, new XmlSchemaObjectContainer(seq)); } else { GetSchemaElement(schema, (XmlTypeMapElementInfo)member.ElementInfo[0], true, new XmlSchemaObjectContainer(seq)); } } } if (seq.Items.Count > 0) { particle = seq; } // Write attributes ICollection attributes = map.AttributeMembers; if (attributes != null) { foreach (XmlTypeMapMemberAttribute attr in attributes) { if (baseMap != null && DefinedInBaseMap(baseMap, attr)) { continue; } outAttributes.Add(GetSchemaAttribute(schema, attr, true)); } } XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember; if (anyAttrMember != null) { anyAttribute = new XmlSchemaAnyAttribute(); } else { anyAttribute = null; } }
//[Variation(Desc = "TFS_470021 Unexpected local particle qualified name when chameleon schema is added to set")] public void TFS_470021() { string cham = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='a0' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:complexType name='ctseq1_a'> <xs:sequence> <xs:element name='foo'/> </xs:sequence> <xs:attribute name='abt0' type='xs:string'/> </xs:complexType> <xs:element name='gect1_a' type ='ctseq1_a'/> </xs:schema>"; string main = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='m0' targetNamespace='http://tempuri.org/chameleon1' elementFormDefault='qualified' xmlns='http://tempuri.org/chameleon1' xmlns:mstns='http://tempuri.org/chameleon1' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:include schemaLocation='cham.xsd' /> <xs:element name='root'> <xs:complexType> <xs:sequence maxOccurs='unbounded'> <xs:any namespace='##any' processContents='lax'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; using (var tempDirectory = new TempDirectory()) { string chamPath = Path.Combine(tempDirectory.Path, "cham.xsd"); string tempDirectoryPath = tempDirectory.Path[tempDirectory.Path.Length - 1] == Path.DirectorySeparatorChar ? tempDirectory.Path : tempDirectory.Path + Path.DirectorySeparatorChar; using (XmlWriter w = XmlWriter.Create(chamPath)) { using (XmlReader r = XmlReader.Create(new StringReader(cham))) w.WriteNode(r, true); } XmlSchemaSet ss = new XmlSchemaSet(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, XmlReader.Create(new StringReader(cham))); // TempDirectory path must end with a DirectorySeratorChar, otherwise it will throw in the Xml validation. var settings = new XmlReaderSettings() { XmlResolver = new XmlUrlResolver() }; ss.Add(null, XmlReader.Create(new StringReader(main), settings, tempDirectoryPath)); ss.Compile(); Assert.Equal(2, ss.Count); foreach (XmlSchemaElement e in ss.GlobalElements.Values) { _output.WriteLine(e.QualifiedName.ToString()); XmlSchemaComplexType type = e.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence seq = type.ContentTypeParticle as XmlSchemaSequence; foreach (XmlSchemaObject child in seq.Items) { if (child is XmlSchemaElement) { _output.WriteLine("\t" + (child as XmlSchemaElement).QualifiedName); } } } Assert.Equal(0, warningCount); Assert.Equal(0, errorCount); } }
XmlQualifiedName ExportArraySchema(XmlTypeMapping map, string defaultNamespace) { ListMap lmap = (ListMap)map.ObjectMap; if (encodedFormat) { string name, ns, schemaNs; lmap.GetArrayType(-1, out name, out ns); if (ns == XmlSchema.Namespace) { schemaNs = defaultNamespace; } else { schemaNs = ns; } if (IsMapExported(map)) { return(new XmlQualifiedName(lmap.GetSchemaArrayName(), schemaNs)); } SetMapExported(map); XmlSchema schema = GetSchema(schemaNs); XmlSchemaComplexType stype = new XmlSchemaComplexType(); stype.Name = lmap.GetSchemaArrayName(); schema.Items.Add(stype); XmlSchemaComplexContent content = new XmlSchemaComplexContent(); content.IsMixed = false; stype.ContentModel = content; XmlSchemaComplexContentRestriction rest = new XmlSchemaComplexContentRestriction(); content.Content = rest; rest.BaseTypeName = new XmlQualifiedName("Array", XmlSerializer.EncodingNamespace); XmlSchemaAttribute at = new XmlSchemaAttribute(); rest.Attributes.Add(at); at.RefName = new XmlQualifiedName("arrayType", XmlSerializer.EncodingNamespace); XmlAttribute arrayType = Document.CreateAttribute("arrayType", XmlSerializer.WsdlNamespace); arrayType.Value = ns + (ns != "" ? ":" : "") + name; at.UnhandledAttributes = new XmlAttribute [] { arrayType }; ImportNamespace(schema, XmlSerializer.WsdlNamespace); XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo)lmap.ItemInfo[0]; if (einfo.MappedType != null) { switch (einfo.TypeData.SchemaType) { case SchemaTypes.Enum: ExportEnumSchema(einfo.MappedType); break; case SchemaTypes.Array: ExportArraySchema(einfo.MappedType, schemaNs); break; case SchemaTypes.Class: ExportClassSchema(einfo.MappedType); break; } } return(new XmlQualifiedName(lmap.GetSchemaArrayName(), schemaNs)); } else { if (IsMapExported(map)) { return(new XmlQualifiedName(map.XmlType, map.XmlTypeNamespace)); } SetMapExported(map); XmlSchema schema = GetSchema(map.XmlTypeNamespace); XmlSchemaComplexType stype = new XmlSchemaComplexType(); stype.Name = map.ElementName; schema.Items.Add(stype); XmlSchemaParticle spart = GetSchemaArrayElement(schema, lmap.ItemInfo); if (spart is XmlSchemaChoice) { stype.Particle = spart; } else { XmlSchemaSequence seq = new XmlSchemaSequence(); seq.Items.Add(spart); stype.Particle = seq; } return(new XmlQualifiedName(map.XmlType, map.XmlTypeNamespace)); } }
/// <summary> /// Returns the sequence of properties of the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="schema">The schema.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="serializationManager">The serialization manager.</param> /// <param name="exportedTypes">The exported types.</param> /// <returns>Sequence containing all properties.</returns> private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, HashSet <string> exportedTypes) { Argument.IsNotNull("type", type); Argument.IsNotNull("schema", schema); Argument.IsNotNull("schemaSet", schemaSet); var propertiesSequence = new XmlSchemaSequence(); if (typeof(ModelBase).IsAssignableFromEx(type)) { var members = new List <MemberInfo>(); members.AddRange(from field in serializationManager.GetFieldsToSerialize(type) select type.GetFieldEx(field)); members.AddRange(from property in serializationManager.GetPropertiesToSerialize(type) select type.GetPropertyEx(property)); foreach (var member in members) { var propertySchemaElement = new XmlSchemaElement(); propertySchemaElement.Name = member.Name; var memberType = typeof(object); var fieldInfo = member as FieldInfo; if (fieldInfo != null) { memberType = fieldInfo.FieldType; } var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { memberType = propertyInfo.PropertyType; } propertySchemaElement.IsNillable = memberType.IsNullableType(); propertySchemaElement.MinOccurs = 0; var exporter = new XsdDataContractExporter(schemaSet); var alreadyExported = IsAlreadyExported(schemaSet, memberType, exporter, exportedTypes); if (!alreadyExported) { if (!exportedTypes.Contains(memberType.FullName)) { exportedTypes.Add(memberType.FullName); } try { if (exporter.CanExport(memberType)) { exporter.Export(memberType); } } catch (Exception) { // Ignore } } propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType); propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType); propertiesSequence.Items.Add(propertySchemaElement); } } return(propertiesSequence); }
internal static XmlSchemaComplexType GenerateComplexTypeACC(GeneratorContext context, XmlSchema schema, IAcc acc, string accPrefix) { // R A4CE, R AF95: a complex type must be defined for each ABIE XmlSchemaComplexType complexTypeACC = new XmlSchemaComplexType(); // R 9D83: the name of the ABIE must be the DictionaryEntryName with all whitespace and separators // removed. The 'Details' suffix is replaced with 'Type'. complexTypeACC.Name = acc.Name + "Type"; if (context.Annotate) { complexTypeACC.Annotation = GetACCAnnotation(acc); } // create the sequence for the BBIEs within the ABIE XmlSchemaSequence sequenceBCCs = new XmlSchemaSequence(); foreach (IBcc bcc in acc.Bccs.OrderBy(a => a.Name)) { // R 89A6: for every BBIE a named element must be locally declared XmlSchemaElement elementBCC = new XmlSchemaElement(); // R AEFE, R 96D9, R9A40, R A34A are implemented in GetXsdElementNameFromBbie(...) elementBCC.Name = NDR.GenerateBCCName(bcc); // R 8B85: every BBIE type must be named the property term and qualifiers and the // representation term of the basic business information entity (BBIE) it represents // with the word 'Type' appended. elementBCC.SchemaTypeName = new XmlQualifiedName(NSPREFIX_CDT + ":" + bcc.Cdt.Name + bcc.Cdt.Con.BasicType.Name + "Type"); // R 90F9: cardinality of elements within the ABIE elementBCC.MinOccursString = AdjustLowerBound(bcc.LowerBound); elementBCC.MaxOccursString = AdjustUpperBound(bcc.UpperBound); if (context.Annotate) { elementBCC.Annotation = GetBCCAnnotation(bcc); } // add the element created to the sequence sequenceBCCs.Items.Add(elementBCC); } foreach (IAscc ascc in acc.Asccs.OrderBy(a => a.Name)) { XmlSchemaElement elementASCC = new XmlSchemaElement(); // R A08A: name of the ASBIE elementASCC.Name = NDR.GenerateASCCName(ascc); elementASCC.SchemaTypeName = new XmlQualifiedName(accPrefix + ":" + ascc.AssociatedAcc.Name + "Type"); if (context.Annotate) { elementASCC.Annotation = GetASCCAnnotiation(ascc); } // R 9241: for ASBIEs with AggregationKind = shared a global element must be declared. // ASCCs are always shared (as defined in UPCC) XmlSchemaElement refASCC = new XmlSchemaElement(); refASCC.RefName = new XmlQualifiedName(accPrefix + ":" + elementASCC.Name); // every shared ASCC may only appear once in the XSD file if (!globalASCCs.Contains(elementASCC.Name)) { schema.Items.Add(elementASCC); globalASCCs.Add(elementASCC.Name); } sequenceBCCs.Items.Add(refASCC); } // add the sequence created to the complex type complexTypeACC.Particle = sequenceBCCs; return(complexTypeACC); }
public XmlSchemaType WriteArrayType(Type type, MemberInfo member) { if (generatedSchemaTypes.Contains(type.FullName)) // Caching { return(null); } XmlSchemaComplexType complexType = new XmlSchemaComplexType(); XmlQualifiedName qname = GetQualifiedName(type); if (qname == null) { complexType.Name = type.Name; } else { complexType.Name = qname.Name; } XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaElement element = new XmlSchemaElement(); element.MinOccurs = 0; element.MaxOccursString = "unbounded"; element.IsNillable = true; element.Name = qname.Name.ToLower(); object [] attrs = member.GetCustomAttributes(false); if (attrs.Length > 0) { foreach (object o in attrs) { if (o is XmlArrayItemAttribute) { if (type.IsArray == false) { throw new ArgumentException( String.Format("XmlArrayAttribute is not applicable to {0}, because it is not an array.", member.Name)); } XmlArrayItemAttribute attr = (XmlArrayItemAttribute)o; if (attr.ElementName.Length != 0) { element.Name = attr.ElementName; } continue; } if (o is XmlAnyElementAttribute) { return(null); } } } element.SchemaTypeName = GetQualifiedName( type.FullName.Substring(0, type.FullName.Length - 2)); sequence.Items.Add(element); complexType.Particle = sequence; generatedSchemaTypes.Add(type.FullName, complexType); return(complexType); }
protected XmlSchemaComplexType FindOrCreateComplexType(Type t) { XmlSchemaComplexType ct; string typeId = GenerateIDFromType(t); ct = FindComplexTypeByID(typeId); if (ct != null) { return(ct); } ct = new XmlSchemaComplexType(); ct.Name = typeId; // add complex type to collection immediately to avoid stack // overflows, when we allow a type to be nested _nantComplexTypes.Add(typeId, ct); #if NOT_IMPLEMENTED // // TODO - add task/type documentation in the future // ct.Annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); ct.Annotation.Items.Add(doc); doc.Markup = ...; #endif XmlSchemaSequence group1 = null; XmlSchemaObjectCollection attributesCollection = ct.Attributes; foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if (memInfo.DeclaringType.Equals(typeof(object))) { continue; } //Check for any return type that is derived from Element // add Attributes TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute) Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute), false); BuildElementAttribute buildElemAttr = (BuildElementAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute), false); if (taskAttrAttr != null) { XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required); attributesCollection.Add(newAttr); } else if (buildElemAttr != null) { // Create individial choice for any individual child Element Decimal min = 0; if (buildElemAttr.Required) { min = 1; } XmlSchemaElement childElement = new XmlSchemaElement(); childElement.MinOccurs = min; childElement.MaxOccurs = 1; childElement.Name = buildElemAttr.Name; //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue); Type childType; // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class if (memInfo is PropertyInfo) { childType = ((PropertyInfo)memInfo).PropertyType; } else if (memInfo is FieldInfo) { childType = ((FieldInfo)memInfo).FieldType; } else if (memInfo is MethodInfo) { MethodInfo method = (MethodInfo)memInfo; if (method.GetParameters().Length == 1) { childType = method.GetParameters()[0].ParameterType; } else { throw new ApplicationException("Method should have one parameter."); } } else { throw new ApplicationException("Member Type != Field/Property/Method"); } BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false); // determine type of child elements if (buildElementArrayAttribute != null) { if (buildElementArrayAttribute.ElementType == null) { if (childType.IsArray) { childType = childType.GetElementType(); } else { Type elementType = null; // locate Add method with 1 parameter, type of that parameter is parameter type foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; elementType = parameter.ParameterType; break; } } childType = elementType; } } else { childType = buildElementArrayAttribute.ElementType; } if (childType == null || !typeof(Element).IsAssignableFrom(childType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name)); } } BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute)Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false); if (buildElementCollectionAttribute != null) { XmlSchemaComplexType collectionType = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); collectionType.Particle = sequence; sequence.MinOccurs = 0; sequence.MaxOccursString = "unbounded"; XmlSchemaElement itemType = new XmlSchemaElement(); itemType.Name = buildElementCollectionAttribute.ChildElementName; itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; sequence.Items.Add(itemType); childElement.SchemaType = collectionType; } else { childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; } // lazy init of sequence if (group1 == null) { group1 = CreateXsdSequence(0, Decimal.MaxValue); ct.Particle = group1; } group1.Items.Add(childElement); } } // allow attributes from other namespace ct.AnyAttribute = new XmlSchemaAnyAttribute(); ct.AnyAttribute.Namespace = "##other"; ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip; Schema.Items.Add(ct); Compile(); return(ct); }
///<summary> /// Populates element nodes inside a '<xs:sequence>' node. ///</summary> public void AddElement(XmlSchemaSequence sequence, MemberInfo member, Type type) { // // Only read/write properties are supported. // if (member is PropertyInfo) { PropertyInfo p = (PropertyInfo)member; if ((p.CanRead && p.CanWrite) == false) { return; } } // // readonly fields are not supported. // if (member is FieldInfo) { FieldInfo f = (FieldInfo)member; if (f.IsInitOnly || f.IsLiteral) { return; } } // // delegates are not supported. // if (!type.IsAbstract && typeof(System.Delegate).IsAssignableFrom(type)) { return; } // // If it's an array, write a SchemaType for the type of array // if (type.IsArray) { XmlSchemaType arrayType = WriteArrayType(type, member); if (arrayType != null) { schema.Items.Add(arrayType); } } XmlSchemaElement element = new XmlSchemaElement(); element.Name = member.Name; XmlQualifiedName schema_type_name = GetQualifiedName(type); if (type.IsEnum) { element.SchemaTypeName = new XmlQualifiedName(type.Name); } else if (schema_type_name.Name == "xml") { element.SchemaType = WriteComplexSchemaType(); element.SchemaTypeName = XmlQualifiedName.Empty; // 'xml' is just a temporary name } else if (schema_type_name == null) { throw new ArgumentException(String.Format("The type '{0}' cannot be represented in XML Schema.", type.FullName)); } else // this is the normal case { element.SchemaTypeName = schema_type_name; } object [] attrs = member.GetCustomAttributes(false); if (attrs.Length > 0) { foreach (object o in attrs) { if (o is XmlElementAttribute) { XmlElementAttribute attr = (XmlElementAttribute)o; if (attr.DataType != null && attr.DataType.Length != 0) { element.SchemaTypeName = new XmlQualifiedName(attr.DataType, xs); } if (attr.ElementName != null && attr.ElementName.Length != 0) { element.Name = attr.ElementName; } continue; } if (o is XmlArrayAttribute) { if (type.IsArray == false) { throw new ArgumentException( String.Format("XmlArrayAttribute is not applicable to {0}, because it is not an array.", member.Name)); } XmlArrayAttribute attr = (XmlArrayAttribute)o; if (attr.ElementName.Length != 0) { element.Name = attr.ElementName; } continue; } // // isText signals that the mixed="true" in the schema type. // if (o is XmlTextAttribute) { isText = true; return; } if (o is XmlAnyElementAttribute) { XmlSchemaAny any = new XmlSchemaAny(); any.MinOccurs = 0; any.MaxOccursString = "unbounded"; sequence.Items.Add(any); return; } } } if (type.IsClass) { element.MinOccurs = 0; } else if (type.IsValueType) { element.MinOccurs = 1; } element.MaxOccurs = 1; sequence.Items.Add(element); }
/// <summary> /// 获取webservice方法列表 /// </summary> /// <param name="dbsrc">WebService数据源</param> /// <returns></returns> public Dictionary <string, string> GetWebServiceMethods(SFDBSrc dbsrc) { if (dbsrc == null || string.IsNullOrWhiteSpace(dbsrc.IP)) { return(new Dictionary <string, string>()); } var wsurl = dbsrc.IP.ToLower(); if (!wsurl.EndsWith(".asmx") && !wsurl.EndsWith(".svc")) { throw new Exception("@失败:" + dbsrc.No + " 中WebService地址不正确。"); } wsurl += wsurl.EndsWith(".asmx") ? "?wsdl" : "?singleWsdl"; #region //解析WebService所有方法列表 var methods = new Dictionary <string, string>(); //名称Name,全称Text var wc = new WebClient(); var stream = wc.OpenRead(wsurl); var sd = ServiceDescription.Read(stream); var eles = sd.Types.Schemas[0].Elements.Values.Cast <XmlSchemaElement>(); var s = new StringBuilder(); XmlSchemaComplexType ctype = null; XmlSchemaSequence seq = null; XmlSchemaElement res = null; foreach (var ele in eles) { if (ele == null) { continue; } var resType = string.Empty; var mparams = string.Empty; //获取接口返回元素 res = eles.FirstOrDefault(o => o.Name == (ele.Name + "Response")); if (res != null) { //1.接口名称 ele.Name //2.接口返回值类型 ctype = res.SchemaType as XmlSchemaComplexType; seq = ctype.Particle as XmlSchemaSequence; if (seq != null && seq.Items.Count > 0) { resType = (seq.Items[0] as XmlSchemaElement).SchemaTypeName.Name; } else { continue;// resType = "void"; //去除不返回结果的接口 } //3.接口参数 ctype = ele.SchemaType as XmlSchemaComplexType; seq = ctype.Particle as XmlSchemaSequence; if (seq != null && seq.Items.Count > 0) { foreach (XmlSchemaElement pe in seq.Items) { mparams += pe.SchemaTypeName.Name + " " + pe.Name + ", "; } mparams = mparams.TrimEnd(", ".ToCharArray()); } methods.Add(ele.Name, string.Format("{0} {1}({2})", resType, ele.Name, mparams)); } } stream.Close(); stream.Dispose(); wc.Dispose(); #endregion return(methods); }
internal static XmlQualifiedName NameOf(XmlSchemaObject o) { if (o is XmlSchemaAttribute) { return(((XmlSchemaAttribute)o).QualifiedName); } else if (o is XmlSchemaAttributeGroup) { return(((XmlSchemaAttributeGroup)o).QualifiedName); } else if (o is XmlSchemaComplexType) { return(((XmlSchemaComplexType)o).QualifiedName); } else if (o is XmlSchemaSimpleType) { return(((XmlSchemaSimpleType)o).QualifiedName); } else if (o is XmlSchemaElement) { return(((XmlSchemaElement)o).QualifiedName); } else if (o is XmlSchemaGroup) { return(((XmlSchemaGroup)o).QualifiedName); } else if (o is XmlSchemaGroupRef) { return(((XmlSchemaGroupRef)o).RefName); } else if (o is XmlSchemaNotation) { return(((XmlSchemaNotation)o).QualifiedName); } else if (o is XmlSchemaSequence) { XmlSchemaSequence s = (XmlSchemaSequence)o; if (s.Items.Count == 0) { return(new XmlQualifiedName(".sequence", Namespace(o))); } return(NameOf(s.Items[0])); } else if (o is XmlSchemaAll) { XmlSchemaAll a = (XmlSchemaAll)o; if (a.Items.Count == 0) { return(new XmlQualifiedName(".all", Namespace(o))); } return(NameOf(a.Items)); } else if (o is XmlSchemaChoice) { XmlSchemaChoice c = (XmlSchemaChoice)o; if (c.Items.Count == 0) { return(new XmlQualifiedName(".choice", Namespace(o))); } return(NameOf(c.Items)); } else if (o is XmlSchemaAny) { return(new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList))); } else if (o is XmlSchemaIdentityConstraint) { return(((XmlSchemaIdentityConstraint)o).QualifiedName); } return(new XmlQualifiedName("?", Namespace(o))); }
private static XmlSchemaComplexType GenerateComplexTypeForMa(GeneratorContext context, XmlSchema schema, IMa ma, string abiePrefix) { var maType = new XmlSchemaComplexType(); maType.Name = ma.Name + "Type"; var sequence = new XmlSchemaSequence(); foreach (IAsma asma in ma.Asmas.OrderBy(a => a.Name)) { XmlSchemaElement elementAsma = null; // Take care of ASMAS aggregating ABIEs if (asma.AssociatedBieAggregator.IsAbie) { elementAsma = new XmlSchemaElement { Name = NDR.GetXsdElementNameFromAsma(asma), SchemaTypeName = new XmlQualifiedName(NSPREFIX_BIE + ":" + asma.AssociatedBieAggregator.Name + "Type") }; } else if (asma.AssociatedBieAggregator.IsMa) { elementAsma = new XmlSchemaElement { Name = NDR.GetXsdElementNameFromAsma(asma), SchemaTypeName = new XmlQualifiedName(context.NamespacePrefix + ":" + asma.AssociatedBieAggregator.Name + "Type") }; } var refAsma = new XmlSchemaElement { RefName = new XmlQualifiedName(context.NamespacePrefix + ":" + NDR.GetXsdElementNameFromAsma(asma)) }; // every shared ASCC may only appear once in the XSD file if (!globalAsmas.Contains(elementAsma.Name)) { // R 9241: for ASBIEs with AggregationKind = shared a global element must be declared. schema.Items.Add(elementAsma); globalAsmas.Add(elementAsma.Name); } sequence.Items.Add(refAsma); } maType.Particle = sequence; if (context.Annotate) { maType.Annotation = GetMaAnnotation(ma); } return(maType); }
static void Main(string[] args) { // Add the customer schema to a new XmlSchemaSet and compile it. // Any schema validation warnings and errors encountered reading or // compiling the schema are handled by the ValidationEventHandler delegate. XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add("http://www.tempuri.org", "customer.xsd"); schemaSet.Compile(); // Retrieve the compiled XmlSchema object from the XmlSchemaSet // by iterating over the Schemas property. XmlSchema customerSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { customerSchema = schema; } // Create a complex type for the FirstName element. XmlSchemaComplexType complexType = new XmlSchemaComplexType(); complexType.Name = "FirstNameComplexType"; // Create a simple content extension with a base type of xs:string. XmlSchemaSimpleContent simpleContent = new XmlSchemaSimpleContent(); XmlSchemaSimpleContentExtension simpleContentExtension = new XmlSchemaSimpleContentExtension(); simpleContentExtension.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // Create the new Title attribute with a SchemaTypeName of xs:string // and add it to the simple content extension. XmlSchemaAttribute attribute = new XmlSchemaAttribute(); attribute.Name = "Title"; attribute.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); simpleContentExtension.Attributes.Add(attribute); // Set the content model of the simple content to the simple content extension // and the content model of the complex type to the simple content. simpleContent.Content = simpleContentExtension; complexType.ContentModel = simpleContent; // Add the new complex type to the pre-schema-compilation Items collection. customerSchema.Items.Add(complexType); // Iterate over each XmlSchemaObject in the pre-schema-compilation // Items collection. foreach (XmlSchemaObject schemaObject in customerSchema.Items) { // If the XmlSchemaObject is an element, whose QualifiedName // is "Customer", get the complex type of the Customer element // and the sequence particle of the complex type. if (schemaObject is XmlSchemaElement) { XmlSchemaElement element = schemaObject as XmlSchemaElement; if (element.QualifiedName.Name.Equals("Customer")) { XmlSchemaComplexType customerType = element.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence sequence = customerType.Particle as XmlSchemaSequence; // Iterate over each XmlSchemaParticle in the pre-schema-compilation // Items property. foreach (XmlSchemaParticle particle in sequence.Items) { // If the XmlSchemaParticle is an element, who's QualifiedName // is "FirstName", set the SchemaTypeName of the FirstName element // to the new FirstName complex type. if (particle is XmlSchemaElement) { XmlSchemaElement childElement = particle as XmlSchemaElement; if (childElement.Name.Equals("FirstName")) { childElement.SchemaTypeName = new XmlQualifiedName("FirstNameComplexType", "http://www.tempuri.org"); } } } } } } // Reprocess and compile the modified XmlSchema object and write it to the console. schemaSet.Reprocess(customerSchema); schemaSet.Compile(); customerSchema.Write(Console.Out); }
void GenerateXmlSchema(String[] formats, String fileFormatType) { StreamWriter writer = File.CreateText(xmlSchemaFile + "_" + fileFormatType + ".xml"); XmlSchema schema; XmlSchemaElement element; XmlSchemaComplexType complexType; XmlSchemaSequence sequence; schema = new XmlSchema(); element = new XmlSchemaElement(); schema.Items.Add(element); element.Name = "Table"; complexType = new XmlSchemaComplexType(); element.SchemaType = complexType; sequence = new XmlSchemaSequence(); complexType.Particle = sequence; element = new XmlSchemaElement(); element.Name = "Number"; element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); sequence.Items.Add(element); for(int i=0; i<formats.Length; i++){ element = new XmlSchemaElement(); element.Name = formats[i]; element.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); sequence.Items.Add(element); } schema.Compile(new ValidationEventHandler(ValidationCallbackOne)); schema.Write(writer); writer.Close(); }
private XmlSchemaComplexType CreateOperationResponseSchemaType(ResponseValueDefinition definition, XmlSchemaElement requestElement, XmlSchemaElement responseElement, FaultDefinition faultDefinition) { if (definition.ContainsNonTechnicalFault) { return new XmlSchemaComplexType { Particle = new XmlSchemaSequence { Items = { requestElement, responseElement } } } } ; if ("unbounded".Equals(responseElement.MaxOccursString) || responseElement.MaxOccurs > 1) { responseElement = new XmlSchemaElement { Name = definition.ResponseElementName, SchemaType = new XmlSchemaComplexType { Particle = new XmlSchemaSequence { Items = { responseElement } } } } } ; else { responseElement.Name = definition.ResponseElementName; } var complexTypeSequence = new XmlSchemaSequence(); if (definition.DeclaringOperationDefinition.CopyRequestPartToResponse) { complexTypeSequence.Items.Add(requestElement); } switch (definition.XRoadFaultPresentation) { case XRoadFaultPresentation.Choice: complexTypeSequence.Items.Add(new XmlSchemaChoice { Items = { responseElement, CreateFaultElement(definition, faultDefinition) } }); break; case XRoadFaultPresentation.Explicit: responseElement.MinOccurs = 0; var faultElement = CreateFaultElement(definition, faultDefinition); faultElement.MinOccurs = 0; complexTypeSequence.Items.Add(responseElement); complexTypeSequence.Items.Add(faultElement); break; case XRoadFaultPresentation.Implicit: complexTypeSequence.Items.Add(responseElement); break; default: throw new ArgumentOutOfRangeException(); } return(new XmlSchemaComplexType { Particle = complexTypeSequence }); }