public static int Main(string[] args) { ThisAssembly = Assembly.GetExecutingAssembly(); XmlSchemaSet set = new XmlSchemaSet(); ValidationEventHandler veh = new ValidationEventHandler(ValidationCallback); set.ValidationEventHandler += veh; string csFileName = string.Empty; string configFileName = null; string assemblyName = string.Empty; bool fSourceNameProvided = false; bool xmlSerializable = false; bool nameMangler2 = false; if (args.Length == 0) { PrintHelp(); return(0); } for (int i = 0; i < args.Length; i++) { string arg = args[i]; string value = string.Empty; bool argument = false; if (arg.StartsWith("/") || arg.StartsWith("-")) { argument = true; int colonPos = arg.IndexOf(":"); if (colonPos != -1) { value = arg.Substring(colonPos + 1); arg = arg.Substring(0, colonPos); } } arg = arg.ToLower(CultureInfo.InvariantCulture); if (!argument) { try { set.Add(null, CreateReader(arg)); } catch (Exception e) { PrintErrorMessage(e.ToString()); return(1); } if (csFileName == string.Empty) { csFileName = Path.ChangeExtension(arg, "cs"); } } else if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help")) { PrintHelp(); return(0); } else if (ArgumentMatch(arg, "config")) { configFileName = value; } else if (ArgumentMatch(arg, "filename")) { csFileName = value; fSourceNameProvided = true; } else if (ArgumentMatch(arg, "enableservicereference")) { xmlSerializable = true; } else if (ArgumentMatch(arg, "lib")) { assemblyName = value; } else if (ArgumentMatch(arg, "namemangler2")) { nameMangler2 = true; } } if (assemblyName != string.Empty && !fSourceNameProvided) { //only generate assembly csFileName = string.Empty; } set.Compile(); set.ValidationEventHandler -= veh; if (set.Count > 0 && set.IsCompiled) { /* * GenerateXObjects( * set, csFileName, configFileName, assemblyName, xmlSerializable, nameMangler2); */ try { GenerateXObjects( set, csFileName, configFileName, assemblyName, xmlSerializable, nameMangler2); } catch (Exception e) { PrintErrorMessage(e.ToString()); return(1); } } return(0); }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="RatingType"> XmlSchemaSimpleType RatingType = new XmlSchemaSimpleType(); RatingType.Name = "RatingType"; // <xs:restriction base="xs:number"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema"); // <xs:totalDigits value="2"/> XmlSchemaTotalDigitsFacet totalDigits = new XmlSchemaTotalDigitsFacet(); totalDigits.Value = "2"; restriction.Facets.Add(totalDigits); // <xs:fractionDigits value="1"/> XmlSchemaFractionDigitsFacet fractionDigits = new XmlSchemaFractionDigitsFacet(); fractionDigits.Value = "1"; restriction.Facets.Add(fractionDigits); RatingType.Content = restriction; schema.Items.Add(RatingType); // <xs:element name="movie"> XmlSchemaElement element = new XmlSchemaElement(); element.Name = "movie"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="rating" type="RatingType"/> XmlSchemaAttribute ratingAttribute = new XmlSchemaAttribute(); ratingAttribute.Name = "rating"; ratingAttribute.SchemaTypeName = new XmlQualifiedName("RatingType", ""); complexType.Attributes.Add(ratingAttribute); element.SchemaType = complexType; schema.Items.Add(element); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
static void Main(string[] args) { Assembly rimworld = Assembly.Load("Assembly-CSharp, Version=1.0.6955.24033, Culture=neutral, PublicKeyToken=null"); var defs = from type in rimworld.GetExportedTypes() where type.IsClass && !type.IsAbstract && typeof(Def).IsAssignableFrom(type) select type; XmlSchema schema = new XmlSchema { TargetNamespace = "https://github.com/kfish610/RimWorldSchema", ElementFormDefault = XmlSchemaForm.Qualified }; var defsRoot = new XmlSchemaElement { Name = "Defs" }; var defsType = new XmlSchemaComplexType(); defsRoot.SchemaType = defsType; var defsChoice = new XmlSchemaChoice() { MinOccurs = 1, MaxOccursString = "unbounded" }; defsType.Particle = defsChoice; schema.Items.Add(defsRoot); foreach (var def in defs) { Aliases.Add(def, "string"); } foreach (var def in defs) { defsChoice.Items.Add(new XmlSchemaElement() { Name = def.Name, SchemaType = Derive(def) }); } defsChoice.Items.Add(new XmlSchemaAny() { MinOccurs = 0, MaxOccursString = "unbounded", ProcessContents = XmlSchemaContentProcessing.Skip }); foreach (var type in types) { schema.Items.Insert(0, type); } XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler((_, e) => Console.WriteLine(e.Message)); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace(string.Empty, "https://github.com/kfish610/RimWorldSchema"); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); File.WriteAllText(@"schema.xsd", string.Empty); using StreamWriter file = new StreamWriter(@"schema.xsd"); compiledSchema.Write(file, nsmgr); }
[Test] // part of bug #670945 public void TwoSchemasInSameDocumentUri() { string xsd1 = @" <xs:schema targetNamespace='http://www.onvif.org/ver10/schema' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tt='http://www.onvif.org/ver10/schema'> <xs:complexType name='SystemDateTime'> <xs:sequence> <xs:element name='foobar' type='xs:string' minOccurs='0' /> <xs:element name='Extension' type='tt:SystemDateTimeExtension' minOccurs='0'/> </xs:sequence> <!-- xs:anyAttribute processContents='lax'/ --> </xs:complexType> <xs:complexType name='SystemDateTimeExtension'> <xs:sequence> <xs:any namespace='##any' processContents='lax' minOccurs='0' maxOccurs='unbounded'/> </xs:sequence> </xs:complexType> </xs:schema>"; string xsd2 = @" <xs:schema targetNamespace='http://www.onvif.org/ver10/device/wsdl' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tt='http://www.onvif.org/ver10/schema' xmlns:tds='http://www.onvif.org/ver10/device/wsdl' elementFormDefault='qualified'> <xs:element name='GetSystemDateAndTime'> <xs:complexType> <xs:sequence/> </xs:complexType> </xs:element> <xs:element name='GetSystemDateAndTimeResponse'> <xs:complexType> <xs:sequence> <xs:element name='SystemDateAndTime' type='tt:SystemDateTime' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; var xss = new XmlSchemaSet(); var xs1 = XmlSchema.Read(new StringReader(xsd1), null); xs1.SourceUri = "http://localhost:8080/dummy.wsdl"; xs1.LineNumber = 5; xss.Add(xs1); var xs2 = XmlSchema.Read(new StringReader(xsd2), null); xs2.SourceUri = "http://localhost:8080/dummy.wsdl"; xs2.LineNumber = 50; xss.Add(xs2); xss.Compile(); Assert.IsNotNull(xss.GlobalElements [new XmlQualifiedName("GetSystemDateAndTimeResponse", "http://www.onvif.org/ver10/device/wsdl")], "#1"); }
private void RetrieveSerializableSchema() { if (_needSchema) { _needSchema = false; if (_getSchemaMethod != null) { // get the type info if (_schemas == null) { _schemas = new XmlSchemaSet(); } object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; if (typeInfo != null) { if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsdType = (XmlSchemaType)typeInfo; // check if type is named _xsiType = _xsdType.QualifiedName; } else if (typeof(XmlQualifiedName).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsiType = (XmlQualifiedName)typeInfo; if (_xsiType.IsEmpty) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else { _any = true; } // make sure that user-specified schemas are valid _schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode); _schemas.Compile(); #if !XMLSERIALIZERGENERATOR // at this point we verified that the information returned by the IXmlSerializable is valid // Now check to see if the type was referenced before: // UNDONE check for the duplcate types if (!_xsiType.IsEmpty) { // try to find the type in the schemas collection if (_xsiType.Namespace != XmlSchema.Namespace) { ArrayList srcSchemas = (ArrayList)_schemas.Schemas(_xsiType.Namespace); if (srcSchemas.Count == 0) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } if (srcSchemas.Count > 1) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name)); } XmlSchema s = (XmlSchema)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } _xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType]; if (_xsdType == null) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); } _xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType; } } #endif } else { IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type); _schema = serializable.GetSchema(); if (_schema != null) { if (_schema.Id == null || _schema.Id.Length == 0) { throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type.FullName)); } } } } }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="ZipCodeType"> XmlSchemaSimpleType ZipCodeType = new XmlSchemaSimpleType(); ZipCodeType.Name = "ZipCodeType"; // <xs:restriction base="xs:string"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:pattern value="[0-9]{5}(-[0-9]{4})?"/> XmlSchemaPatternFacet pattern = new XmlSchemaPatternFacet(); pattern.Value = "[0-9]{5}(-[0-9]{4})?"; restriction.Facets.Add(pattern); ZipCodeType.Content = restriction; schema.Items.Add(ZipCodeType); // <xs:element name="Address"> XmlSchemaElement element = new XmlSchemaElement(); element.Name = "Address"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="ZipCode" type="ZipCodeType"/> XmlSchemaAttribute ZipCodeAttribute = new XmlSchemaAttribute(); ZipCodeAttribute.Name = "ZipCode"; ZipCodeAttribute.SchemaTypeName = new XmlQualifiedName("ZipCodeType", ""); complexType.Attributes.Add(ZipCodeAttribute); element.SchemaType = complexType; schema.Items.Add(element); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
public void Generate(UblGeneratorOptions options) { _options = options; options.Validate(); var baseInputDirectory = options.XsdBasePath; var commonDirectory = Path.Combine(baseInputDirectory, "common"); var xmldsigFilename = new DirectoryInfo(commonDirectory).GetFiles("UBL-xmldsig-core-schema-*.xsd").Single().FullName; var maindocDirectory = Path.Combine(baseInputDirectory, "maindoc"); var maindocfiles = new DirectoryInfo(maindocDirectory).GetFiles("*.xsd").ToList(); // var extrafiles = new DirectoryInfo(commonDirectory).GetFiles("UBL-CommonSignatureComponents*.xsd").ToList(); // var maindocfiles = new DirectoryInfo(maindocDirectory).GetFiles("UBL-Order-2.1.xsd").ToList(); // maindocfiles.Add(new DirectoryInfo(maindocDirectory).GetFiles("UBL-BaseDocument-*.xsd").Single()); var maindocSchemaSet = new XmlSchemaSet(); var nameTable = new NameTable(); var readerSettings = new XmlReaderSettings { ValidationType = ValidationType.Schema, DtdProcessing = DtdProcessing.Parse, NameTable = nameTable, }; using (var reader = XmlReader.Create(xmldsigFilename, readerSettings)) { var schema = XmlSchema.Read(reader, null); maindocSchemaSet.Add(schema); } foreach (var maindocfile in maindocfiles) { using (var reader = XmlReader.Create(maindocfile.FullName, readerSettings)) { var schema = XmlSchema.Read(reader, null); maindocSchemaSet.Add(schema); } } //foreach (var extrafile in extrafiles) //{ // using (var reader = XmlReader.Create(extrafile.FullName, readerSettings)) // { // var schema = XmlSchema.Read(reader, null); // maindocSchemaSet.Add(schema); // } //} maindocSchemaSet.Compile(); foreach (var schemaFixer in _schemaFixers) { schemaFixer(maindocSchemaSet); maindocSchemaSet.Compile(); } var rootNamespaces = maindocSchemaSet.Schemas().OfType <XmlSchema>() .Where(x => x.SourceUri.Contains("maindoc")) .Select(x => x.TargetNamespace) .Concat(new[] { Namespaces.Xmldsig, Namespaces.Sac, Namespaces.Csc, Namespaces.Xades141, }); var tempCodeNamespace = CreateCodeNamespace(maindocSchemaSet, rootNamespaces.ToArray()); _globalCodeFixer.Fix(tempCodeNamespace); var codeDeclsBySchema = (from t in tempCodeNamespace.Types.Cast <CodeTypeDeclaration>() group t by t.GetSchema() into g select g) .ToDictionary(k => k.Key, v => v.ToArray()); var codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); var codegenOptions = new CodeGeneratorOptions() { BracingStyle = "C", IndentString = " ", BlankLinesBetweenMembers = true, VerbatimOrder = true }; var namespaceProvider = new CodeNamespaceProvider(maindocSchemaSet, options); foreach (var schema in maindocSchemaSet.Schemas().Cast <XmlSchema>()) { var codeNamespace = namespaceProvider.CreateCodeNamespace(schema.TargetNamespace); if (codeDeclsBySchema.ContainsKey(schema)) { codeNamespace.Types.AddRange(codeDeclsBySchema[schema]); } if (codeNamespace.Types.Count == 0) { continue; } _namespacedCodeFixer.Fix(codeNamespace); var sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { codeProvider.GenerateCodeFromNamespace(codeNamespace, sw, codegenOptions); } sb = sb.Replace("Namespace=\"", "Namespace = \""); var fileContent = sb.ToString(); var lines = fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); foreach (var fixer in _conditionalFeatureFixers) { int lineNum = 0; while (true) { lineNum = fixer(lines, lineNum); if (lineNum < 0) { break; } } } sb = new StringBuilder(string.Join(Environment.NewLine, lines)); var xsdFilename = new Uri(schema.SourceUri).LocalPath; var fi = new FileInfo(xsdFilename); var foldername = namespaceProvider.GetNamespaceFolderName(schema); string targetPath = Path.Combine(options.OutputPath, foldername); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var outputFile = Path.Combine(targetPath, Path.ChangeExtension(fi.Name, ".generated.cs")); using (var ofile = File.CreateText(outputFile)) { ofile.Write(sb); } } }
static void Main(string[] args) { // Add the customer schema to a new XmlSchemaSet and compile it. // Any schema validation warnings and errors encountered reading or // compiling the schema are handled by the ValidationEventHandler delegate. XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add("http://www.tempuri.org", "customer.xsd"); schemaSet.Compile(); // Retrieve the compiled XmlSchema object from the XmlSchemaSet // by iterating over the Schemas property. XmlSchema customerSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { customerSchema = schema; } // Create the PhoneNumber element. XmlSchemaElement phoneElement = new XmlSchemaElement(); phoneElement.Name = "PhoneNumber"; // Create the xs:string simple type restriction. XmlSchemaSimpleType phoneType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // Add a pattern facet to the restriction. XmlSchemaPatternFacet phonePattern = new XmlSchemaPatternFacet(); phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)"; restriction.Facets.Add(phonePattern); // Add the restriction to the Content property of the simple type // and the simple type to the SchemaType of the PhoneNumber element. phoneType.Content = restriction; phoneElement.SchemaType = phoneType; // Iterate over each XmlSchemaElement in the Values collection // of the Elements property. foreach (XmlSchemaElement element in customerSchema.Elements.Values) { // If the qualified name of the element is "Customer", // get the complex type of the Customer element // and the sequence particle of the complex type. if (element.QualifiedName.Name.Equals("Customer")) { XmlSchemaComplexType customerType = element.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence sequence = customerType.Particle as XmlSchemaSequence; // Add the new PhoneNumber element to the sequence. sequence.Items.Add(phoneElement); } } // Reprocess and compile the modified XmlSchema object and write it to the console. schemaSet.Reprocess(customerSchema); schemaSet.Compile(); customerSchema.Write(Console.Out); }
public bool Validate(out string tedXml) { if (_notice.IsCorrigendum) { if (_notice.Parent == null) { _validationErrors.Add("Corrigendum notice should have parent set. Parent is null."); tedXml = string.Empty; return(false); } // Validate that the notice is not expired bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var localFinnishTimezone = isWindows ? TimeZoneInfo.FindSystemTimeZoneById("E. Europe Standard Time") : TimeZoneInfo.FindSystemTimeZoneById("Europe/Helsinki"); var timeInLocalTimezone = TimeZoneInfo.ConvertTime(DateTime.UtcNow, localFinnishTimezone); var expirationTime = _notice.Parent.TenderingInformation?.TendersOrRequestsToParticipateDueDateTime; if (expirationTime.HasValue && expirationTime.Value <= timeInLocalTimezone) { _validationErrors.Add($"Corrigendum notice cannot be made to notice that has expired TendersOrRequestsToParticipateDueDateTime: ExpirationTime: {expirationTime}, Current local time: {timeInLocalTimezone}"); tedXml = string.Empty; return(false); } } if (_notice.Type.IsNational()) { // Do not validate national notices tedXml = null; return(true); } var path = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory); var schema = new XmlSchemaSet { XmlResolver = new XmlUrlResolver() }; var nameSpace = XmlnsGeneral; var isDefence = _notice.Type.IsDefence(); if (isDefence) { schema.Add(XmlnsDefence.ToString(), Path.Combine(path, "Validators", "TedSchema", "208Defence", "TED_ESENDERS.xsd")); nameSpace = XmlnsDefence; } else { schema.Add(XmlnsGeneral.ToString(), Path.Combine(path, "Validators", "TedSchema", "209General", "TED_ESENDERS.xsd")); } schema.Compile(); var noticeContract = _mapper.Map <NoticeContract>(_notice); var parent = _notice.Parent != null?_mapper.Map <NoticeContract>(_notice.Parent) : new NoticeContract(); var xDoc = new TedNoticeFactory(noticeContract, parent, "Validator", "*****@*****.**", "TEDEXXXX", _translationProvider).CreateDocument(); var copy = new XDocument(xDoc); if (isDefence) { // Add namespace attribute to fix the validation copy = TedHelpers.SetRootNamespace(copy); } copy.Validate(schema, (sender, e) => { _validationErrors.Add(e.Message + "\n"); }); // We don't want to send the login part in the response. if (isDefence) { // defense version does not use root namespace in ted xml var descendants = xDoc.Descendants("FORM_SECTION"); tedXml = string.Join("\n", descendants); } else { var descendants = xDoc.Descendants(nameSpace + "FORM_SECTION"); tedXml = string.Join("\n", descendants); } var teSchemaValid = Valid(!_validationErrors.Any(), "TED message formed:\n" + tedXml); return(ValidateAll(teSchemaValid, ValidateValueFields(noticeContract))); }
/// <summary> /// Initiate code generation process /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns></returns> internal static Result <CodeNamespace> Process(GeneratorParams generatorParams) { var ns = new CodeNamespace(); XmlReader reader = null; try { #region Set generation context GeneratorContext.GeneratorParams = generatorParams; #endregion #region Get XmlTypeMapping XmlSchema xsd; var schemas = new XmlSchemas(); reader = XmlReader.Create(generatorParams.InputFilePath); xsd = XmlSchema.Read(reader, new ValidationEventHandler(Validate)); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder; var exporter = new XmlCodeExporter(ns); var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in xsd.Elements.Values) { var mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } //Fixes/handles http://xsd2code.codeplex.com/WorkItem/View.aspx?WorkItemId=6941 foreach (XmlSchemaComplexType complex in xsd.Items.OfType <XmlSchemaComplexType>()) { var mapping = importer.ImportSchemaType(complex.QualifiedName); exporter.ExportTypeMapping(mapping); } #endregion #region Execute extensions var getExtensionResult = GeneratorFactory.GetCodeExtension(generatorParams); if (!getExtensionResult.Success) { return(new Result <CodeNamespace>(ns, false, getExtensionResult.Messages)); } var ext = getExtensionResult.Entity; ext.Process(ns, xsd); #endregion Execute extensions return(new Result <CodeNamespace>(ns, true)); } catch (Exception e) { return(new Result <CodeNamespace>(ns, false, e.Message, MessageType.Error)); } finally { if (reader != null) { reader.Close(); } } }
/// <include file='doc\XmlSchemas.uex' path='docs/doc[@for="XmlSchemas.Compile"]/*' /> public void Compile(ValidationEventHandler handler, bool fullCompile) { if (isCompiled) { return; } foreach (XmlSchema s in delayedSchemas.Values) { Merge(s); } delayedSchemas.Clear(); if (fullCompile) { schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = null; schemaSet.ValidationEventHandler += handler; foreach (XmlSchema s in References.Values) { schemaSet.Add(s); } int schemaCount = schemaSet.Count; foreach (XmlSchema s in List) { if (!SchemaSet.Contains(s)) { schemaSet.Add(s); schemaCount++; } } if (!SchemaSet.Contains(XmlSchema.Namespace)) { AddReference(XsdSchema); schemaSet.Add(XsdSchema); schemaCount++; } if (!SchemaSet.Contains(XmlReservedNs.NsXml)) { AddReference(XmlSchema); schemaSet.Add(XmlSchema); schemaCount++; } schemaSet.Compile(); schemaSet.ValidationEventHandler -= handler; isCompiled = schemaSet.IsCompiled && schemaCount == schemaSet.Count; } else { try { XmlNameTable nameTable = new System.Xml.NameTable(); Preprocessor prep = new Preprocessor(nameTable, new SchemaNames(nameTable), null); prep.XmlResolver = null; prep.SchemaLocations = new Hashtable(); prep.ChameleonSchemas = new Hashtable(); foreach (XmlSchema schema in SchemaSet.Schemas()) { prep.Execute(schema, schema.TargetNamespace, true); } } catch (XmlSchemaException e) { throw CreateValidationException(e, e.Message); } } }
private static void Main(string[] args) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add("http://www.w3.org/2001/XMLSchema", "C:\\Chandan\\myxsdfile.xsd"); schemaSet.Compile(); XmlSchema xmlSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { xmlSchema = schema; } DataSet myDS = new DataSet(); myDS.ReadXmlSchema("C:\\Chandan\\myxsdfile.xsd"); foreach (object item in xmlSchema.Items) { XmlSchemaElement schemaElement = item as XmlSchemaElement; XmlSchemaComplexType complexType = item as XmlSchemaComplexType; if (schemaElement != null) { Console.Out.WriteLine("Schema Element: {0}", schemaElement.Name); XmlSchemaType schemaType = schemaElement.SchemaType; XmlSchemaComplexType schemaComplexType = schemaType as XmlSchemaComplexType; if (schemaComplexType != null) { XmlSchemaParticle particle = schemaComplexType.Particle; XmlSchemaSequence sequence = particle as XmlSchemaSequence; if (sequence != null) { foreach (XmlSchemaElement childElement in sequence.Items) { Console.Out.WriteLine(" Element/Type: {0}:{1}", childElement.Name, childElement.SchemaTypeName.Name); } } if (schemaComplexType.AttributeUses.Count > 0) { IDictionaryEnumerator enumerator = schemaComplexType.AttributeUses.GetEnumerator(); while (enumerator.MoveNext()) { XmlSchemaAttribute attribute = (XmlSchemaAttribute)enumerator.Value; Console.Out.WriteLine(" Attribute/Type: {0}", attribute.Name); } } } } else if (complexType != null) { Console.Out.WriteLine("Complex Type: {0}", complexType.Name); OutputElements(complexType.Particle); if (complexType.AttributeUses.Count > 0) { IDictionaryEnumerator enumerator = complexType.AttributeUses.GetEnumerator(); while (enumerator.MoveNext()) { XmlSchemaAttribute attribute = (XmlSchemaAttribute)enumerator.Value; Console.Out.WriteLine(" Attribute/Type: {0}", attribute.Name); } } } Console.Out.WriteLine(); } Console.Out.WriteLine(); Console.In.ReadLine(); }
public void v51(object param0, object param1, object param2, object param3) { bWarningCallback = false; bErrorCallback = false; string mainFile = TestData._Root + param0.ToString(); string include1 = TestData._Root + param1.ToString(); string include2 = TestData._Root + param2.ToString(); string xmlFile = TestData._Root + "bug382119.xml"; bool IsImport = (bool)param3; XmlSchemaSet set1 = new XmlSchemaSet(); set1.XmlResolver = new XmlUrlResolver(); set1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema includedSchema = set1.Add(null, include1); set1.Compile(); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema mainSchema = set.Add(null, mainFile); set.Compile(); _output.WriteLine("First validation ***************"); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; XmlReader reader = XmlReader.Create(xmlFile, settings); while (reader.Read()) { } CError.Compare(bWarningCallback, false, "Warning count mismatch"); CError.Compare(bErrorCallback, true, "Error count mismatch"); if (IsImport == true) { set.Remove(((XmlSchemaExternal)mainSchema.Includes[0]).Schema); } _output.WriteLine("re-setting include"); XmlSchema reParsedInclude = LoadSchema(include2, include1); ((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude; _output.WriteLine("Calling reprocess"); set.Reprocess(mainSchema); set.Compile(); bWarningCallback = false; bErrorCallback = false; _output.WriteLine("Second validation ***************"); settings.Schemas = set; reader = XmlReader.Create(xmlFile, settings); while (reader.Read()) { } CError.Compare(bWarningCallback, false, "Warning count mismatch"); CError.Compare(bErrorCallback, false, "Error count mismatch"); //Editing the include again _output.WriteLine("Re-adding include to set1"); XmlSchema reParsedInclude2 = LoadSchema(include1, include1); set1.Remove(includedSchema); set1.Add(reParsedInclude2); set1.Compile(); if (IsImport == true) { set.Remove(((XmlSchemaExternal)mainSchema.Includes[0]).Schema); } ((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude2; set.Reprocess(mainSchema); set.Compile(); bWarningCallback = false; bErrorCallback = false; _output.WriteLine("Third validation, Expecting errors ***************"); settings.Schemas = set; reader = XmlReader.Create(xmlFile, settings); while (reader.Read()) { } CError.Compare(bWarningCallback, false, "Warning count mismatch"); CError.Compare(bErrorCallback, true, "Error count mismatch"); return; }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="OrderQuantityType"> XmlSchemaSimpleType OrderQuantityType = new XmlSchemaSimpleType(); OrderQuantityType.Name = "OrderQuantityType"; // <xs:restriction base="xs:int"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema"); // <xs:minInclusive value="5"/> XmlSchemaMinInclusiveFacet minInclusive = new XmlSchemaMinInclusiveFacet(); minInclusive.Value = "5"; restriction.Facets.Add(minInclusive); OrderQuantityType.Content = restriction; schema.Items.Add(OrderQuantityType); // <xs:element name="item"> XmlSchemaElement element = new XmlSchemaElement(); element.Name = "item"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="OrderQuantity" type="OrderQuantityType"/> XmlSchemaAttribute OrderQuantityAttribute = new XmlSchemaAttribute(); OrderQuantityAttribute.Name = "OrderQuantity"; OrderQuantityAttribute.SchemaTypeName = new XmlQualifiedName("OrderQuantityType", ""); complexType.Attributes.Add(OrderQuantityAttribute); element.SchemaType = complexType; schema.Items.Add(element); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
//[Variation(Desc = "TFS_470021 Unexpected local particle qualified name when chameleon schema is added to set")] public void TFS_470021() { string cham = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='a0' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:complexType name='ctseq1_a'> <xs:sequence> <xs:element name='foo'/> </xs:sequence> <xs:attribute name='abt0' type='xs:string'/> </xs:complexType> <xs:element name='gect1_a' type ='ctseq1_a'/> </xs:schema>"; string main = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='m0' targetNamespace='http://tempuri.org/chameleon1' elementFormDefault='qualified' xmlns='http://tempuri.org/chameleon1' xmlns:mstns='http://tempuri.org/chameleon1' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:include schemaLocation='cham.xsd' /> <xs:element name='root'> <xs:complexType> <xs:sequence maxOccurs='unbounded'> <xs:any namespace='##any' processContents='lax'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; using (var tempDirectory = new TempDirectory()) { string chamPath = Path.Combine(tempDirectory.Path, "cham.xsd"); string tempDirectoryPath = tempDirectory.Path[tempDirectory.Path.Length - 1] == Path.DirectorySeparatorChar ? tempDirectory.Path : tempDirectory.Path + Path.DirectorySeparatorChar; using (XmlWriter w = XmlWriter.Create(chamPath)) { using (XmlReader r = XmlReader.Create(new StringReader(cham))) w.WriteNode(r, true); } XmlSchemaSet ss = new XmlSchemaSet(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, XmlReader.Create(new StringReader(cham))); // TempDirectory path must end with a DirectorySeratorChar, otherwise it will throw in the Xml validation. var settings = new XmlReaderSettings() { XmlResolver = new XmlUrlResolver() }; ss.Add(null, XmlReader.Create(new StringReader(main), settings, tempDirectoryPath)); ss.Compile(); Assert.Equal(2, ss.Count); foreach (XmlSchemaElement e in ss.GlobalElements.Values) { _output.WriteLine(e.QualifiedName.ToString()); XmlSchemaComplexType type = e.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence seq = type.ContentTypeParticle as XmlSchemaSequence; foreach (XmlSchemaObject child in seq.Items) { if (child is XmlSchemaElement) { _output.WriteLine("\t" + (child as XmlSchemaElement).QualifiedName); } } } Assert.Equal(0, warningCount); Assert.Equal(0, errorCount); } }
public void v10() { XmlCachedSchemaSetResolver resolver = new XmlCachedSchemaSetResolver(); XmlTextReader r = new XmlTextReader(TestData._Root + @"RedefineEmployee.xsd"); XmlSchema s = XmlSchema.Read(r, null); resolver.Add(new Uri(s.SourceUri), s); XmlTextReader r2 = new XmlTextReader(TestData._Root + @"BaseEmployee2.xsd"); XmlSchema s2 = XmlSchema.Read(r2, null); resolver.Add(new Uri(s2.SourceUri), s2); XmlSchemaSet set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(callback); set.XmlResolver = resolver; set.Add(s2); Assert.Equal(set.Count, 1); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.IsCompiled, false); set.Add(s); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, false); set.Compile(); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, true); XmlTextReader r3 = new XmlTextReader(TestData._Root + @"BaseEmployee2.xsd"); XmlSchema s3 = XmlSchema.Read(r3, null); resolver.Add(new Uri(s3.SourceUri), s3); //Clear includes in S foreach (XmlSchemaExternal ext in s.Includes) { ext.Schema = null; } XmlSchemaSet set2 = new XmlSchemaSet(); set2.ValidationEventHandler += new ValidationEventHandler(callback); set2.XmlResolver = resolver; set2.Add(s3); Assert.Equal(set2.Count, 1); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), false); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Add(s); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Compile(); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, true); Assert.Equal(errorCount, 0); }
/// <summary> /// Converts schemas to NodeTypes, AttributeTypes, and root elements</summary> /// <param name="schemaSet">Schemas to register</param> public void Load(XmlSchemaSet schemaSet) { if (!schemaSet.IsCompiled) { schemaSet.Compile(); } System.Collections.ICollection schemas = schemaSet.Schemas(); foreach (XmlSchema schema in schemas) { string targetNamespace = schema.TargetNamespace; if (string.IsNullOrEmpty(targetNamespace)) { throw new InvalidOperationException("Schema has no target namespace"); } // only register the schema once; targetNamespaces must be globally unique if (!m_typeCollections.ContainsKey(targetNamespace)) { XmlQualifiedName[] nameSpaces = schema.Namespaces.ToArray(); XmlSchemaTypeCollection typeCollection = new XmlSchemaTypeCollection(nameSpaces, targetNamespace, this); m_typeCollections.Add(targetNamespace, typeCollection); } } try { m_annotations = new Dictionary <NamedMetadata, IList <XmlNode> >(); m_typeNameSet = new HashSet <string>(); m_localElementSet = new Dictionary <XmlSchemaElement, XmlQualifiedName>(); // collect global element & type names so we do not generate local type names that collides with those foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values) { m_typeNameSet.Add(element.QualifiedName.Name); } foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values) { if (type is XmlSchemaComplexType) { m_typeNameSet.Add(type.Name); } } var substitutionGroups = new Multimap <XmlQualifiedName, ChildInfo>(); // Get types reachable from global elements foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values) { XmlSchemaType type = element.ElementSchemaType; DomNodeType nodeType = GetNodeType(type, element); ChildInfo childInfo = new ChildInfo(GetFieldName(element.QualifiedName), nodeType); m_annotations.Add(childInfo, GetAnnotation(element)); // Keep list of substitution groups if (!element.SubstitutionGroup.IsEmpty) { substitutionGroups.Add(element.SubstitutionGroup, childInfo); } // only add root elements once; root element names must be globally unique string name = element.QualifiedName.ToString(); if (!m_rootElements.ContainsKey(name)) { m_rootElements[name] = childInfo; } } // Get global complex type definitions foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values) { if (type is XmlSchemaComplexType) { GetNodeType(type, null); } } // Parse substitution groups foreach (var kvp in m_refElements) { XmlQualifiedName refName = kvp.Value; ChildInfo childInfo = kvp.Key; var substitutions = substitutionGroups.Find(refName).ToArray(); if (substitutions.Length > 0) { childInfo.AddRule(new SubstitutionGroupChildRule(substitutions)); } } // Preserve annotation from any types that were redefined foreach (XmlSchema schema in schemas) { foreach (XmlSchemaObject schemaInclude in schema.Includes) { XmlSchemaRedefine schemaRedefine = schemaInclude as XmlSchemaRedefine; if (schemaRedefine != null) { MergeRedefinedTypeAnnotations(schemaRedefine); } } } // Sort DomNodeTypes, so that base types are always before derived types // Bucket sort by depth in the inheritance tree // Time: O(n * d) with n = number of DomNodeTypes, d = depth of inheritance tree var sortedTypes = new List <List <DomNodeType> >(); foreach (DomNodeType type in GetNodeTypes()) { // Get inheritance depth of current type int depth = 0; DomNodeType curType = type; while (curType != null && curType != DomNodeType.BaseOfAllTypes) { depth++; curType = curType.BaseType; } // We don't need to merge annotations for BaseAllTypes (level 0) // and its immediate child types (level 1) int idx = depth - 2; if (idx >= 0) { while (sortedTypes.Count <= idx) { sortedTypes.Add(new List <DomNodeType>()); } sortedTypes[idx].Add(type); } } // Merge type annotations with base type annotations foreach (var list in sortedTypes) { foreach (DomNodeType type in list) { if (type.BaseType != null && type.BaseType != DomNodeType.BaseOfAllTypes) { IList <XmlNode> baseAnnotations; IList <XmlNode> annotations; if (m_annotations.TryGetValue(type.BaseType, out baseAnnotations) && m_annotations.TryGetValue(type, out annotations)) { // Call protected virtual merge method - allowing clients to define if & how annotations are being merged IEnumerable <XmlNode> mergedAnnotations = MergeInheritedTypeAnnotations(baseAnnotations, annotations); m_annotations[type] = mergedAnnotations as IList <XmlNode> ?? mergedAnnotations.ToList(); } } } } // Call before the DomNodeTypes are frozen. Note that iterating through Attributes or // calling 'SetIdAttribute' freezes the attributes on DomNodeType. OnSchemaSetLoaded(schemaSet); // Set up ID attributes where xs:ID has been specified foreach (DomNodeType nodeType in GetNodeTypes()) { foreach (var attribute in nodeType.Attributes.OfType <XmlAttributeInfo>()) { if (((XmlAttributeType)attribute.Type).XmlTypeCode == XmlTypeCode.Id) { nodeType.SetIdAttribute(attribute.Name); } } } // Attach annotation as metadata to the associated type so that other classes can find it foreach (var keyValuePair in m_annotations) { if (keyValuePair.Value.Count > 0) { keyValuePair.Key.SetTag <IEnumerable <XmlNode> >(keyValuePair.Value); } } ParseAnnotations(schemaSet, m_annotations); // Call this after the ID attributes have been set and after the DomNodeTypes are frozen. OnDomNodeTypesFrozen(schemaSet); } finally { m_annotations = null; m_typeNameSet = null; m_localElementSet = null; } }
public void v11() { XmlCachedSchemaSetResolver resolver = new XmlCachedSchemaSetResolver(); XmlTextReader r = new XmlTextReader(TestData._Root + @"RedefineEmployee.xsd"); XmlSchema s = XmlSchema.Read(r, null); resolver.Add(new Uri(s.SourceUri), s); XmlTextReader r2 = new XmlTextReader(TestData._Root + @"BaseEmployee2.xsd"); XmlSchema s2 = XmlSchema.Read(r2, null); resolver.Add(new Uri(s2.SourceUri), s2); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = resolver; set.Add(s2); Assert.Equal(set.Count, 1); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.IsCompiled, false); set.Add(s); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, false); set.Compile(); Assert.Equal(set.Count, 2); Assert.Equal(set.Contains(s2), true); Assert.Equal(set.Contains(s), true); Assert.Equal(set.IsCompiled, true); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; using (XmlReader reader = XmlReader.Create(TestData._Root + "EmployeesDefaultPrefix.xml", settings)) { while (reader.Read()) { ; } } XmlTextReader r3 = new XmlTextReader(TestData._Root + @"BaseEmployee2.xsd"); XmlSchema s3 = XmlSchema.Read(r3, null); resolver.Add(new Uri(s3.SourceUri), s3); XmlSchemaSet set2 = new XmlSchemaSet(); set2.XmlResolver = resolver; set2.Add(s3); Assert.Equal(set2.Count, 1); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), false); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); foreach (XmlSchemaRedefine redefine in s.Includes) { redefine.Schema = null; } set2.Add(s); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, false); set2.Compile(); Assert.Equal(set2.Count, 2); Assert.Equal(set2.Contains(s2), false); Assert.Equal(set2.Contains(s), true); Assert.Equal(set2.Contains(s3), true); Assert.Equal(set2.IsCompiled, true); settings.Schemas = set2; using (XmlReader reader = XmlReader.Create(TestData._Root + "EmployeesDefaultPrefix.xml", settings)) { while (reader.Read()) { ; } } Assert.Equal(errorCount, 0); }
/// <summary> /// Gets the XML schemas for generating data contracts. /// </summary> /// <param name="options">The metadata resolving options.</param> /// <returns>A collection of the XML schemas.</returns> public static XmlSchemas GetXmlSchemas(MetadataResolverOptions options) { if (options.DataContractFiles == null) { throw new ArgumentNullException("options"); } // Resolve the schemas. XmlSchemas schemas = new XmlSchemas(); for (int fi = 0; fi < options.DataContractFiles.Length; fi++) { // Skip the non xsd/wsdl files. string lowext = Path.GetExtension(options.DataContractFiles[fi]).ToLower(); if (lowext == ".xsd") // This is an XSD file. { XmlTextReader xmltextreader = null; try { xmltextreader = new XmlTextReader(options.DataContractFiles[fi]); XmlSchema schema = XmlSchema.Read(xmltextreader, null); XmlSchemaSet schemaset = new XmlSchemaSet(); schemaset.Add(schema); RemoveDuplicates(ref schemaset); schemaset.Compile(); schemas.Add(schema); } finally { if (xmltextreader != null) { xmltextreader.Close(); } } } else if (lowext == ".wsdl") // This is a WSDL file. { XmlSchemaSet schemaset = new XmlSchemaSet(); XmlSchemaSet embeddedschemaset = new XmlSchemaSet(); DiscoveryClientProtocol dcp = new DiscoveryClientProtocol(); dcp.AllowAutoRedirect = true; dcp.Credentials = CredentialCache.DefaultCredentials; dcp.DiscoverAny(options.DataContractFiles[fi]); dcp.ResolveAll(); foreach (object document in dcp.Documents.Values) { if (document is XmlSchema) { schemaset.Add((XmlSchema)document); schemas.Add((XmlSchema)document); } if (document is WebServiceDescription) { schemas.Add(((WebServiceDescription)document).Types.Schemas); foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas) { embeddedschemaset.Add(schema); schemas.Add(schema); } } } RemoveDuplicates(ref schemaset); schemaset.Add(embeddedschemaset); schemaset.Compile(); } } return(schemas); }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:element name="cat" type="xs:string"/> XmlSchemaElement elementCat = new XmlSchemaElement(); schema.Items.Add(elementCat); elementCat.Name = "cat"; elementCat.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:element name="dog" type="xs:string"/> XmlSchemaElement elementDog = new XmlSchemaElement(); schema.Items.Add(elementDog); elementDog.Name = "dog"; elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:element name="redDog" substitutionGroup="dog" /> XmlSchemaElement elementRedDog = new XmlSchemaElement(); schema.Items.Add(elementRedDog); elementRedDog.Name = "redDog"; elementRedDog.SubstitutionGroup = new XmlQualifiedName("dog"); // <xs:element name="brownDog" substitutionGroup ="dog" /> XmlSchemaElement elementBrownDog = new XmlSchemaElement(); schema.Items.Add(elementBrownDog); elementBrownDog.Name = "brownDog"; elementBrownDog.SubstitutionGroup = new XmlQualifiedName("dog"); // <xs:element name="pets"> XmlSchemaElement elementPets = new XmlSchemaElement(); schema.Items.Add(elementPets); elementPets.Name = "pets"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); elementPets.SchemaType = complexType; // <xs:choice minOccurs="0" maxOccurs="unbounded"> XmlSchemaChoice choice = new XmlSchemaChoice(); complexType.Particle = choice; choice.MinOccurs = 0; choice.MaxOccursString = "unbounded"; // <xs:element ref="cat"/> XmlSchemaElement catRef = new XmlSchemaElement(); choice.Items.Add(catRef); catRef.RefName = new XmlQualifiedName("cat"); // <xs:element ref="dog"/> XmlSchemaElement dogRef = new XmlSchemaElement(); choice.Items.Add(dogRef); dogRef.RefName = new XmlQualifiedName("dog"); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
void RetrieveSerializableSchema() { if (needSchema) { needSchema = false; if (getSchemaMethod != null) { // get the type info if (schemas == null) { schemas = new XmlSchemaSet(); } object typeInfo = getSchemaMethod.Invoke(null, new object[] { schemas }); xsiType = XmlQualifiedName.Empty; if (typeInfo != null) { if (typeof(XmlSchemaType).IsAssignableFrom(getSchemaMethod.ReturnType)) { xsdType = (XmlSchemaType)typeInfo; // check if type is named xsiType = xsdType.QualifiedName; } else if (typeof(XmlQualifiedName).IsAssignableFrom(getSchemaMethod.ReturnType)) { xsiType = (XmlQualifiedName)typeInfo; if (xsiType.IsEmpty) { throw new InvalidOperationException(Res.GetString(Res.XmlGetSchemaEmptyTypeName, type.FullName, getSchemaMethod.Name)); } } else { throw new InvalidOperationException(Res.GetString(Res.XmlGetSchemaMethodReturnType, type.Name, getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else { any = true; } // make sure that user-specified schemas are valid schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode); schemas.Compile(); // at this point we verified that the information returned by the IXmlSerializable is valid // Now check to see if the type was referenced before: // if (!xsiType.IsEmpty) { // try to find the type in the schemas collection if (xsiType.Namespace != XmlSchema.Namespace) { ArrayList srcSchemas = (ArrayList)schemas.Schemas(xsiType.Namespace); if (srcSchemas.Count == 0) { throw new InvalidOperationException(Res.GetString(Res.XmlMissingSchema, xsiType.Namespace)); } if (srcSchemas.Count > 1) { throw new InvalidOperationException(Res.GetString(Res.XmlGetSchemaInclude, xsiType.Namespace, getSchemaMethod.DeclaringType.FullName, getSchemaMethod.Name)); } XmlSchema s = (XmlSchema)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(Res.GetString(Res.XmlMissingSchema, xsiType.Namespace)); } xsdType = (XmlSchemaType)s.SchemaTypes[xsiType]; if (xsdType == null) { throw new InvalidOperationException(Res.GetString(Res.XmlGetSchemaTypeMissing, getSchemaMethod.DeclaringType.FullName, getSchemaMethod.Name, xsiType.Name, xsiType.Namespace)); } xsdType = xsdType.Redefined != null ? xsdType.Redefined : xsdType; } } } else { IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(type); schema = serializable.GetSchema(); if (schema != null) { if (schema.Id == null || schema.Id.Length == 0) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializableNameMissing1, type.FullName)); } } } } }
/// <summary> /// Gets the XML schemas for generating data contracts. /// </summary> /// <param name="options">The metadata resolving options.</param> /// <returns>A collection of the XML schemas.</returns> public static XmlSchemas GetXmlSchemaSetFromDataContractFiles(MetadataResolverOptions options) { if (options.DataContractFiles == null) { throw new ArgumentNullException("No data contract files provided"); } // Resolve the schemas. XmlSchemaSet schemaSet = CreateXmlSchemaSet(); for (int fi = 0; fi < options.DataContractFiles.Length; fi++) { // Skip the non xsd/wsdl files. string lowext = Path.GetExtension(options.DataContractFiles[fi]).ToLower(); if (lowext == ".xsd") // This is an XSD file. { XmlTextReader xmltextreader = null; try { xmltextreader = new XmlTextReader(options.DataContractFiles[fi]); XmlSchema schema = XmlSchema.Read(xmltextreader, null); if (options.GenerateSeparateFilesEachXsd) { if (string.IsNullOrWhiteSpace(schema.SourceUri)) { schema.SourceUri = options.DataContractFiles[fi]; } ResolveIncludedSchemas(schemaSet, schema); } schemaSet.Add(schema); } finally { if (xmltextreader != null) { xmltextreader.Close(); } } } else if (lowext == ".wsdl") // This is a WSDL file. { AntDiscoveryClientProtocol dcp = new AntDiscoveryClientProtocol(); dcp.AllowAutoRedirect = true; dcp.Credentials = CredentialCache.DefaultCredentials; dcp.DiscoverAny(options.DataContractFiles[fi]); dcp.ResolveAll(); foreach (string url in dcp.Documents.Keys) { object document = dcp.Documents[url]; if (document is XmlSchema) { XmlSchema xmlSchema = (XmlSchema)document; if (options.GenerateSeparateFilesEachXsd) { if (string.IsNullOrWhiteSpace(xmlSchema.SourceUri)) { xmlSchema.SourceUri = url; } ResolveIncludedSchemas(schemaSet, xmlSchema); } schemaSet.Add(xmlSchema); } if (document is WebServiceDescription) { foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas) { if (!IsEmptySchema(schema)) { if (options.GenerateSeparateFilesEachXsd) { if (string.IsNullOrWhiteSpace(schema.SourceUri)) { schema.SourceUri = url; } ResolveIncludedSchemas(schemaSet, schema); } schemaSet.Add(schema); } } } } } } RemoveDuplicates(ref schemaSet); schemaSet.Compile(); XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } return(schemas); }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:element name="selected"/> XmlSchemaElement xeSelected = new XmlSchemaElement(); xeSelected.Name = "selected"; schema.Items.Add(xeSelected); // <xs:element name="unselected"/> XmlSchemaElement xeUnselected = new XmlSchemaElement(); xeUnselected.Name = "unselected"; schema.Items.Add(xeUnselected); // <xs:element name="dimpled"/> XmlSchemaElement xeDimpled = new XmlSchemaElement(); xeDimpled.Name = "dimpled"; schema.Items.Add(xeDimpled); // <xs:element name="perforated"/> XmlSchemaElement xePerforated = new XmlSchemaElement(); xePerforated.Name = "perforated"; schema.Items.Add(xePerforated); // <xs:complexType name="chadState"> XmlSchemaComplexType chadState = new XmlSchemaComplexType(); schema.Items.Add(chadState); chadState.Name = "chadState"; // <xs:choice minOccurs="1" maxOccurs="1"> XmlSchemaChoice choice = new XmlSchemaChoice(); chadState.Particle = choice; choice.MinOccurs = 1; choice.MaxOccurs = 1; // <xs:element ref="selected"/> XmlSchemaElement elementSelected = new XmlSchemaElement(); choice.Items.Add(elementSelected); elementSelected.RefName = new XmlQualifiedName("selected"); // <xs:element ref="unselected"/> XmlSchemaElement elementUnselected = new XmlSchemaElement(); choice.Items.Add(elementUnselected); elementUnselected.RefName = new XmlQualifiedName("unselected"); // <xs:element ref="dimpled"/> XmlSchemaElement elementDimpled = new XmlSchemaElement(); choice.Items.Add(elementDimpled); elementDimpled.RefName = new XmlQualifiedName("dimpled"); // <xs:element ref="perforated"/> XmlSchemaElement elementPerforated = new XmlSchemaElement(); choice.Items.Add(elementPerforated); elementPerforated.RefName = new XmlQualifiedName("perforated"); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
/// <summary> /// Gets the XML schemas from a given WSDL document /// </summary> /// <param name="options">The metadata resolving options.</param> /// <returns>A collection of the XML schemas.</returns> public static XmlSchemas GetXmlSchemaSetFromWsdlFile(MetadataResolverOptions options) { if (options == null) { throw new ArgumentException("MetadataResolverOptions could not be null."); } if (string.IsNullOrEmpty(options.MetadataLocation)) { throw new ArgumentException("MetadataLocation option could not be null or an empty string."); } try { // First download the contracts if they are accessed over the web. DownloadContract(options); AntDiscoveryClientProtocol dcp = new AntDiscoveryClientProtocol(); dcp.Credentials = GetCredentials(options); dcp.AllowAutoRedirect = true; dcp.DiscoverAny(options.MetadataLocation); dcp.ResolveAll(); XmlSchemaSet schemaSet = CreateXmlSchemaSet(); foreach (string url in dcp.Documents.Keys) { object document = dcp.Documents[url]; if (document is System.Web.Services.Description.ServiceDescription) { foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas) { if (!IsEmptySchema(schema)) { if (options.GenerateSeparateFilesEachXsd) { if (string.IsNullOrWhiteSpace(schema.SourceUri)) { schema.SourceUri = url; } ResolveIncludedSchemas(schemaSet, schema); } schemaSet.Add(schema); } } continue; } if (document is XmlSchema) { XmlSchema xmlSchema = (XmlSchema)document; if (options.GenerateSeparateFilesEachXsd) { if (string.IsNullOrWhiteSpace(xmlSchema.SourceUri)) { xmlSchema.SourceUri = url; } ResolveIncludedSchemas(schemaSet, xmlSchema); } schemaSet.Add(xmlSchema); } } RemoveDuplicates(ref schemaSet); schemaSet.Compile(); XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } return(schemas); } catch (Exception ex) { // TODO: Log exception. throw new MetadataResolveException("Could not resolve metadata. " + ex, ex); } }
//[Variation(Desc = "TFS_470021 Unexpected local particle qualified name when chameleon schema is added to set")] public void TFS_470021() { string cham = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='a0' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:complexType name='ctseq1_a'> <xs:sequence> <xs:element name='foo'/> </xs:sequence> <xs:attribute name='abt0' type='xs:string'/> </xs:complexType> <xs:element name='gect1_a' type ='ctseq1_a'/> </xs:schema>"; string main = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema id='m0' targetNamespace='http://tempuri.org/chameleon1' elementFormDefault='qualified' xmlns='http://tempuri.org/chameleon1' xmlns:mstns='http://tempuri.org/chameleon1' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:include schemaLocation='cham.xsd' /> <xs:element name='root'> <xs:complexType> <xs:sequence maxOccurs='unbounded'> <xs:any namespace='##any' processContents='lax'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; using (XmlWriter w = XmlWriter.Create("cham.xsd")) { using (XmlReader r = XmlReader.Create(new StringReader(cham))) w.WriteNode(r, true); } XmlSchemaSet ss = new XmlSchemaSet(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, XmlReader.Create(new StringReader(cham))); ss.Add(null, XmlReader.Create(new StringReader(main))); ss.Compile(); Assert.Equal(ss.Count, 2); foreach (XmlSchemaElement e in ss.GlobalElements.Values) { _output.WriteLine(e.QualifiedName.ToString()); XmlSchemaComplexType type = e.ElementSchemaType as XmlSchemaComplexType; XmlSchemaSequence seq = type.ContentTypeParticle as XmlSchemaSequence; foreach (XmlSchemaObject child in seq.Items) { if (child is XmlSchemaElement) { _output.WriteLine("\t" + (child as XmlSchemaElement).QualifiedName); } } } Assert.Equal(warningCount, 0); Assert.Equal(errorCount, 0); return; }
/// <summary> /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types, /// HostedServices and Client Proxies. /// </summary> /// <remarks>Currently only generates C# source files.</remarks> /// <param name="contractFilename">The name of a contract source code (.cs) file.</param> /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param> /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param> /// <param name="targetPlatform">Specifies the target runtime platform.</param> public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform) { m_platform = targetPlatform; Logger.WriteLine("", LogLevel.Normal); Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal); if (contractFilename == null) { throw new ArgumentNullException("codeFilename", "You must pass a valid code filename."); } if (m_svcDesc.Types == null) { throw new Exception("No wsdl types found."); } string path = Path.GetDirectoryName(contractFilename).Trim(); if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) { Directory.CreateDirectory(path); } // Create code file stream FileStream dcStream = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None); StreamWriter dcStreamWriter = new StreamWriter(dcStream); // Write the auto generated header dcStreamWriter.Write(AutoGenTextHeader.Message); try { // Set up data contract code generator CSharpCodeProvider cSharpCP = new CSharpCodeProvider(); ICodeGenerator codeGen = cSharpCP.CreateGenerator(dcStreamWriter); CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions(); codeGenOptions.BracingStyle = "C"; // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.' string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace); // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh! foreach (XmlSchema schema in m_svcDesc.Types.Schemas) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(schema); schemaSet.Compile(); } // Create new code namespace CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName); // Add data contract using directives CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;"); codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using System.Xml;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); if (m_platform == TargetPlatform.MicroFramework) { compileUnit.Value = "using System.Ext;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using System.Ext.Xml;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); } compileUnit.Value = "using Ws.ServiceModel;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using Ws.Services.Mtom;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using Ws.Services.Serialization;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;"; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Value = ""; codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions); compileUnit.Namespaces.Add(targetNamespace); m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces; Logger.WriteLine("", LogLevel.Normal); // Create HostedServices and ClientProxies collections HostedServices hostedServices = new HostedServices(targetNamespaceName); ClientProxies clientProxies = new ClientProxies(targetNamespaceName); // For each PortType process foreach (PortType portType in m_svcDesc.PortTypes) { // For each operation in the port type: // Get input and output message parts. // If the message part is a simple type: // Build HostedService operation. // Else if the message part is an element: // Find elements in Schema // If element type is native xml type: // Build HostedService operation. // Else if element references a simple or complex type: // If simpleType is base xml type with restrictions: // Build HostedService operation. // Else // Build DataContract and DataContractSerializer. // Build HostedService Operation. // // Create instance of a HostedService to hold the port type details HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform); // Create instance of ClientProxyGenerator ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform); // Create service contract interface CodeTypeDeclaration serviceCodeType = new CodeTypeDeclaration("I" + portType.Name); CodeAttributeArgument codeAttr = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace)); CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("ServiceContract", codeAttr); serviceCodeType.CustomAttributes.Add(codeAttrDecl); // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes // are required to regenerate policy assertions when converting a service to Wsdl. List <PolicyAssertion> policyAssertions = GetPolicyAssertions(); bool OptimizedMimeEncoded = false; foreach (PolicyAssertion assert in policyAssertions) { serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID)); // if Optimized Mime assertion id found set a processing flag if (assert.Name == "OptimizedMimeSerialization") { OptimizedMimeEncoded = true; } } // Add type declaration serviceCodeType.TypeAttributes = TypeAttributes.Public; serviceCodeType.IsInterface = true; // Create service contract callback client interface CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback"); // Add type declaration serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public; serviceCallbackCodeType.IsInterface = true; // If the binding contains a ref to Mtom encoding type set the Mtom flag if (OptimizedMimeEncoded) { m_dcCodeGen.EncodingType = MessageEncodingType.Mtom; hostedService.EncodingType = MessageEncodingType.Mtom; clientProxy.EncodingType = MessageEncodingType.Mtom; } // Step through port operations, get method names and parse elements. for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index) { Operation operation = portType.Operations[pt_index]; string operationName = operation.Name; string inputMessageName = null; string outputMessageName = null; MessagePartCollection inputMessageParts = null; MessagePartCollection outputMessageParts = null; string inAction = null; string outAction = null; GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction); // Oneway request port type if (operation.Messages.Flow == OperationFlow.OneWay) { OperationInput input = operation.Messages.Input; inputMessageName = input.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Twoway request/response pattern else if (operation.Messages.Flow == OperationFlow.RequestResponse) { OperationInput input = operation.Messages.Input; inputMessageName = input.Message.Name; OperationOutput output = operation.Messages.Output; outputMessageName = output.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Event pattern else if (operation.Messages.Flow == OperationFlow.Notification) { OperationOutput output = operation.Messages.Output; outputMessageName = output.Message.Name; // Add operation for HostedService code generation hostedService.AddOperation(operation, inAction, outAction); // Add method for ClientProxy code generation clientProxy.AddOperation(operation, inAction, outAction); } // Find input and output message parts collection in messages collection // and store for later. foreach (Message message in m_svcDesc.Messages) { if (inputMessageName != null) { if (message.Name == inputMessageName) { inputMessageParts = message.Parts; // Add operation for HostedService code generation hostedService.Messages.Add(message); // Add Message to ClientProxy generator for later clientProxy.Messages.Add(message); } } if (outputMessageName != null) { if (message.Name == outputMessageName) { outputMessageParts = message.Parts; // Add operation for HostedService code generation hostedService.Messages.Add(message); // Add Message to ClientProxy generator for later clientProxy.Messages.Add(message); } } } try { // Try to generate Data Contracts and DataContractSerializers GenerateTypeContracts(operation, inputMessageParts, outputMessageParts); // If operation flow is notification (event) add OperationContract to ServiceContractCallback // else add OperationContract to ServiceContract if (operation.Messages.Flow == OperationFlow.Notification) { AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType); } else { AddServiceOperationToInterface(operation, inAction, serviceCodeType); } } catch (Exception e) { dcStreamWriter.Close(); File.Delete(contractFilename); Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal); return; } } // Add serviceCodeType Service Contract interface to namespace // A serviceCodeType is added even if the wsdl only contains notifications. In that case // the contract will be empty but the ServiceContract attribute and CallbackContract argument // will be used to point to the notification or callback contract interace targetNamespace.Types.Add(serviceCodeType); // If service contract callback type contains members add callback contract to namespace // and add CallbackContract reference attribute to serviceCodeType contract. if (serviceCallbackCodeType.Members.Count > 0) { // Add the callback argument to the service description attribute CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract", new CodeTypeOfExpression(serviceCallbackCodeType.Name) ); serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg); // Add the callback interface to namespace targetNamespace.Types.Add(serviceCallbackCodeType); } // If the hosted service has opeations add to Hosted Services collection for Code Gen if (hostedService.ServiceOperations.Count > 0) { hostedServices.Add(hostedService); } // If the client Proxy service has opeations add to client proxy collection for Code Gen if (clientProxy.ServiceOperations.Count > 0) { clientProxies.Add(clientProxy); } } // MOD: 12-02-08 Added code to handle multiple type namespaces // Generate contract source file foreach (CodeNamespace codeNamespace in compileUnit.Namespaces) { codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions); } dcStreamWriter.Flush(); dcStreamWriter.Close(); // Generate Hosted Service code Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal); HostedServiceGenerator hsGen = new HostedServiceGenerator(); hsGen.GenerateCode(hostedServiceFilename, hostedServices); // Generate Client proxy code Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal); ClientProxyGenerator cpGen = new ClientProxyGenerator(); cpGen.GenerateCode(clientProxyFilename, clientProxies); } catch (Exception e) { dcStreamWriter.Close(); File.Delete(contractFilename); Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal); throw new Exception("Failed to generate service code. ", e); } }
private void DeserializeSampleXml(string pattern, Assembly assembly) { var files = Glob.Glob.ExpandNames(pattern); var set = new XmlSchemaSet(); var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) => { Assert.True(false, e.Message); })); foreach (var s in schemas) { set.Add(s); } set.Compile(); foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract)) { var type = FindType(assembly, rootElement.QualifiedName); var serializer = new XmlSerializer(type); var generator = new XmlSampleGenerator(set, rootElement.QualifiedName); var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true })) { // generate sample xml generator.WriteXml(xw); var xml = sb.ToString(); File.WriteAllText("xml.xml", xml); // deserialize from sample var sr = new StringReader(xml); var o = serializer.Deserialize(sr); // serialize back to xml var xml2 = Serialize(serializer, o); File.WriteAllText("xml2.xml", xml2); // validate serialized xml XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = set }; settings.ValidationEventHandler += (s, e) => { // generator doesn't generate valid values where pattern restrictions exist, e.g. email if (!e.Message.Contains("The Pattern constraint failed")) { Assert.True(false, e.Message); } }; XmlReader reader = XmlReader.Create(new StringReader(xml2), settings); while (reader.Read()) { ; } // deserialize again sr = new StringReader(xml2); var o2 = serializer.Deserialize(sr); AssertEx.Equal(o, o2); } } }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:simpleType name="SizeType"> XmlSchemaSimpleType SizeType = new XmlSchemaSimpleType(); SizeType.Name = "SizeType"; // <xs:restriction base="xs:string"> XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:enumeration value="Small"/> XmlSchemaEnumerationFacet enumerationSmall = new XmlSchemaEnumerationFacet(); enumerationSmall.Value = "Small"; restriction.Facets.Add(enumerationSmall); // <xs:enumeration value="Medium"/> XmlSchemaEnumerationFacet enumerationMedium = new XmlSchemaEnumerationFacet(); enumerationMedium.Value = "Medium"; restriction.Facets.Add(enumerationMedium); // <xs:enumeration value="Large"/> XmlSchemaEnumerationFacet enumerationLarge = new XmlSchemaEnumerationFacet(); enumerationLarge.Value = "Large"; restriction.Facets.Add(enumerationLarge); SizeType.Content = restriction; schema.Items.Add(SizeType); // <xs:element name="Item"> XmlSchemaElement elementItem = new XmlSchemaElement(); elementItem.Name = "Item"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); // <xs:attribute name="Size" type="SizeType"/> XmlSchemaAttribute attributeSize = new XmlSchemaAttribute(); attributeSize.Name = "Size"; attributeSize.SchemaTypeName = new XmlQualifiedName("SizeType", ""); complexType.Attributes.Add(attributeSize); elementItem.SchemaType = complexType; schema.Items.Add(elementItem); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
public static void Schema(string xsdFile, string outFile) { XmlSchemaSet schema = new XmlSchemaSet(); schema.Add("http://www.tcxml.org/Schemas/TCXMLSchema", xsdFile); schema.Compile(); XmlSchemaObjectTable table = schema.GlobalElements; System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(outFile, settings)) { writer.WriteStartDocument(true); writer.WriteStartElement("BMO"); //writer.WriteLine("USE Test"); XmlSchemaElement[] array = new XmlSchemaElement[table.Values.Count]; table.Values.CopyTo(array, 0); foreach (XmlSchemaElement el in array) { if (el.ElementSchemaType.BaseXmlSchemaType.GetType().Name.ToString() == "XmlSchemaComplexType") { string elementName = el.Name; XmlSchemaComplexType mType = (XmlSchemaComplexType)el.ElementSchemaType; XmlSchemaAttribute[] Attributes = mType.AttributeUses.Values.Cast <XmlSchemaAttribute>().Select(e => e).ToArray(); if (Attributes.Count() == 0) { continue; } writer.WriteStartElement(elementName); // writer.WriteLine("CREATE TABLE [" + elementName + "] ("); XmlSchemaAttribute last = Attributes.Last(); foreach (XmlSchemaAttribute attr in Attributes) { string name = attr.Name; // string type = attr.AttributeSchemaType.TypeCode.ToString(); string requirement = attr.Use.ToString(); requirement = ((requirement == "Required") ? "Y" : "N"); writer.WriteStartElement(name); //writer.WriteStartAttribute("req"); //writer.WriteValue(requirement); //writer.WriteEndAttribute(); //if (attr.Equals(last)) // writer.WriteLine("\t[" + name + "] " + typeReplace + ((requirement == "Required") ? " NOT NULL" : "")); //else // writer.WriteLine("\t[" + name + "] " + typeReplace + ((requirement == "Required") ? " NOT NULL" : "") + ","); writer.WriteEndElement(); } writer.WriteEndElement(); } } writer.WriteEndDocument(); } }
public void Start(string sDirIn, string sDirCppXmlOut, string sDirCppBinOut, string sDirJsBinOut, ValidationEventHandler oValidationEventHandler) { string sChartNamespace = "http://purl.oclc.org/ooxml/spreadsheetml/main"; string[] aFiles = Directory.GetFiles(sDirIn); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += oValidationEventHandler; for (int i = 0; i < aFiles.Length; i++) { string sFile = aFiles[i]; if (".xsd" == Path.GetExtension(sFile)) { schemaSet.Add(null, sFile); } } schemaSet.Compile(); XmlSchema chartSchema = null; XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { if (schema.TargetNamespace == sChartNamespace) { chartSchema = schema; schemas.Add(schema); } } if (null != chartSchema) { CodeNamespace ns = new CodeNamespace(); XmlCodeExporter exporter = new XmlCodeExporter(ns); CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; XmlSchemaImporter importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in chartSchema.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(ns); ////Microsoft.CSharp.CSharpCodeProvider oProvider; //// output the C# code //Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); //using (StringWriter writer = new StringWriter()) //{ // codeProvider.GenerateCodeFromNamespace(ns, writer, new CodeGeneratorOptions()); // string sCode = writer.GetStringBuilder().ToString(); //} List <GenClassPivot> aGenClasses = PreProcess(ns, chartSchema); aGenClasses = FilterClassesPivot(aGenClasses); //(new CodegenCPP()).Process(sDirCppXmlOut, sDirCppBinOut, aGenClasses); //(new CodegenJS()).Process(sDirJsBinOut, aGenClasses); (new CodegenJSXml()).Process(sDirJsBinOut, aGenClasses); } }