/// <summary> /// Validates the CDATA section. /// </summary> /// <param name="cdata">The Xml string in CDATA section.</param> /// <param name="include">The schema should be included.</param> /// <param name="type">The type name in the included schema to validate the CDATA.</param> /// <returns>The schema which validated the CDATA.</returns> public static XmlSchema ValidateCdataSection(string cdata, XmlSchemaInclude include, string type) { if (string.IsNullOrEmpty(cdata)) { throw new ArgumentNullException("cdata"); } if (include == null) { throw new ArgumentNullException("include"); } if (string.IsNullOrEmpty(type)) { throw new ArgumentNullException("type"); } // Creates a XmlDocument to load the cdata, to get a the document element. XmlDocument doc = new XmlDocument(); try { doc.LoadXml(cdata); } catch (XmlException e) { throw new ArgumentException(Helper.NeutralFormat("Input data is not a Xml document - \"{0}\"", cdata), e); } if (doc.DocumentElement == null) { throw new ArgumentException("Input data have no document element - \"{0}\"", cdata); } // Generates a fake document by adding a root element. string xml = GenerateDocumentForCDataSection(cdata); // Creates a stream to save the document. using (MemoryStream stream = new MemoryStream()) { byte[] bytes = Encoding.UTF8.GetBytes(xml); stream.Write(bytes, 0, bytes.Length); stream.Seek(0, SeekOrigin.Begin); // Creates a schema to validate the document. XmlSchema schema = GenerateSchemaForCDataSection(include, doc.DocumentElement.Name, type); try { // Validates the stream. XmlHelper.Validate(stream, schema); } catch (InvalidDataException ide) { throw new InvalidDataException( Helper.NeutralFormat("Validation failed in input data \"{0}\"", cdata), ide); } return schema; } }
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); } } }
//<include // id = ID // schemaLocation = anyURI // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</include> internal static XmlSchemaInclude Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaInclude include = new XmlSchemaInclude(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaInclude.Read, name="+reader.Name,null); reader.SkipToEnd(); return null; } include.LineNumber = reader.LineNumber; include.LinePosition = reader.LinePosition; include.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { include.Id = reader.Value; } else if(reader.Name == "schemaLocation") { include.SchemaLocation = reader.Value; } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for include",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,include); } } reader.MoveToElement(); if(reader.IsEmptyElement) return include; // Content: (annotation?) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaInclude.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) include.Annotation = annotation; continue; } reader.RaiseInvalidElementError(); } return include; }
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); } }
protected override void Visit(XmlSchemaInclude include) { TraverseExternalSchema(include); }
/// <summary> /// Generates a schema to validate the generated document. /// </summary> /// <param name="include">The schema should be included.</param> /// <param name="name">The name of the CDATA section.</param> /// <param name="type">The type name in the included schema to validate the CDATA.</param> /// <returns>The generated schema.</returns> private static XmlSchema GenerateSchemaForCDataSection(XmlSchemaInclude include, string name, string type) { StringBuilder builder = new StringBuilder(); builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); builder.AppendLine("<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\""); builder.AppendLine(" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""); builder.AppendLine(" targetNamespace=\"http://schemas.microsoft.com/tts/toolsuite\""); builder.AppendLine(" xmlns=\"http://schemas.microsoft.com/tts/toolsuite\">"); builder.AppendLine("<xs:element name=\"cdataSection\">"); builder.AppendLine("<xs:complexType>"); builder.AppendLine("<xs:sequence>"); builder.AppendFormat("<xs:element name=\"{0}\" type=\"{1}\" />", name, type); builder.AppendLine("</xs:sequence>"); builder.AppendLine("</xs:complexType>"); builder.AppendLine("</xs:element>"); builder.Append("</xs:schema>"); using (TextReader reader = new StringReader(builder.ToString())) { XmlSchema schema = XmlSchema.Read(reader, null); schema.Includes.Add(include); return schema; } }
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 static XmlSchemaInclude Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaInclude xmlSchemaInclude = new XmlSchemaInclude(); reader.MoveToElement(); if (reader.NamespaceURI != "http://www.w3.org/2001/XMLSchema" || reader.LocalName != "include") { XmlSchemaObject.error(h, "Should not happen :1: XmlSchemaInclude.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } xmlSchemaInclude.LineNumber = reader.LineNumber; xmlSchemaInclude.LinePosition = reader.LinePosition; xmlSchemaInclude.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { xmlSchemaInclude.Id = reader.Value; } else if (reader.Name == "schemaLocation") { xmlSchemaInclude.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 include", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, xmlSchemaInclude); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(xmlSchemaInclude); } int num = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != "include") { XmlSchemaObject.error(h, "Should not happen :2: XmlSchemaInclude.Read, name=" + reader.Name, null); } break; } if (num <= 1 && reader.LocalName == "annotation") { num = 2; XmlSchemaAnnotation xmlSchemaAnnotation = XmlSchemaAnnotation.Read(reader, h); if (xmlSchemaAnnotation != null) { xmlSchemaInclude.Annotation = xmlSchemaAnnotation; } } else { reader.RaiseInvalidElementError(); } } return(xmlSchemaInclude); }
protected virtual void Visit(XmlSchemaInclude include) { }
private void Compile(XmlSchemas userSchemas) { XmlSchema parent = new XmlSchema(); foreach (XmlSchema schema2 in userSchemas) { if ((schema2.TargetNamespace != null) && (schema2.TargetNamespace.Length == 0)) { schema2.TargetNamespace = null; } if (schema2.TargetNamespace == parent.TargetNamespace) { XmlSchemaInclude item = new XmlSchemaInclude(); item.Schema = schema2; parent.Includes.Add(item); } else { XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = schema2.TargetNamespace; import.Schema = schema2; parent.Includes.Add(import); } } AddFakeSchemas(parent, userSchemas); try { //XmlSchemaCollection schemas = new XmlSchemaCollection(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallbackWithErrorCode); schemas.Add(parent); if (schemas.Count == 0) { this.CheckPoint(MessageType.Warning, schemaValidationFailure); } } catch (Exception exception) { this.CheckPoint(MessageType.Warning, schemaValidationFailure + "\n" + exception.Message); } }
private void Compile(XmlSchemas userSchemas) { XmlSchema schema1 = new XmlSchema(); foreach (XmlSchema schema2 in userSchemas) { if ((schema2.TargetNamespace != null) && (schema2.TargetNamespace.Length == 0)) { schema2.TargetNamespace = null; } if (schema2.TargetNamespace == schema1.TargetNamespace) { XmlSchemaInclude include1 = new XmlSchemaInclude(); include1.Schema = schema2; schema1.Includes.Add(include1); } else { XmlSchemaImport import1 = new XmlSchemaImport(); import1.Namespace = schema2.TargetNamespace; import1.Schema = schema2; schema1.Includes.Add(import1); } } AddFakeSchemas(schema1, userSchemas); try { XmlSchemaCollection collection1 = new XmlSchemaCollection(); collection1.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode); collection1.Add(schema1); if (collection1.Count == 0) { CheckPoint(MessageType.Warning, schemaValidationFailure); } } catch (Exception exception1) { CheckPoint(MessageType.Warning, schemaValidationFailure + "\n" + exception1.Message); return; } }
private static void ConstructSchemaImports(InterfaceContract serviceInterfaceContract, bool isRoundTrip, System.Web.Services.Description.ServiceDescription desc) { XmlSchema typesSchema = null; // Are we round-tripping? Then we have to access the existing types // section. // Otherwise we just initialize a new XmlSchema for types. if (isRoundTrip) { typesSchema = desc.Types.Schemas[desc.TargetNamespace]; // if we don't have a types section belonging to the same namespace as service description // we take the first types section available. if (typesSchema == null) { typesSchema = desc.Types.Schemas[0]; } // Remove the includes. We gonna re-add them later in this operation. typesSchema.Includes.Clear(); } else { typesSchema = new XmlSchema(); } // Add imports to the types section resolved above. foreach (SchemaImport import in serviceInterfaceContract.Imports) { XmlSchemaExternal importedSchema = null; if (import.SchemaNamespace == null || import.SchemaNamespace == "") { importedSchema = new XmlSchemaInclude(); } else { importedSchema = new XmlSchemaImport(); ((XmlSchemaImport)importedSchema).Namespace = import.SchemaNamespace; } if (serviceInterfaceContract.UseAlternateLocationForImports) { importedSchema.SchemaLocation = import.AlternateLocation; } else { importedSchema.SchemaLocation = import.SchemaLocation; } typesSchema.Includes.Add(importedSchema); } // If we are not round-tripping we have to link the types schema we just created to // the service description. if (!isRoundTrip) { // Finally add the type schema to the ServiceDescription.Types.Schemas collection. desc.Types.Schemas.Add(typesSchema); } }
private void Write12_XmlSchemaInclude(string n, string ns, XmlSchemaInclude o, bool isNullable, bool needType) { if (o == null) { if (isNullable) { base.WriteNullTagLiteral(n, ns); } } else { if (!needType && !(o.GetType() == typeof(XmlSchemaInclude))) { throw base.CreateUnknownTypeException(o); } base.EscapeName = false; base.WriteStartElement(n, ns, o, false, o.Namespaces); if (needType) { base.WriteXsiType("XmlSchemaInclude", "http://www.w3.org/2001/XMLSchema"); } base.WriteAttribute("schemaLocation", "", o.SchemaLocation); base.WriteAttribute("id", "", o.Id); XmlAttribute[] unhandledAttributes = o.UnhandledAttributes; if (unhandledAttributes != null) { for (int i = 0; i < unhandledAttributes.Length; i++) { XmlAttribute node = unhandledAttributes[i]; base.WriteXmlAttribute(node, o); } } this.Write11_XmlSchemaAnnotation("annotation", "http://www.w3.org/2001/XMLSchema", o.Annotation, false, false); base.WriteEndElement(o); } }
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); } }
/// <summary> /// Generates the WSDL file for a specified <see cref="InterfaceContract"/>. /// </summary> /// <param name="serviceInterfaceContract"> /// <see cref="InterfaceContract"/> to use for the WSDL generation. /// </param> /// <param name="wsdlSaveLocation">Location to save the generated WSDL file.</param> /// <param name="xmlComment">XML comment to add to the top of the WSDL file.</param> /// <param name="wsdlLocation">Path of an existing WSDL file to overwrite with the generated /// WSDL file.</param> /// <returns>The path of the WSDL file generated.</returns> /// <remarks> /// This methods loads the information, it receive in a <see cref="InterfaceContract"/> to /// a <see cref="System.Web.Services.Description.ServiceDescription"/> class, which is later /// used to generate the WSDL file. The loading process takes place in several steps. <br></br> /// 1. Load the basic meta data from <see cref="InterfaceContract"/>.<br></br> /// 2. Load the schema imports in the <see cref="SchemaImports"/> collection.<br></br> /// 3. Load the messages in <see cref="OperationsCollection"/>.<br></br> /// 4. Create the WSDL Port Type.<br></br> /// 5. Add each operation and it's corresponding in/out messages to the Port Type.<br></br> /// 6. Create a WSDL Binding section and add OperationBinding for each operation.<br></br> /// 7. Generate the WSDL 'service' tags if required.<br></br> /// 8. Finally write the file to the output stream.<br></br> /// /// This method generates <see cref="WsdlGenerationException"/> exception, if it fails to create the WSDL file. /// If a file is specified to overwrite with the new file, the original file is restored in case of /// a failure. /// </remarks> public static string GenerateWsdl(InterfaceContract serviceInterfaceContract, string wsdlSaveLocation, string xmlComment, string wsdlLocation) { System.Web.Services.Description.ServiceDescription desc = null; string serviceAttributeName = ""; string bindingName = ""; string serviceName = ""; string portTypeName = ""; // Load the existing WSDL if one specified. if (wsdlLocation != null) { #region Round-tripping desc = System.Web.Services.Description.ServiceDescription.Read(wsdlLocation); // Read the existing name values. serviceAttributeName = desc.Name; bindingName = desc.Bindings[0].Name; portTypeName = desc.PortTypes[0].Name; // Check whether we have a service element and save it's name for the // future use. if (desc.Services.Count > 0) { serviceName = desc.Services[0].Name; } else { serviceName = serviceInterfaceContract.ServiceName + "Port"; ; } // Check for the place which has the Service name and assign the new value // appropriatly. if (serviceAttributeName != null && serviceAttributeName != "") { serviceAttributeName = serviceInterfaceContract.ServiceName; } else if (serviceName != null && serviceName != "") { // If the user has selected to remove the service element, // use the service name in the attribute by default. if (serviceInterfaceContract.NeedsServiceElement) { serviceName = serviceInterfaceContract.ServiceName; } else { serviceAttributeName = serviceInterfaceContract.ServiceName; } } else if (bindingName != null && bindingName != "") { bindingName = serviceInterfaceContract.ServiceName; } // Clear the service description. But do not clear the types definitions. desc.Extensions.Clear(); desc.Bindings.Clear(); desc.Documentation = ""; desc.Imports.Clear(); desc.Messages.Clear(); desc.PortTypes.Clear(); desc.RetrievalUrl = ""; if (desc.ServiceDescriptions != null) { desc.ServiceDescriptions.Clear(); } if (!serviceInterfaceContract.NeedsServiceElement) { desc.Services.Clear(); } #endregion } else { #region New WSDL desc = new System.Web.Services.Description.ServiceDescription(); // Create the default names. serviceAttributeName = serviceInterfaceContract.ServiceName; bindingName = serviceInterfaceContract.ServiceName; portTypeName = serviceInterfaceContract.ServiceName + "Interface"; serviceName = serviceInterfaceContract.ServiceName + "Port"; #endregion } #region Load the basic meta data. if (serviceAttributeName != null && serviceAttributeName != "") { desc.Name = serviceAttributeName; } desc.TargetNamespace = serviceInterfaceContract.ServiceNamespace; desc.Documentation = serviceInterfaceContract.ServiceDocumentation; #endregion #region Load the schema imports. XmlSchema typesSchema = null; // Are we round-tripping? Then we have to access the existing types // section. // Otherwise we just initialize a new XmlSchema for types. if (wsdlLocation != null) { typesSchema = desc.Types.Schemas[desc.TargetNamespace]; // if we don't have a types section belonging to the same namespace as service description // we take the first types section available. if (typesSchema == null) { typesSchema = desc.Types.Schemas[0]; } // Remove the includes. We gonna re-add them later in this operation. typesSchema.Includes.Clear(); } else { typesSchema = new XmlSchema(); } // Add imports to the types section resolved above. foreach (SchemaImport import in serviceInterfaceContract.Imports) { XmlSchemaExternal importedSchema = null; if (import.SchemaNamespace == null || import.SchemaNamespace == "") { importedSchema = new XmlSchemaInclude(); } else { importedSchema = new XmlSchemaImport(); ((XmlSchemaImport)importedSchema).Namespace = import.SchemaNamespace; } if (serviceInterfaceContract.UseAlternateLocationForImports) { importedSchema.SchemaLocation = import.AlternateLocation; } else { importedSchema.SchemaLocation = import.SchemaLocation; } typesSchema.Includes.Add(importedSchema); } // If we are not round-tripping we have to link the types schema we just created to // the service description. if (wsdlLocation == null) { // Finally add the type schema to the ServiceDescription.Types.Schemas collection. desc.Types.Schemas.Add(typesSchema); } #endregion #region Load the messages in all the operations MessageCollection msgs = desc.Messages; foreach (Operation op in serviceInterfaceContract.OperationsCollection) { foreach (Message msg in op.MessagesCollection) { FxMessage tempMsg = new FxMessage(); tempMsg.Name = msg.Name; tempMsg.Documentation = msg.Documentation; MessagePart msgPart = new MessagePart(); msgPart.Name = Constants.DefaultMessagePartName; msgPart.Element = new XmlQualifiedName(msg.Element.ElementName, msg.Element.ElementNamespace); tempMsg.Parts.Add(msgPart); msgs.Add(tempMsg); } foreach (Message msg in op.Faults) { Message messageName = msg; if (msgs.OfType<FxMessage>().Any(m => m.Name == messageName.Name)) continue; FxMessage tempMsg = new FxMessage(); tempMsg.Name = msg.Name; tempMsg.Documentation = msg.Documentation; MessagePart msgPart = new MessagePart(); msgPart.Name = Constants.FaultMessagePartName; msgPart.Element = new XmlQualifiedName(msg.Element.ElementName, msg.Element.ElementNamespace); tempMsg.Parts.Add(msgPart); msgs.Add(tempMsg); } } #endregion #region Create the Port Type PortTypeCollection portTypes = desc.PortTypes; PortType portType = new PortType(); portType.Name = portTypeName; portType.Documentation = serviceInterfaceContract.ServiceDocumentation; // Add each operation and it's corresponding in/out messages to the WSDL Port Type. foreach (Operation op in serviceInterfaceContract.OperationsCollection) { FxOperation tempOperation = new FxOperation(); tempOperation.Name = op.Name; tempOperation.Documentation = op.Documentation; int i = 0; OperationInput operationInput = new OperationInput(); operationInput.Message = new XmlQualifiedName(op.MessagesCollection[i].Name, desc.TargetNamespace); tempOperation.Messages.Add(operationInput); if (op.Mep == Mep.RequestResponse) { OperationOutput operationOutput = new OperationOutput(); operationOutput.Message = new XmlQualifiedName(op.MessagesCollection[i + 1].Name, desc.TargetNamespace); tempOperation.Messages.Add(operationOutput); } foreach (Message fault in op.Faults) { OperationFault operationFault = new OperationFault(); operationFault.Name = fault.Name; operationFault.Message = new XmlQualifiedName(fault.Name, desc.TargetNamespace); tempOperation.Faults.Add(operationFault); } portType.Operations.Add(tempOperation); i++; } portTypes.Add(portType); #endregion // Here we have a list of WCF endpoints. // Currently we populate this list with only two endpoints that has default // BasicHttpBinding and default NetTcpBinding. List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>(); BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(basicHttpBinding)); // BDS (10/22/2007): Commented out the TCP binding generation as we are not going to support this feature // in this version. //NetTcpBinding netTcpBinding = new NetTcpBinding(); //endpoints.Add(ServiceEndpointFactory<IDummyContract>.CreateServiceEndpoint(netTcpBinding)); // Now, for each endpoint we have to create a binding in our service description. foreach (ServiceEndpoint endpoint in endpoints) { // Create a WSDL BindingCollection. BindingCollection bindings = desc.Bindings; System.Web.Services.Description.Binding binding = new System.Web.Services.Description.Binding(); binding.Name = endpoint.Name.Replace(Constants.InternalContractName, portTypeName); binding.Type = new XmlQualifiedName(portType.Name, desc.TargetNamespace); // Create Operation binding for each operation and add it the the BindingCollection. foreach (Operation op in serviceInterfaceContract.OperationsCollection) { // SOAP 1.1 Operation bindings. OperationBinding operationBinding1 = new OperationBinding(); operationBinding1.Name = op.Name; InputBinding inputBinding1 = new InputBinding(); object bodyBindingExtension = GetSoapBodyBinding(endpoint.Binding); if (bodyBindingExtension != null) { inputBinding1.Extensions.Add(bodyBindingExtension); } operationBinding1.Input = inputBinding1; // Faults. foreach (Message fault in op.Faults) { FaultBinding faultBinding = new FaultBinding(); faultBinding.Name = fault.Name; SoapFaultBinding faultBindingExtension = GetFaultBodyBinding(endpoint.Binding); if (faultBindingExtension != null) { faultBindingExtension.Name = fault.Name; faultBinding.Extensions.Add(faultBindingExtension); } operationBinding1.Faults.Add(faultBinding); } // Input message. // Look up the message headers for each Message and add them to the current binding. foreach (MessageHeader inHeader in op.MessagesCollection[0].HeadersCollection) { object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, inHeader.Message, desc.TargetNamespace); if (headerBindingExtension != null) { inputBinding1.Extensions.Add(headerBindingExtension); } } if (op.Mep == Mep.RequestResponse) { // Output message. OutputBinding outputBinding1 = new OutputBinding(); object responseBodyBindingExtension = GetSoapBodyBinding(endpoint.Binding); if (responseBodyBindingExtension != null) { outputBinding1.Extensions.Add(responseBodyBindingExtension); } operationBinding1.Output = outputBinding1; // Look up the message headers for each Message and add them to the current binding. foreach (MessageHeader outHeader in op.MessagesCollection[1].HeadersCollection) { object headerBindingExtension = GetSoapHeaderBinding(endpoint.Binding, outHeader.Message, desc.TargetNamespace); if (headerBindingExtension != null) { outputBinding1.Extensions.Add(headerBindingExtension); } } } string action = desc.TargetNamespace + ":" + op.Input.Name; object operationBindingExtension = GetSoapOperationBinding(endpoint.Binding, action); if (operationBindingExtension != null) { operationBinding1.Extensions.Add(operationBindingExtension); } binding.Operations.Add(operationBinding1); // End of SOAP 1.1 operation bindings. } object soapBindingExtension = GetSoapBinding(endpoint.Binding); if (soapBindingExtension != null) { binding.Extensions.Add(soapBindingExtension); } bindings.Add(binding); } // Generate <service> element optionally - sometimes necessary for interop reasons if (serviceInterfaceContract.NeedsServiceElement) { Service defaultService = null; if (wsdlLocation == null || desc.Services.Count == 0) { // Create a new service element. defaultService = new Service(); defaultService.Name = serviceName; foreach (ServiceEndpoint endpoint in endpoints) { if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap11) { Port defaultPort = new Port(); defaultPort.Name = serviceInterfaceContract.ServiceName + "Port"; defaultPort.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace); SoapAddressBinding defaultSoapAddressBinding = new SoapAddressBinding(); defaultSoapAddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName); defaultPort.Extensions.Add(defaultSoapAddressBinding); defaultService.Ports.Add(defaultPort); } else if (endpoint.Binding.MessageVersion.Envelope == EnvelopeVersion.Soap12) { Port soap12Port = new Port(); soap12Port.Name = serviceInterfaceContract.ServiceName + "SOAP12Port"; soap12Port.Binding = new XmlQualifiedName(endpoint.Name.Replace(Constants.InternalContractName, portTypeName), desc.TargetNamespace); Soap12AddressBinding soap12AddressBinding = new Soap12AddressBinding(); soap12AddressBinding.Location = GetDefaultEndpoint(endpoint.Binding, serviceInterfaceContract.ServiceName); soap12Port.Extensions.Add(soap12AddressBinding); defaultService.Ports.Add(soap12Port); } } desc.Services.Add(defaultService); } else { defaultService = desc.Services[0]; defaultService.Name = serviceName; } } // Generate the WSDL file. string fileName = string.Empty; string bkFileName = string.Empty; // Overwrite the existing file if one specified. if (wsdlLocation == null) { fileName = wsdlSaveLocation + @"\" + serviceInterfaceContract.ServiceName + ".wsdl"; } else { fileName = wsdlLocation; } // Backup existing file before proceeding. if (File.Exists(fileName)) { int index = 1; // Create the backup file name. // See whether the generated backup file name is already taken by an existing file and // generate a new file name. while (File.Exists(fileName + "." + index.ToString())) { index++; } bkFileName = fileName + "." + index.ToString(); // Backup the file. try { File.Copy(fileName, bkFileName); } catch (Exception ex) { throw new WsdlGenerationException("An error occured while trying to generate a WSDL. Failed to backup the existing WSDL file.", ex); } } StreamWriter writer1 = new StreamWriter(fileName); try { XmlTextWriter writer11 = new XmlTextWriter(writer1); writer11.Formatting = Formatting.Indented; writer11.Indentation = 2; writer11.WriteComment(xmlComment); // BDS: Added a new comment line with the date time of WSDL file. CultureInfo ci = new CultureInfo("en-US"); writer11.WriteComment(DateTime.Now.ToString("dddd", ci) + ", " + DateTime.Now.ToString("dd-MM-yyyy - hh:mm tt", ci)); XmlSerializer serializer1 = System.Web.Services.Description.ServiceDescription.Serializer; XmlSerializerNamespaces nsSer = new XmlSerializerNamespaces(); nsSer.Add("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); nsSer.Add("soap12", "http://schemas.xmlsoap.org/wsdl/soap12/"); nsSer.Add("xsd", "http://www.w3.org/2001/XMLSchema"); nsSer.Add("tns", desc.TargetNamespace); // Add the imported namespaces to the WSDL <description> element. for (int importIndex = 0; importIndex < serviceInterfaceContract.Imports.Count; importIndex++) { if (serviceInterfaceContract.Imports[importIndex].SchemaNamespace != null && serviceInterfaceContract.Imports[importIndex].SchemaNamespace != "") { nsSer.Add("import" + importIndex.ToString(), serviceInterfaceContract.Imports[importIndex].SchemaNamespace); } } // // Finally write the file to the output stram. serializer1.Serialize(writer11, desc, nsSer); // Close the stream and delete the backupfile. writer1.Close(); if (bkFileName != string.Empty) { File.Delete(bkFileName); } WsdlWorkshop workshop = new WsdlWorkshop(endpoints, fileName, portTypeName); workshop.BuildWsdl(); return fileName; } catch (Exception ex) { writer1.Close(); string message = ex.Message; if (ex.InnerException != null) { message += ex.InnerException.Message; } // Restore the original file. if (bkFileName != string.Empty) { try { File.Copy(bkFileName, fileName, true); File.Delete(bkFileName); } catch { throw new WsdlGenerationException( message + "\nFailed to restore the original file."); } } else if (File.Exists(fileName)) { File.Delete(fileName); } throw new WsdlGenerationException( message, ex); } }
//<include // id = ID // schemaLocation = anyURI // {any attributes with non-schema namespace . . .}> // Content: (annotation?) //</include> internal static XmlSchemaInclude Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaInclude include = new XmlSchemaInclude(); reader.MoveToElement(); if (reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h, "Should not happen :1: XmlSchemaInclude.Read, name=" + reader.Name, null); reader.SkipToEnd(); return(null); } include.LineNumber = reader.LineNumber; include.LinePosition = reader.LinePosition; include.SourceUri = reader.BaseURI; while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { include.Id = reader.Value; } else if (reader.Name == "schemaLocation") { include.SchemaLocation = reader.Value; } else if ((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h, reader.Name + " is not a valid attribute for include", null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader, include); } } reader.MoveToElement(); if (reader.IsEmptyElement) { return(include); } // Content: (annotation?) int level = 1; while (reader.ReadNextElement()) { if (reader.NodeType == XmlNodeType.EndElement) { if (reader.LocalName != xmlname) { error(h, "Should not happen :2: XmlSchemaInclude.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) { include.Annotation = annotation; } continue; } reader.RaiseInvalidElementError(); } return(include); }
public void AddEditInvalidIncludeSchema(String testFile, int expCountGT, int expCountGE) { string xsd = Path.Combine(testData, testFile); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), null); XmlSchema Schema1 = ss.Add(Schema); ValidateSchemaSet(ss, 1, false, 0, 0, 0, "Validation after add"); ss.Compile(); ValidateSchemaSet(ss, 1, true, expCountGT, expCountGE, 0, "Validation after add/comp"); XmlSchemaInclude inc = new XmlSchemaInclude(); inc.SchemaLocation = "include_v2.xsd"; Schema1.Includes.Add(inc); try { ss.Reprocess(Schema1); Assert.True(false); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); } ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr"); try { ss.Compile(); Assert.True(false); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); } ValidateSchemaSet(ss, 1, false, 1, 0, 0, "Validation after repr/comp"); try { ValidateWithSchemaInfo(ss); Assert.True(false); } catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); } return; }
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(); } }
public static void SaveSchema(this ModuleConfiguration moduleConfiguration, string fileName, string[] list) { fileName = Path.ChangeExtension(fileName, "xsd"); using (StreamWriter writer = new StreamWriter(fileName)) { XmlSchema xsd = new XmlSchema(); xsd.Namespaces.Add("", @"urn:configuration-schema"); xsd.Namespaces.Add("xsd", @"http://www.w3.org/2001/XMLSchema"); xsd.Namespaces.Add("config", @"urn:configuration-schema"); xsd.TargetNamespace = @"urn:configuration-schema"; xsd.ElementFormDefault = XmlSchemaForm.Qualified; XmlSchemaInclude include = new XmlSchemaInclude(); include.SchemaLocation = "CommonConfig.xsd"; xsd.Includes.Add(include); foreach (string item in list) { include = new XmlSchemaInclude(); include.SchemaLocation = item + @"Config.xsd"; xsd.Includes.Add(include); } xsd.Write(writer); } }
public void v12() { bWarningCallback = false; bErrorCallback = false; XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema Schema1 = sc.Add(null, TestData._Root + "include_v1_a.xsd"); CError.Compare(sc.Count, 1, "Count after add"); CError.Compare(sc.Contains(Schema1), true, "Contains after add"); sc.Compile(); CError.Compare(sc.Count, 1, "Count after add/comp"); CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp"); ///edit XmlSchemaInclude inc = new XmlSchemaInclude(); inc.SchemaLocation = "include_v2.xsd"; Schema1.Includes.Add(inc); sc.Reprocess(Schema1); ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after edit/reprocess"); CError.Compare(bWarningCallback, false, "Warning repr"); CError.Compare(bErrorCallback, true, "Error repr"); sc.Compile(); ValidateSchemaSet(sc, 1, false, 1, 0, 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; }
private void Compile(XmlSchemas userSchemas) { var parent = new XmlSchema(); foreach (XmlSchema userSchema in userSchemas) { if (userSchema.TargetNamespace != null && userSchema.TargetNamespace.Length == 0) { userSchema.TargetNamespace = null; } if (userSchema.TargetNamespace == parent.TargetNamespace) { var item = new XmlSchemaInclude {Schema = userSchema}; parent.Includes.Add(item); } else { var import = new XmlSchemaImport {Namespace = userSchema.TargetNamespace, Schema = userSchema}; parent.Includes.Add(import); } } AddFakeSchemas(parent, userSchemas); try { var schemas = new XmlSchemaSet(); schemas.ValidationEventHandler += ValidationCallback; schemas.Add(parent); if (schemas.Count == 0) { //warn of error } } catch (Exception) { //warn of error throw; } }