static void AddImport(XmlSchema schema, string ns) { if (schema.TargetNamespace == ns) return; foreach (XmlSchemaExternal ex in schema.Includes) { XmlSchemaImport import = ex as XmlSchemaImport; if (import != null && import.Namespace == ns) { return; } } XmlSchemaImport newImport = new XmlSchemaImport(); newImport.Namespace = ns; schema.Includes.Add(newImport); }
private static void AddImport(XmlSchema schema, string ns) { if (schema.TargetNamespace != ns) { foreach (XmlSchemaExternal external in schema.Includes) { XmlSchemaImport import = external as XmlSchemaImport; if ((import != null) && (import.Namespace == ns)) { return; } } XmlSchemaImport item = new XmlSchemaImport { Namespace = ns }; schema.Includes.Add(item); } }
static internal void AddImportToSchema(string ns, XmlSchema schema) { if (NamespacesEqual(ns, schema.TargetNamespace) || NamespacesEqual(ns, XmlSchema.Namespace) || NamespacesEqual(ns, XmlSchema.InstanceNamespace)) return; foreach (object item in schema.Includes) { if (item is XmlSchemaImport && NamespacesEqual(ns, ((XmlSchemaImport)item).Namespace)) return; } XmlSchemaImport import = new XmlSchemaImport(); if (ns != null && ns.Length > 0) import.Namespace = ns; schema.Includes.Add(import); }
private void AddSchemaImport(string ns, string referencingNs) { if (((referencingNs != null) && (ns != null)) && (ns != referencingNs)) { XmlSchema schema = this.schemas[referencingNs]; if (schema == null) { throw new InvalidOperationException(Res.GetString("XmlMissingSchema", new object[] { referencingNs })); } if (((ns != null) && (ns.Length > 0)) && (this.FindImport(schema, ns) == null)) { XmlSchemaImport item = new XmlSchemaImport { Namespace = ns }; schema.Includes.Add(item); } } }
internal static void AddImportToSchema(string ns, System.Xml.Schema.XmlSchema schema) { if ((!NamespacesEqual(ns, schema.TargetNamespace) && !NamespacesEqual(ns, "http://www.w3.org/2001/XMLSchema")) && !NamespacesEqual(ns, "http://www.w3.org/2001/XMLSchema-instance")) { foreach (object obj2 in schema.Includes) { if ((obj2 is XmlSchemaImport) && NamespacesEqual(ns, ((XmlSchemaImport) obj2).Namespace)) { return; } } XmlSchemaImport item = new XmlSchemaImport(); if ((ns != null) && (ns.Length > 0)) { item.Namespace = ns; } schema.Includes.Add(item); } }
private void AddSchemaImport(string ns, string referencingNs) { if ((referencingNs != null) && !NamespacesEqual(ns, referencingNs)) { XmlSchema schema = this.schemas[referencingNs]; if (schema == null) { schema = this.AddSchema(referencingNs); } if (this.FindImport(schema, ns) == null) { XmlSchemaImport item = new XmlSchemaImport(); if ((ns != null) && (ns.Length > 0)) { item.Namespace = ns; } schema.Includes.Add(item); } } }
internal void AddExternal(XmlSchema schema, string ns, string location) { if (schema != null) { if (schema.TargetNamespace == ns) { XmlSchemaInclude item = new XmlSchemaInclude { SchemaLocation = location }; schema.Includes.Add(item); } else { XmlSchemaImport import = new XmlSchemaImport { SchemaLocation = location, Namespace = ns }; schema.Includes.Add(import); } } }
/// <summary> /// Find common elements amongst all maindocSchemas and put them in a new abstractBaseSchema. /// Modify maindocsSchemas to inherit from abstractBaseSchema and remove elements that now go /// into abstractBaseSchema. /// </summary> /// <param name="maindocSchemas"></param> /// <returns>Base schema</returns> public static XmlSchema ModifyMaindocSchemasForInheritance(ICollection<XmlSchema> maindocSchemas) { int sharedElementCount = GetSharedElementCount(maindocSchemas); if (0 == sharedElementCount) { throw new ApplicationException("Maindoc schemas do not seem to have any shared elements. Inheritance from a baseclass pointless." + "Have you mixed-up xsdfiles in common and maindoc folders?"); } // Construct new abstract base from an arbitrary maindoc schema (use it as template). Just pick the first one and pray XmlSchema templateSchema = maindocSchemas.First(); XmlSchema abstractBaseSchema = CreateAbstractBaseSchemaFromMaindocSchema(templateSchema, sharedElementCount); XmlSchemaImport abstactBaseSchemaImport = new XmlSchemaImport { Namespace = abstractBaseSchema.TargetNamespace, Schema = abstractBaseSchema }; XmlQualifiedName abstactBaseSchemaQNameToInheritFrom = new XmlQualifiedName(Constants.abstractBaseSchemaComplexTypeName, abstractBaseSchema.TargetNamespace); foreach (XmlSchema maindocSchema in maindocSchemas) { maindocSchema.Namespaces.Add("abs", abstractBaseSchema.TargetNamespace); maindocSchema.Includes.Add(abstactBaseSchemaImport); XmlSchemaComplexType maindocSchemaComplexType = maindocSchema.Items.OfType<XmlSchemaComplexType>().Single(); // Single is safe. Should only be one. XmlSchemaSequence nonSharedElementSequence = maindocSchemaComplexType.Particle as XmlSchemaSequence; //maindocSchemaComplexType.Particle = null; // do I have to do this? Has no effect // remove shared elements (they are now in the base we inherit from) for (int i = 0; i < sharedElementCount; i++) nonSharedElementSequence.Items.RemoveAt(0); maindocSchemaComplexType.ContentModel = new XmlSchemaComplexContent { Content = new XmlSchemaComplexContentExtension { BaseTypeName = abstactBaseSchemaQNameToInheritFrom, Particle = nonSharedElementSequence } }; } return abstractBaseSchema; }
private void AddImport(string current, string import) { foreach (XmlSchema schema in schemas.Schemas(current)) { bool exists = false; foreach (XmlSchemaExternal e in schema.Includes) { Import imp = e as Import; if (imp != null && imp.Namespace == import) { exists = true; } } if (exists) { continue; } Import newimp = new Import(); newimp.Namespace = import; schema.Includes.Add(newimp); } }
static void EnsureXsdImport(string ns, WsdlNS.ServiceDescription wsdl) { string refNs = wsdl.TargetNamespace; if (!refNs.EndsWith("/", StringComparison.Ordinal)) refNs = refNs + "/Imports"; else refNs += "Imports"; if (refNs == ns) refNs = wsdl.TargetNamespace; XmlSchema xsd = GetContainedSchema(wsdl, refNs); if (xsd != null) { foreach (object include in xsd.Includes) { XmlSchemaImport import = include as XmlSchemaImport; if (import != null && SchemaHelper.NamespacesEqual(import.Namespace, ns)) return; } } else { xsd = new XmlSchema(); xsd.TargetNamespace = refNs; wsdl.Types.Schemas.Add(xsd); } XmlSchemaImport imp = new XmlSchemaImport(); if (ns != null && ns.Length > 0) imp.Namespace = ns; xsd.Includes.Add(imp); }
static void AddImport(XmlSchema schema, string importNamespace) { XmlSchemaImport importElement = new XmlSchemaImport(); importElement.Namespace = importNamespace; schema.Includes.Add(importElement); }
void AddSchemaImport(string ns, string referencingNs) { if (referencingNs == null) return; if (NamespacesEqual(ns, referencingNs)) return; XmlSchema schema = schemas[referencingNs]; if (schema == null) { schema = AddSchema(referencingNs); } if (FindImport(schema, ns) == null) { XmlSchemaImport import = new XmlSchemaImport(); if (ns != null && ns.Length > 0) import.Namespace = ns; schema.Includes.Add(import); } }
//<import // id = ID // namespace = anyURI // schemaLocation = anyURI // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</import> internal static XmlSchemaImport Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaImport import = new XmlSchemaImport(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != "import") { error(h, "Should not happen :1: XmlSchemaImport.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } import.LineNumber = reader.LineNumber; import.LinePosition = reader.LinePosition; import.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { import.Id = reader.Value; } else if (reader.Name == "namespace") { import.nameSpace = reader.Value; } else if (reader.Name == "schemaLocation") { import.SchemaLocation = reader.Value; } else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h, reader.Name + " is not a valid attribute for import", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, import); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(import); } // Content: (annotation?) int level = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != xmlname) { error(h, "Should not happen :2: XmlSchemaImport.Read, name=" + reader.Name, null); } break; } if (level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h); if (annotation != null) { import.Annotation = annotation; } continue; } reader.RaiseInvalidElementError(); } return(import); }
void AddSchemaImport(string ns, string referencingNs) { if (referencingNs == null) return; if (NamespacesEqual(ns, referencingNs)) return; XmlSchema schema = schemas[referencingNs]; if (schema == null) throw new InvalidOperationException(Res.GetString(Res.XmlMissingSchema, referencingNs)); if (FindImport(schema, ns) == null) { XmlSchemaImport import = new XmlSchemaImport(); if (ns != null && ns.Length > 0) import.Namespace = ns; schema.Includes.Add(import); } }
private static void Compile(XmlSchemas userSchemas) { XmlSchema parent = new XmlSchema(); foreach (XmlSchema s in userSchemas) { if (s.TargetNamespace != null && s.TargetNamespace.Length == 0) { s.TargetNamespace = null; } if (s.TargetNamespace == parent.TargetNamespace) { XmlSchemaInclude include = new XmlSchemaInclude(); include.Schema = s; parent.Includes.Add(include); } else { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = s.TargetNamespace; import.Schema = s; parent.Includes.Add(import); } } /* to be able to compile multiple schemas using DataSets and encoded Arrays we need three additional schemas : XmlSchema: <xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema".. SoapEncoding: <xs:schema targetNamespace="http://schemas.xmlsoap.org/soap/encoding/".. Wsdl: <xs:schema targetNamespace="http://schemas.xmlsoap.org/wsdl/".. we do not need them for our validation, just to fool XmlSchema.Compile, so we are going to create the bare minimum schemas */ AddFakeSchemas(parent, userSchemas); try { XmlSchemaCollection xsc = new XmlSchemaCollection(); xsc.ValidationEventHandler += new ValidationEventHandler (ValidationCallbackWithErrorCode); xsc.Add(parent); if (xsc.Count == 0) { Console.WriteLine(Environment.NewLine + Res.GetString(Res.SchemaValidationWarning) + Environment.NewLine); } } catch (Exception e) { Console.WriteLine(Environment.NewLine + Res.GetString(Res.SchemaValidationWarning) + Environment.NewLine + e.Message + Environment.NewLine); } }
List<IWsdlExportExtension> ExportContractInternal (ContractDescription contract) { QName qname = new QName (contract.Name, contract.Namespace); if (ExportedContracts.ContainsKey (qname)) throw new ArgumentException (String.Format ( "A ContractDescription with Namespace : {0} and Name : {1} has already been exported.", contract.Namespace, contract.Name)); WSServiceDescription sd = GetServiceDescription (contract.Namespace); List<IWsdlExportExtension> extensions = new List<IWsdlExportExtension> (); foreach (IWsdlExportExtension extn in contract.Behaviors.FindAll<IWsdlExportExtension> ()) extensions.Add (extn); XmlDocument xdoc = new XmlDocument (); PortType ws_port = new PortType (); ws_port.Name = contract.Name; foreach (OperationDescription sm_op in contract.Operations) { Operation ws_op = new Operation (); ws_op.Name = sm_op.Name; foreach (MessageDescription sm_md in sm_op.Messages) { //OperationMessage OperationMessage ws_opmsg; WSMessage ws_msg = new WSMessage (); MessagePart ws_msgpart; if (sm_md.Direction == MessageDirection.Input) { ws_opmsg = new OperationInput (); ws_msg.Name = String.Concat (ws_port.Name, "_", ws_op.Name, "_", "InputMessage"); ws_msgpart = ExportMessageBodyDescription (sm_md.Body, ws_op.Name, sd.TargetNamespace); } else { ws_opmsg = new OperationOutput (); ws_msg.Name = String.Concat (ws_port.Name, "_", ws_op.Name, "_", "OutputMessage"); ws_msgpart = ExportMessageBodyDescription (sm_md.Body, ws_op.Name + "Response", sd.TargetNamespace); } ws_msg.Parts.Add (ws_msgpart); /* FIXME: Faults */ //Action XmlAttribute attr = xdoc.CreateAttribute ("wsaw", "Action", "http://www.w3.org/2006/05/addressing/wsdl"); attr.Value = sm_md.Action; ws_opmsg.ExtensibleAttributes = new XmlAttribute [] { attr }; //FIXME: Set .Input & .Output ws_opmsg.Message = new QName (ws_msg.Name, sd.TargetNamespace); ws_op.Messages.Add (ws_opmsg); sd.Messages.Add (ws_msg); } ws_port.Operations.Add (ws_op); foreach (IWsdlExportExtension extn in sm_op.Behaviors.FindAll<IWsdlExportExtension> ()) extensions.Add (extn); } //Add Imports for <types XmlSchema xs_import = new XmlSchema (); xs_import.TargetNamespace = String.Concat ( contract.Namespace, contract.Namespace.EndsWith ("/") ? "" : "/", "Imports"); foreach (XmlSchema schema in GeneratedXmlSchemas.Schemas ()) { XmlSchemaImport imp = new XmlSchemaImport (); imp.Namespace = schema.TargetNamespace; xs_import.Includes.Add (imp); } sd.Types.Schemas.Add (xs_import); sd.PortTypes.Add (ws_port); ExportedContracts [qname] = contract; WsdlContractConversionContext context = new WsdlContractConversionContext (contract, ws_port); foreach (IWsdlExportExtension extn in extensions) extn.ExportContract (this, context); return extensions; }
private void AddImport (string current, string import) { foreach (XmlSchema schema in schemas.Schemas (current)) { bool exists = false; foreach (XmlSchemaExternal e in schema.Includes) { Import imp = e as Import; if (imp != null && imp.Namespace == import) exists = true; } if (exists) continue; Import newimp = new Import (); newimp.Namespace = import; schema.Includes.Add (newimp); } }
private void AddSchemaImport(string ns, string referencingNs) { if (referencingNs == null || ns == null) return; if (ns == referencingNs) return; XmlSchema schema = _schemas[referencingNs]; if (schema == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, referencingNs)); if (ns != null && ns.Length > 0 && FindImport(schema, ns) == null) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = ns; schema.Includes.Add(import); } }
private void SetContainer(State state, object container) { switch (state) { case State.Root: break; case State.Schema: break; case State.Annotation: this.annotation = (XmlSchemaAnnotation)container; break; case State.Include: this.include = (XmlSchemaInclude)container; break; case State.Import: this.import = (XmlSchemaImport)container; break; case State.Element: this.element = (XmlSchemaElement)container; break; case State.Attribute: this.attribute = (XmlSchemaAttribute)container; break; case State.AttributeGroup: this.attributeGroup = (XmlSchemaAttributeGroup)container; break; case State.AttributeGroupRef: this.attributeGroupRef = (XmlSchemaAttributeGroupRef)container; break; case State.AnyAttribute: this.anyAttribute = (XmlSchemaAnyAttribute)container; break; case State.Group: this.group = (XmlSchemaGroup)container; break; case State.GroupRef: this.groupRef = (XmlSchemaGroupRef)container; break; case State.All: this.all = (XmlSchemaAll)container; break; case State.Choice: this.choice = (XmlSchemaChoice)container; break; case State.Sequence: this.sequence = (XmlSchemaSequence)container; break; case State.Any: this.anyElement = (XmlSchemaAny)container; break; case State.Notation: this.notation = (XmlSchemaNotation)container; break; case State.SimpleType: this.simpleType = (XmlSchemaSimpleType)container; break; case State.ComplexType: this.complexType = (XmlSchemaComplexType)container; break; case State.ComplexContent: this.complexContent = (XmlSchemaComplexContent)container; break; case State.ComplexContentExtension: this.complexContentExtension = (XmlSchemaComplexContentExtension)container; break; case State.ComplexContentRestriction: this.complexContentRestriction = (XmlSchemaComplexContentRestriction)container; break; case State.SimpleContent: this.simpleContent = (XmlSchemaSimpleContent)container; break; case State.SimpleContentExtension: this.simpleContentExtension = (XmlSchemaSimpleContentExtension)container; break; case State.SimpleContentRestriction: this.simpleContentRestriction = (XmlSchemaSimpleContentRestriction)container; break; case State.SimpleTypeUnion: this.simpleTypeUnion = (XmlSchemaSimpleTypeUnion)container; break; case State.SimpleTypeList: this.simpleTypeList = (XmlSchemaSimpleTypeList)container; break; case State.SimpleTypeRestriction: this.simpleTypeRestriction = (XmlSchemaSimpleTypeRestriction)container; break; case State.Unique: case State.Key: case State.KeyRef: this.identityConstraint = (XmlSchemaIdentityConstraint)container; break; case State.Selector: case State.Field: this.xpath = (XmlSchemaXPath)container; break; case State.MinExclusive: case State.MinInclusive: case State.MaxExclusive: case State.MaxInclusive: case State.TotalDigits: case State.FractionDigits: case State.Length: case State.MinLength: case State.MaxLength: case State.Enumeration: case State.Pattern: case State.WhiteSpace: this.facet = (XmlSchemaFacet)container; break; case State.AppInfo: this.appInfo = (XmlSchemaAppInfo)container; break; case State.Documentation: this.documentation = (XmlSchemaDocumentation)container; break; case State.Redefine: this.redefine = (XmlSchemaRedefine)container; break; default: Debug.Assert(false, "State is " + state); break; } }
internal void AddExternal(XmlSchema schema, string ns, string location) { if (schema == null) return; if (schema.TargetNamespace == ns) { XmlSchemaInclude include = new XmlSchemaInclude(); include.SchemaLocation = location; this.AddUriFixup(delegate(Uri current) { include.SchemaLocation = CombineUris(current, include.SchemaLocation); }); schema.Includes.Add(include); } else { XmlSchemaImport import = new XmlSchemaImport(); import.SchemaLocation = location; this.AddUriFixup(delegate(Uri current) { import.SchemaLocation = CombineUris(current, import.SchemaLocation); }); import.Namespace = ns; schema.Includes.Add(import); } }
public override void Check (ConformanceCheckContext ctx, XmlSchemaImport value) { // LAMESPEC: same here to Check() for Import. XmlSchema doc = ctx.GetDocument (value.SchemaLocation, value.Namespace) as XmlSchema; if (doc == null) ctx.ReportError (value, "Schema '" + value.SchemaLocation + "' not found"); }
/// <summary> /// Imports all the required schema if not already present in the WSDL. /// The default implementation will import the following schemas, /// (a) WS-Trust Feb 2005. /// (b) WS-Trust 1.3 /// Derived classes can override this method to import other schemas. /// </summary> /// <param name="exporter">The WsdlExporter that exports the contract information.</param> /// <param name="context">Provides mappings from exported WSDL elements to the endpoint description.</param> /// <param name="ns">The current WS-Trust namespace for which the schemas are imported.</param> /// <exception cref="ArgumentNullException">The parameter 'exporter' or 'context' is null.</exception> /// <exception cref="ArgumentException">The parameter 'ns' is either null or String.Empty.</exception> /// <exception cref="InvalidOperationException">The namespace 'ns' is not a recognized WS-Trust namespace.</exception> protected virtual void ImportSchema(WsdlExporter exporter, WsdlEndpointConversionContext context, string ns) { if (exporter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (String.IsNullOrEmpty(ns)) { throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("ns"); } foreach (XmlSchema xmlSchema in context.WsdlPort.Service.ServiceDescription.Types.Schemas) { foreach (XmlSchemaObject include in xmlSchema.Includes) { XmlSchemaImport schemaImport = include as XmlSchemaImport; if ((schemaImport != null) && StringComparer.Ordinal.Equals(schemaImport.Namespace, ns)) { // The schema is already imported. Just return. return; } } } XmlSchema schema = GetXmlSchema(exporter, ns); if (schema == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID3004, ns)); } XmlSchema importedSchema = null; if (context.WsdlPort.Service.ServiceDescription.Types.Schemas.Count == 0) { importedSchema = new XmlSchema(); context.WsdlPort.Service.ServiceDescription.Types.Schemas.Add(importedSchema); } else { importedSchema = context.WsdlPort.Service.ServiceDescription.Types.Schemas[0]; } XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = ns; exporter.GeneratedXmlSchemas.Add(schema); importedSchema.Includes.Add(import); }
void ProcessExternal(ValidationEventHandler handler, List <CompiledSchemaMemo> handledUris, XmlResolver resolver, XmlSchemaExternal ext, XmlSchemaSet col) { if (ext == null) { error(handler, String.Format("Object of Type {0} is not valid in Includes Property of XmlSchema", ext.GetType().Name)); return; } // The only case we want to handle where the SchemaLocation is null is if the external is an import. XmlSchemaImport import = ext as XmlSchemaImport; if (ext.SchemaLocation == null && import == null) { return; } XmlSchema includedSchema = null; if (ext.SchemaLocation != null) { Stream stream = null; string url = null; if (resolver != null) { url = GetResolvedUri(resolver, ext.SchemaLocation); foreach (var i in handledUris) { if (i.SourceUri.Equals(url)) { // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur. return; } } handledUris.Add(new CompiledSchemaMemo() { SourceUri = url }); try { stream = resolver.GetEntity(new Uri(url), null, typeof(Stream)) as Stream; } catch (Exception) { // LAMESPEC: This is not good way to handle errors, but since we cannot know what kind of XmlResolver will come, so there are no mean to avoid this ugly catch. warn(handler, "Could not resolve schema location URI: " + url); stream = null; } } // Process redefinition children in advance. XmlSchemaRedefine redefine = ext as XmlSchemaRedefine; if (redefine != null) { for (int j = 0; j < redefine.Items.Count; j++) { XmlSchemaObject redefinedObj = redefine.Items [j]; redefinedObj.isRedefinedComponent = true; redefinedObj.isRedefineChild = true; if (redefinedObj is XmlSchemaType || redefinedObj is XmlSchemaGroup || redefinedObj is XmlSchemaAttributeGroup) { compilationItems.Add(redefinedObj); } else { error(handler, "Redefinition is only allowed to simpleType, complexType, group and attributeGroup."); } } } if (stream == null) { // It is missing schema components. missedSubComponents = true; return; } else { XmlTextReader xtr = null; try { xtr = new XmlTextReader(url, stream, nameTable); includedSchema = XmlSchema.Read(xtr, handler); } finally { if (xtr != null) { xtr.Close(); } } includedSchema.schemas = schemas; } includedSchema.SetParent(); ext.Schema = includedSchema; } // Set - actual - target namespace for the included schema * before compilation*. if (import != null) { if (ext.Schema == null && ext.SchemaLocation == null) { // if a schema location wasn't specified, check the other schemas we have to see if one of those // is a match. foreach (XmlSchema schema in col.Schemas()) { if (schema.TargetNamespace == import.Namespace) { includedSchema = schema; includedSchema.schemas = schemas; includedSchema.SetParent(); ext.Schema = includedSchema; break; } } // handle case where target namespace doesn't exist in schema collection - i.e can't find it at all if (includedSchema == null) { return; } } else if (includedSchema != null) { if (TargetNamespace == includedSchema.TargetNamespace) { error(handler, "Target namespace must be different from that of included schema."); return; } else if (includedSchema.TargetNamespace != import.Namespace) { error(handler, "Attribute namespace and its importing schema's target namespace must be the same."); return; } } } else if (includedSchema != null) { if (TargetNamespace == null && includedSchema.TargetNamespace != null) { includedSchema.error(handler, String.Format("On {0} element, targetNamespace is required to include a schema which has its own target namespace", ext.GetType().Name)); return; } else if (TargetNamespace != null && includedSchema.TargetNamespace == null) { includedSchema.TargetNamespace = TargetNamespace; } } // Do not compile included schema here. if (includedSchema != null) { AddExternalComponentsTo(includedSchema, compilationItems, handler, handledUris, resolver, col); } }
private XmlSchemaAttribute AddAttribute(string localName, string prefix, string childURI, string attrValue, bool bCreatingNewType, XmlSchema parentSchema, XmlSchemaObjectCollection addLocation, XmlSchemaObjectTable compiledAttributes) { if (childURI == XmlSchema.Namespace) { throw new XmlSchemaInferenceException(Res.SchInf_schema, 0, 0); } XmlSchemaAttribute xsa = null; int AttributeType = -1; XmlSchemaAttribute returnedAttribute = null; //this value will change to attributeReference if childURI!= parentURI XmlSchema xs = null; bool add = true; Debug.Assert(compiledAttributes != null); //AttributeUses is never null // First we need to look into the already compiled attributes // (they come from the schemaset which we got on input) // If there are none or we don't find it there, then we must search the list of attributes // where we are going to add a new one (if it doesn't exist). // This is necessary to avoid adding duplicate attribute declarations. ICollection searchCollectionPrimary, searchCollectionSecondary; if (compiledAttributes.Count > 0) { searchCollectionPrimary = compiledAttributes.Values; searchCollectionSecondary = addLocation; } else { searchCollectionPrimary = addLocation; searchCollectionSecondary = null; } if (childURI == XmlReservedNs.NsXml) { XmlSchemaAttribute attributeReference = null; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); if (attributeReference == null && searchCollectionSecondary != null) { attributeReference = FindAttributeRef(searchCollectionSecondary, localName, childURI); } if (attributeReference == null) { attributeReference = new XmlSchemaAttribute(); attributeReference.RefName = new XmlQualifiedName(localName, childURI); if (bCreatingNewType && this.Occurrence == InferenceOption.Restricted) { attributeReference.Use = XmlSchemaUse.Required; } else { attributeReference.Use = XmlSchemaUse.Optional; } addLocation.Add(attributeReference); } returnedAttribute = attributeReference; } else { if (childURI.Length == 0) { xs = parentSchema; add = false; } else if (childURI != null && !schemaSet.Contains(childURI)) { /*if (parentSchema.AttributeFormDefault = XmlSchemaForm.Unqualified && childURI.Length == 0) { xs = parentSchema; add = false; break; }*/ xs = new XmlSchema(); xs.AttributeFormDefault = XmlSchemaForm.Unqualified; xs.ElementFormDefault = XmlSchemaForm.Qualified; if (childURI.Length != 0) xs.TargetNamespace = childURI; //schemas.Add(childURI, xs); this.schemaSet.Add(xs); if (prefix.Length != 0 && String.Compare(prefix, "xml", StringComparison.OrdinalIgnoreCase) != 0) NamespaceManager.AddNamespace(prefix, childURI); } else { ArrayList col = this.schemaSet.Schemas(childURI) as ArrayList; if (col != null && col.Count > 0) { xs = col[0] as XmlSchema; } } if (childURI.Length != 0) // { XmlSchemaAttribute attributeReference = null; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); if (attributeReference == null & searchCollectionSecondary != null) { attributeReference = FindAttributeRef(searchCollectionSecondary, localName, childURI); } if (attributeReference == null) { attributeReference = new XmlSchemaAttribute(); attributeReference.RefName = new XmlQualifiedName(localName, childURI); if (bCreatingNewType && this.Occurrence == InferenceOption.Restricted) { attributeReference.Use = XmlSchemaUse.Required; } else { attributeReference.Use = XmlSchemaUse.Optional; } addLocation.Add(attributeReference); } returnedAttribute = attributeReference; //see if the attribute exists on the global level xsa = FindAttribute(xs.Items, localName); if (xsa == null) { xsa = new XmlSchemaAttribute(); xsa.Name = localName; xsa.SchemaTypeName = RefineSimpleType(attrValue, ref AttributeType); xsa.LineNumber = AttributeType; //we use LineNumber to store flags of valid types xs.Items.Add(xsa); } else { if (xsa.Parent == null) { AttributeType = xsa.LineNumber; // we use LineNumber to store flags of valid types } else { AttributeType = GetSchemaType(xsa.SchemaTypeName); xsa.Parent = null; } xsa.SchemaTypeName = RefineSimpleType(attrValue, ref AttributeType); xsa.LineNumber = AttributeType; // we use LineNumber to store flags of valid types } } else { xsa = FindAttribute(searchCollectionPrimary, localName); if (xsa == null && searchCollectionSecondary != null) { xsa = FindAttribute(searchCollectionSecondary, localName); } if (xsa == null) { xsa = new XmlSchemaAttribute(); xsa.Name = localName; xsa.SchemaTypeName = RefineSimpleType(attrValue, ref AttributeType); xsa.LineNumber = AttributeType; // we use LineNumber to store flags of valid types if (bCreatingNewType && this.Occurrence == InferenceOption.Restricted) xsa.Use = XmlSchemaUse.Required; else xsa.Use = XmlSchemaUse.Optional; addLocation.Add(xsa); if (xs.AttributeFormDefault != XmlSchemaForm.Unqualified) { xsa.Form = XmlSchemaForm.Unqualified; } } else { if (xsa.Parent == null) { AttributeType = xsa.LineNumber; // we use LineNumber to store flags of valid types } else { AttributeType = GetSchemaType(xsa.SchemaTypeName); xsa.Parent = null; } xsa.SchemaTypeName = RefineSimpleType(attrValue, ref AttributeType); xsa.LineNumber = AttributeType; // we use LineNumber to store flags of valid types } returnedAttribute = xsa; } } string nullString = null; if (add && childURI != parentSchema.TargetNamespace) { for (int i = 0; i < parentSchema.Includes.Count; ++i) { XmlSchemaImport import = parentSchema.Includes[i] as XmlSchemaImport; if (import == null) { continue; } if (import.Namespace == childURI) { add = false; } } if (add) { XmlSchemaImport import = new XmlSchemaImport(); import.Schema = xs; if (childURI.Length != 0) { nullString = childURI; } import.Namespace = nullString; parentSchema.Includes.Add(import); } } return returnedAttribute; }
private static void ReadContent(XmlSchema schema, XmlSchemaReader reader, ValidationEventHandler h) { reader.MoveToElement(); if (reader.LocalName != "schema" && reader.NamespaceURI != XmlSchema.Namespace && reader.NodeType != XmlNodeType.Element) { error(h, "UNREACHABLE CODE REACHED: Method: Schema.ReadContent, " + reader.LocalName + ", " + reader.NamespaceURI, null); } //(include | import | redefine | annotation)*, //((simpleType | complexType | group | attributeGroup | element | attribute | notation | annotation)* int level = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != xmlname) { error(h, "Should not happen :2: XmlSchema.Read, name=" + reader.Name, null); } break; } if (level <= 1) { if (reader.LocalName == "include") { XmlSchemaInclude include = XmlSchemaInclude.Read(reader, h); if (include != null) { schema.includes.Add(include); } continue; } if (reader.LocalName == "import") { XmlSchemaImport import = XmlSchemaImport.Read(reader, h); if (import != null) { schema.includes.Add(import); } continue; } if (reader.LocalName == "redefine") { XmlSchemaRedefine redefine = XmlSchemaRedefine.Read(reader, h); if (redefine != null) { schema.includes.Add(redefine); } continue; } if (reader.LocalName == "annotation") { XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h); if (annotation != null) { schema.items.Add(annotation); } continue; } } if (level <= 2) { level = 2; if (reader.LocalName == "simpleType") { XmlSchemaSimpleType stype = XmlSchemaSimpleType.Read(reader, h); if (stype != null) { schema.items.Add(stype); } continue; } if (reader.LocalName == "complexType") { XmlSchemaComplexType ctype = XmlSchemaComplexType.Read(reader, h); if (ctype != null) { schema.items.Add(ctype); } continue; } if (reader.LocalName == "group") { XmlSchemaGroup group = XmlSchemaGroup.Read(reader, h); if (group != null) { schema.items.Add(group); } continue; } if (reader.LocalName == "attributeGroup") { XmlSchemaAttributeGroup attributeGroup = XmlSchemaAttributeGroup.Read(reader, h); if (attributeGroup != null) { schema.items.Add(attributeGroup); } continue; } if (reader.LocalName == "element") { XmlSchemaElement element = XmlSchemaElement.Read(reader, h); if (element != null) { schema.items.Add(element); } continue; } if (reader.LocalName == "attribute") { XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader, h); if (attr != null) { schema.items.Add(attr); } continue; } if (reader.LocalName == "notation") { XmlSchemaNotation notation = XmlSchemaNotation.Read(reader, h); if (notation != null) { schema.items.Add(notation); } continue; } if (reader.LocalName == "annotation") { XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader, h); if (annotation != null) { schema.items.Add(annotation); } continue; } } reader.RaiseInvalidElementError(); } }
internal static XmlSchemaImport Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaImport xmlSchemaImport = new XmlSchemaImport(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "import") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaImport.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } xmlSchemaImport.LineNumber = reader.LineNumber; xmlSchemaImport.LinePosition = reader.LinePosition; xmlSchemaImport.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { xmlSchemaImport.Id = reader.Value; } else if (reader.Name == "namespace") { xmlSchemaImport.nameSpace = reader.Value; } else if (reader.Name == "schemaLocation") { xmlSchemaImport.SchemaLocation = reader.Value; } else if ((reader.NamespaceURI == string.Empty && reader.Name != "xmlns") || reader.NamespaceURI == "http://www.w3.org/2001/XMLSchema") { XmlSchemaObject.error(h, reader.Name + " is not a valid attribute for import", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaImport); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(xmlSchemaImport); } int num = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != "import") { XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaImport.Read, name=" + reader.Name, null); } break; } if (num <= 1 && reader.LocalName == "annotation") { num = 2; XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h); if (xmlSchemaAnnotation != null) { xmlSchemaImport.Annotation = xmlSchemaAnnotation; } } else { reader.RaiseInvalidElementError(); } } return(xmlSchemaImport); }
void DoCompile(ValidationEventHandler handler, Hashtable handledUris, XmlSchemaSet col, XmlResolver resolver) { SetParent(); CompilationId = col.CompilationId; schemas = col; if (!schemas.Contains(this)) // e.g. xs:import { schemas.Add(this); } attributeGroups.Clear(); attributes.Clear(); elements.Clear(); groups.Clear(); notations.Clear(); schemaTypes.Clear(); //1. Union and List are not allowed in block default if (BlockDefault != XmlSchemaDerivationMethod.All) { if ((BlockDefault & XmlSchemaDerivationMethod.List) != 0) { error(handler, "list is not allowed in blockDefault attribute"); } if ((BlockDefault & XmlSchemaDerivationMethod.Union) != 0) { error(handler, "union is not allowed in blockDefault attribute"); } } //2. Substitution is not allowed in finaldefault. if (FinalDefault != XmlSchemaDerivationMethod.All) { if ((FinalDefault & XmlSchemaDerivationMethod.Substitution) != 0) { error(handler, "substitution is not allowed in finalDefault attribute"); } } //3. id must be of type ID XmlSchemaUtil.CompileID(Id, this, col.IDCollection, handler); //4. targetNamespace should be of type anyURI or absent if (TargetNamespace != null) { if (TargetNamespace.Length == 0) { error(handler, "The targetNamespace attribute cannot have have empty string as its value."); } if (!XmlSchemaUtil.CheckAnyUri(TargetNamespace)) { error(handler, TargetNamespace + " is not a valid value for targetNamespace attribute of schema"); } } //5. version should be of type normalizedString if (!XmlSchemaUtil.CheckNormalizedString(Version)) { error(handler, Version + "is not a valid value for version attribute of schema"); } // Compile the content of this schema compilationItems = new XmlSchemaObjectCollection(); for (int i = 0; i < Items.Count; i++) { compilationItems.Add(Items [i]); } // First, we run into inclusion schemas to collect // compilation target items into compiledItems. for (int i = 0; i < Includes.Count; i++) { XmlSchemaExternal ext = Includes [i] as XmlSchemaExternal; if (ext == null) { error(handler, String.Format("Object of Type {0} is not valid in Includes Property of XmlSchema", Includes [i].GetType().Name)); continue; } if (ext.SchemaLocation == null) { continue; } Stream stream = null; string url = null; if (resolver != null) { url = GetResolvedUri(resolver, ext.SchemaLocation); if (handledUris.Contains(url)) { // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur. continue; } handledUris.Add(url, url); try { stream = resolver.GetEntity(new Uri(url), null, typeof(Stream)) as Stream; } catch (Exception) { // LAMESPEC: This is not good way to handle errors, but since we cannot know what kind of XmlResolver will come, so there are no mean to avoid this ugly catch. warn(handler, "Could not resolve schema location URI: " + url); stream = null; } } // Process redefinition children in advance. XmlSchemaRedefine redefine = Includes [i] as XmlSchemaRedefine; if (redefine != null) { for (int j = 0; j < redefine.Items.Count; j++) { XmlSchemaObject redefinedObj = redefine.Items [j]; redefinedObj.isRedefinedComponent = true; redefinedObj.isRedefineChild = true; if (redefinedObj is XmlSchemaType || redefinedObj is XmlSchemaGroup || redefinedObj is XmlSchemaAttributeGroup) { compilationItems.Add(redefinedObj); } else { error(handler, "Redefinition is only allowed to simpleType, complexType, group and attributeGroup."); } } } XmlSchema includedSchema = null; if (stream == null) { // It is missing schema components. missedSubComponents = true; continue; } else { XmlTextReader xtr = null; try { xtr = new XmlTextReader(url, stream, nameTable); includedSchema = XmlSchema.Read(xtr, handler); } finally { if (xtr != null) { xtr.Close(); } } includedSchema.schemas = schemas; } includedSchema.SetParent(); ext.Schema = includedSchema; // Set - actual - target namespace for the included schema * before compilation*. XmlSchemaImport import = ext as XmlSchemaImport; if (import != null) { if (TargetNamespace == includedSchema.TargetNamespace) { error(handler, "Target namespace must be different from that of included schema."); continue; } else if (includedSchema.TargetNamespace != import.Namespace) { error(handler, "Attribute namespace and its importing schema's target namespace must be the same."); continue; } } else { if (TargetNamespace == null && includedSchema.TargetNamespace != null) { error(handler, "Target namespace is required to include a schema which has its own target namespace"); continue; } else if (TargetNamespace != null && includedSchema.TargetNamespace == null) { includedSchema.TargetNamespace = TargetNamespace; } } // Do not compile included schema here. AddExternalComponentsTo(includedSchema, compilationItems); } // Compilation phase. // At least each Compile() must give unique (qualified) name for each component. // It also checks self-resolvable properties correctness. // Post compilation schema information contribution is not done here. // It should be done by Validate(). for (int i = 0; i < compilationItems.Count; i++) { XmlSchemaObject obj = compilationItems [i]; if (obj is XmlSchemaAnnotation) { int numerr = ((XmlSchemaAnnotation)obj).Compile(handler, this); errorCount += numerr; } else if (obj is XmlSchemaAttribute) { XmlSchemaAttribute attr = (XmlSchemaAttribute)obj; int numerr = attr.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable(Attributes, attr, attr.QualifiedName, handler); } } else if (obj is XmlSchemaAttributeGroup) { XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup)obj; int numerr = attrgrp.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( AttributeGroups, attrgrp, attrgrp.QualifiedName, handler); } } else if (obj is XmlSchemaComplexType) { XmlSchemaComplexType ctype = (XmlSchemaComplexType)obj; int numerr = ctype.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( schemaTypes, ctype, ctype.QualifiedName, handler); } } else if (obj is XmlSchemaSimpleType) { XmlSchemaSimpleType stype = (XmlSchemaSimpleType)obj; stype.islocal = false; //This simple type is toplevel int numerr = stype.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( SchemaTypes, stype, stype.QualifiedName, handler); } } else if (obj is XmlSchemaElement) { XmlSchemaElement elem = (XmlSchemaElement)obj; elem.parentIsSchema = true; int numerr = elem.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( Elements, elem, elem.QualifiedName, handler); } } else if (obj is XmlSchemaGroup) { XmlSchemaGroup grp = (XmlSchemaGroup)obj; int numerr = grp.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( Groups, grp, grp.QualifiedName, handler); } } else if (obj is XmlSchemaNotation) { XmlSchemaNotation ntn = (XmlSchemaNotation)obj; int numerr = ntn.Compile(handler, this); errorCount += numerr; if (numerr == 0) { XmlSchemaUtil.AddToTable( Notations, ntn, ntn.QualifiedName, handler); } } else { ValidationHandler.RaiseValidationEvent( handler, null, String.Format("Object of Type {0} is not valid in Item Property of Schema", obj.GetType().Name), null, this, null, XmlSeverityType.Error); } } }
public override void Check (ConformanceCheckContext ctx, XmlSchemaImport value) { XmlSchema doc = ctx.GetDocument (value.SchemaLocation) as XmlSchema; if (doc == null) ctx.ReportError (value, "Schema '" + value.SchemaLocation + "' not found"); }
/// <summary> /// Generate a set of schemas from the given type. /// /// Every serializable .NET class can be represented by a schema. /// If that class inherits from another class, then this method will generate more than one schema. /// The number of schemas is determines by .NET's own magic formula for when a new schema is needed /// but this is probably determined by the namespace attributes added (in the form of XmlRoot and /// XmlType attribute) to the class. /// /// We assume that the first schema in the array of generated schemas contains the schema /// of the type we requested. /// /// </summary> /// <param name="type">A type to generate schemas from</param> /// <returns>An array of schemas</returns> public IList<XmlSchema> GenerateSchema(Type type) { Type typeToGenerate = type.IsByRef ? type.GetElementType() : type; #region generate the schema from the type XmlReflectionImporter reflectionImporter = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping map = reflectionImporter.ImportTypeMapping(typeToGenerate); exporter.ExportTypeMapping(map); #endregion #region compile the schemas to make sure they were generated correctly XmlSchemaSet schemaSet = new XmlSchemaSet(); try { foreach (XmlSchema schema in schemas) schemaSet.Add(schema); // some generated classes contain xs:any elements // disabling this check allows us to avoid a compilation error schemaSet.CompilationSettings.EnableUpaCheck = false; schemaSet.XmlResolver = null; // we don't want to resolve any outside schemas schemaSet.ValidationEventHandler += new ValidationEventHandler(schemaSet_ValidationEventHandler); schemaSet.Compile(); } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } #endregion #region this is a special case for certain types of generated classes // when you use the System.Reflection.Emit namespace to generate a type, // and then try to generate schemas from that type, the schemas don't // contain "imports" for types in other namespaces. // This code block adds those imports. // if the number of schemas generated is greater than 1 (meaning there are // potentially types in other namespaces (and hence other schemas) // AND if the first schema generated does not include any other schemas // we know we're generating a schema that has the charateristics we're // expecting if (schemas.Count > 1 && schemas[0].Includes.Count == 0) { // create a list of schemas to process IList<XmlSchema> schemaArray = XmlSchemasToArray(schemas); // since the number of schemas is greater than one we know that there // are at least 2 schemas, so we can safely index from 1 for (int i = 1; i < schemaArray.Count; i++) { // create a new schema import, and set the namespace XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = schemaArray[i].TargetNamespace; // import it into the first schema schemaArray[0].Includes.Add(import); } schemaSet.Compile(); } #endregion #region "fix" the pointers to the included schemas for the generated schemas ResolveImportedSchemas(schemas, XmlConvert.EncodeName(typeToGenerate.Name)); #endregion // convert the generated schemas to an array of schemas return XmlSchemasToArray(schemas); }
void ImportNamespace (XmlSchema schema, string ns) { if (ns == null || ns.Length == 0 || ns == schema.TargetNamespace || ns == XmlSchema.Namespace) return; foreach (XmlSchemaObject sob in schema.Includes) if ((sob is XmlSchemaImport) && ((XmlSchemaImport)sob).Namespace == ns) return; XmlSchemaImport imp = new XmlSchemaImport (); imp.Namespace = ns; schema.Includes.Add (imp); }
//FIXME: Replace with a dictionary ? void AddImport (XmlSchema schema, string ns) { if (ns == XmlSchema.Namespace || schema.TargetNamespace == ns) return; foreach (XmlSchemaObject o in schema.Includes) { XmlSchemaImport import = o as XmlSchemaImport; if (import == null) continue; if (import.Namespace == ns) return; } XmlSchemaImport imp = new XmlSchemaImport (); imp.Namespace = ns; schema.Includes.Add (imp); }
//<import // id = ID // namespace = anyURI // schemaLocation = anyURI // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</import> internal static XmlSchemaImport Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaImport import = new XmlSchemaImport(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != "import") { error(h,"Should not happen :1: XmlSchemaImport.Read, name="+reader.Name,null); reader.SkipToEnd(); return null; } import.LineNumber = reader.LineNumber; import.LinePosition = reader.LinePosition; import.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { import.Id = reader.Value; } else if(reader.Name == "namespace") { import.nameSpace = reader.Value; } else if(reader.Name == "schemaLocation") { import.SchemaLocation = reader.Value; } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for import",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,import); } } reader.MoveToElement(); if(reader.IsEmptyElement) return import; // Content: (annotation?) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaImport.Read, name="+reader.Name,null); break; } if(level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h); if(annotation != null) import.Annotation = annotation; continue; } reader.RaiseInvalidElementError(); } return import; }
public void v10() { bWarningCallback = false; bErrorCallback = false; XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema Schema1 = sc.Add(null, TestData._Root + "reprocess_v9_a.xsd"); CError.Compare(sc.Count, 2, "Count after add"); CError.Compare(sc.Contains(Schema1), true, "Contains after add"); sc.Compile(); CError.Compare(sc.Count, 2, "Count after add/comp"); CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp"); //edit XmlSchemaImport imp = new XmlSchemaImport(); imp.Namespace = "ns-a"; imp.SchemaLocation = "reprocess_v9_a.xsd"; Schema1.Includes.Add(imp); sc.Reprocess(Schema1); ValidateSchemaSet(sc, 2, false, 2, 1, 0, "Validation after edit/reprocess"); CError.Compare(bWarningCallback, false, "Warning repr"); CError.Compare(bErrorCallback, true, "Error repr"); sc.Compile(); ValidateSchemaSet(sc, 2, false, 2, 1, 0, "Validation after comp/reprocess"); CError.Compare(bWarningCallback, false, "Warning comp"); CError.Compare(bErrorCallback, true, "Error comp"); CError.Compare(Schema1.IsCompiled, false, "IsCompiled on SOM"); return; }
internal void ReflectStringParametersMessage() { Message inputMessage = InputMessage; foreach (ParameterInfo parameterInfo in Method.InParameters) { MessagePart part = new MessagePart(); part.Name = XmlConvert.EncodeLocalName(parameterInfo.Name); if (parameterInfo.ParameterType.IsArray) { string typeNs = DefaultNamespace; if (typeNs.EndsWith("/", StringComparison.Ordinal)) typeNs += "AbstractTypes"; else typeNs += "/AbstractTypes"; string typeName = "StringArray"; if (!ServiceDescription.Types.Schemas.Contains(typeNs)) { XmlSchema schema = new XmlSchema(); schema.TargetNamespace = typeNs; ServiceDescription.Types.Schemas.Add(schema); XmlSchemaElement element = new XmlSchemaElement(); element.Name = "String"; element.SchemaTypeName = new XmlQualifiedName("string", XmlSchema.Namespace); element.MinOccurs = decimal.Zero; element.MaxOccurs = decimal.MaxValue; XmlSchemaSequence all = new XmlSchemaSequence(); all.Items.Add(element); XmlSchemaComplexContentRestriction restriction = new XmlSchemaComplexContentRestriction(); restriction.BaseTypeName = new XmlQualifiedName(Soap.ArrayType, Soap.Encoding); restriction.Particle = all; XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = restriction.BaseTypeName.Namespace; XmlSchemaComplexContent model = new XmlSchemaComplexContent(); model.Content = restriction; XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = typeName; type.ContentModel = model; schema.Items.Add(type); schema.Includes.Add(import); } part.Type = new XmlQualifiedName(typeName, typeNs); } else { part.Type = new XmlQualifiedName("string", XmlSchema.Namespace); } inputMessage.Parts.Add(part); } }
private XmlSchemaElement AddElement(string localName, string prefix, string childURI, XmlSchema parentSchema, XmlSchemaObjectCollection addLocation, int positionWithinCollection) { if (childURI == XmlSchema.Namespace) { throw new XmlSchemaInferenceException(Res.SchInf_schema, 0, 0); } XmlSchemaElement xse = null; XmlSchemaElement returnedElement = xse; //this value will change to elementReference if childURI!= parentURI XmlSchema xs = null; bool bCreatingNewType = true; if (childURI == String.Empty) { childURI = null; } // The new element belongs to the same ns as parent and addlocation is not null if (parentSchema != null && childURI == parentSchema.TargetNamespace) { xse = new XmlSchemaElement(); xse.Name = localName; xs = parentSchema; if (xs.ElementFormDefault != XmlSchemaForm.Qualified && addLocation != null) { xse.Form = XmlSchemaForm.Qualified; } } else if (schemaSet.Contains(childURI)) { xse = this.FindGlobalElement(childURI, localName, out xs); if (xse == null) { ArrayList col = this.schemaSet.Schemas(childURI)as ArrayList; if (col != null && col.Count > 0 ) { xs = col[0] as XmlSchema; } xse = new XmlSchemaElement(); xse.Name = localName; xs.Items.Add(xse); } else bCreatingNewType = false; } else { xs = CreateXmlSchema(childURI); if (prefix.Length!=0) NamespaceManager.AddNamespace(prefix, childURI); xse=new XmlSchemaElement(); xse.Name = localName; xs.Items.Add(xse); //add global element declaration only when creating new schema } if (parentSchema == null) { parentSchema = xs; this.rootSchema = parentSchema; } if (childURI != parentSchema.TargetNamespace ) { bool add = true; for (int i = 0; i < parentSchema.Includes.Count; ++i) { XmlSchemaImport import = parentSchema.Includes[i] as XmlSchemaImport; if (import == null) { continue; } //Debug.WriteLine(import.Schema.TargetNamespace); if (import.Namespace == childURI) { add = false; } } if (add) { XmlSchemaImport import = new XmlSchemaImport(); import.Schema = xs; import.Namespace = childURI; parentSchema.Includes.Add(import); } } returnedElement = xse; if (addLocation != null) { if (childURI == parentSchema.TargetNamespace ) { if (this.Occurrence == InferenceOption.Relaxed /*&& parentSchema.Items != addLocation*/) { xse.MinOccurs = 0; } if (positionWithinCollection == -1) { positionWithinCollection = addLocation.Add(xse); } else { addLocation.Insert(positionWithinCollection, xse); } } else { XmlSchemaElement elementReference = new XmlSchemaElement(); elementReference.RefName = new XmlQualifiedName(localName, childURI); if (this.Occurrence == InferenceOption.Relaxed) { elementReference.MinOccurs = 0; } if (positionWithinCollection == -1) { positionWithinCollection = addLocation.Add(elementReference); } else { addLocation.Insert(positionWithinCollection, elementReference); } returnedElement = elementReference; /* if (childURI == XmlSchema.Namespace) { schemaList.Add(new ReplaceList(addLocation, positionWithinCollection)); }*/ } } InferElement(xse, bCreatingNewType, xs); return returnedElement; }
static void AddFakeSchemas(XmlSchema parent, XmlSchemas schemas) { if (schemas[XmlSchema.Namespace] == null) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = XmlSchema.Namespace; import.Schema = CreateFakeXsdSchema(XmlSchema.Namespace, "schema"); parent.Includes.Add(import); } if (schemas[Namespace.SoapEncoding] == null) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = Namespace.SoapEncoding; import.Schema = CreateFakeSoapEncodingSchema(Namespace.SoapEncoding, "Array"); parent.Includes.Add(import); } if (schemas[Namespace.Wsdl] == null) { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = Namespace.Wsdl; import.Schema = CreateFakeWsdlSchema(Namespace.Wsdl); parent.Includes.Add(import); } }