public static CodeNamespace Process(string xsdFile, string targetNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (FileStream fs = new FileStream("Untitled1.xsd", FileMode.Open)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); } XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } return ns; }
public static CodeNamespace GenerateCode(Stream schemaStream, string classesNamespace) { // Open schema XmlSchema schema = XmlSchema.Read(schemaStream, null); XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); schemas.Compile(null, true); // Generate code CodeNamespace code = new CodeNamespace(classesNamespace); XmlSchemaImporter importer = new XmlSchemaImporter(schemas); XmlCodeExporter exporter = new XmlCodeExporter(code); foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } // Modify generated code using extensions schemaStream.Position = 0; // Rewind stream to the start XPathDocument xPathDoc = new XPathDocument(schemaStream); CodeGenerationContext context = new CodeGenerationContext(code, schema, xPathDoc); new ExplicitXmlNamesExtension().ApplyTo(context); new DocumentationExtension().ApplyTo(context); new FixXmlTextAttributeExtension().ApplyTo(context); new ArraysToGenericExtension().ApplyTo(context); new CamelCaseExtension().ApplyTo(context); new GetByIDExtension().ApplyTo(context); return code; }
public void Bug360541 () { XmlSchemaComplexType stype = GetStype (); XmlSchemaElement selem1 = new XmlSchemaElement (); selem1.Name = "schema"; selem1.SchemaType = stype; XmlSchema schema = new XmlSchema (); schema.Items.Add (selem1); XmlSchemas xs = new XmlSchemas (); xs.Add (schema); xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement)); selem1 = new XmlSchemaElement (); selem1.Name = "schema1"; selem1.SchemaType = stype; schema = new XmlSchema (); schema.Items.Add (selem1); xs = new XmlSchemas (); xs.Add (schema); xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement)); }
private static void Main(string[] args) { XmlSchema rootSchema = GetSchemaFromFile("fpml-main-4-2.xsd"); var schemaSet = new List<XmlSchemaExternal>(); ExtractIncludes(rootSchema, ref schemaSet); var schemas = new XmlSchemas { rootSchema }; schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation))); schemas.Compile(null, true); var xmlSchemaImporter = new XmlSchemaImporter(schemas); var codeNamespace = new CodeNamespace("Hosca.FpML4_2"); var xmlCodeExporter = new XmlCodeExporter(codeNamespace); var xmlTypeMappings = new List<XmlTypeMapping>(); foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values) xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName)); foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values) xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping); CodeGenerator.ValidateIdentifiers(codeNamespace); foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types) { for (int i = codeTypeDeclaration.CustomAttributes.Count - 1; i >= 0; i--) { CodeAttributeDeclaration cad = codeTypeDeclaration.CustomAttributes[i]; if (cad.Name == "System.CodeDom.Compiler.GeneratedCodeAttribute") codeTypeDeclaration.CustomAttributes.RemoveAt(i); } } using (var writer = new StringWriter()) { new CSharpCodeProvider().GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); //Console.WriteLine(writer.GetStringBuilder().ToString()); File.WriteAllText(Path.Combine(rootFolder, "FpML4_2.Generated.cs"), writer.GetStringBuilder().ToString()); } Console.ReadLine(); }
internal static void AddDocument(string path, object document, XmlSchemas schemas, ServiceDescriptionCollection descriptions, StringCollection warnings) { ServiceDescription serviceDescription = document as ServiceDescription; if (serviceDescription != null) { descriptions.Add(serviceDescription); } else { XmlSchema schema = document as XmlSchema; if (schema != null) { schemas.Add(schema); } } }
internal static void ExportEndpoint(WsdlExporter wsdlExporter) { if (wsdlExporter.GeneratedWsdlDocuments.Count > 1) throw new ApplicationException("Single file option is not supported in multiple wsdl files"); ServiceDescription rootDescription = wsdlExporter.GeneratedWsdlDocuments[0]; XmlSchemas imports = new XmlSchemas(); foreach (XmlSchema schema in wsdlExporter.GeneratedXmlSchemas.Schemas()) { imports.Add(schema); } foreach (XmlSchema schema in imports) { schema.Includes.Clear(); } rootDescription.Types.Schemas.Clear(); rootDescription.Types.Schemas.Add(imports); }
public void ExportEndpoint() { ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "ExportEndpoint"); try { System.Web.Services.Description.ServiceDescription wsdl = _exporter.GeneratedWsdlDocuments[0]; XmlSchemaSet schemaSet = _exporter.GeneratedXmlSchemas; XmlSchemas imports = new XmlSchemas(); foreach (XmlSchema schema in _exporter.GeneratedXmlSchemas.Schemas()) { imports.Add(schema); } foreach (XmlSchema schema in imports) { schema.Includes.Clear(); } wsdl.Types.Schemas.Clear(); wsdl.Types.Schemas.Add(imports); //List<XmlSchema> importsList = new List<XmlSchema>(); // foreach (XmlSchema schema in wsdl.Types.Schemas) // { // AddImportedSchemas(schema, schemaSet, importsList); // } // wsdl.Types.Schemas.Clear(); // foreach (XmlSchema schema in importsList) // { // RemoveXsdImports(schema); // wsdl.Types.Schemas.Add(schema); // } //} } catch (Exception ex) { Log.Exception(PROC, ex); } }
public static void Generate (ArrayList services, ArrayList schemas, string binOper, string protocol) { ServiceDescriptionCollection descCol = new ServiceDescriptionCollection (); foreach (ServiceDescription sd in services) descCol.Add (sd); XmlSchemas schemaCol; if (schemas.Count > 0) { schemaCol = new XmlSchemas (); foreach (XmlSchema sc in schemas) schemaCol.Add (sc); } else schemaCol = descCol[0].Types.Schemas; string oper, bin = null; int i = binOper.IndexOf ('/'); if (i != -1) { oper = binOper.Substring (i+1); bin = binOper.Substring (0,i); } else oper = binOper; ConsoleSampleGenerator sg = new ConsoleSampleGenerator (descCol, schemaCol); string req, resp; sg.GenerateMessages (oper, bin, protocol, out req, out resp); Console.WriteLine (); Console.WriteLine ("Sample request message:"); Console.WriteLine (); Console.WriteLine (req); Console.WriteLine (); Console.WriteLine ("Sample response message:"); Console.WriteLine (); Console.WriteLine (resp); }
private void AddDocument(string path, object document, XmlSchemas schemas, ServiceDescriptionCollection descriptions) { ServiceDescription serviceDescription = document as ServiceDescription; if (serviceDescription != null) { if (descriptions[serviceDescription.TargetNamespace] == null) { descriptions.Add(serviceDescription); StringWriter w = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(w); writer.Formatting = Formatting.Indented; serviceDescription.Write(writer); this.wsdls.Add(w.ToString()); } else { this.CheckPoint(MessageType.Warning, string.Format(duplicateService, serviceDescription.TargetNamespace, path)); } } else { XmlSchema schema = document as XmlSchema; if (schema != null) { if (schemas[schema.TargetNamespace] == null) { schemas.Add(schema); StringWriter writer3 = new StringWriter(); XmlTextWriter writer4 = new XmlTextWriter(writer3); writer4.Formatting = Formatting.Indented; schema.Write(writer4); this.xsds.Add(writer3.ToString()); } else { this.CheckPoint(MessageType.Warning, string.Format(duplicateSchema, serviceDescription.TargetNamespace, path)); } } } }
private static void GenerateClasses(CodeNamespace code, XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter importer = new XmlSchemaImporter(schemas); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeGenerationOptions options = CodeGenerationOptions.None; XmlCodeExporter exporter = new XmlCodeExporter(code, codeCompileUnit, options); foreach (XmlSchemaObject item in schema.Items) { XmlSchemaElement element = item as XmlSchemaElement; if (element != null) { XmlQualifiedName name = new XmlQualifiedName(element.Name, schema.TargetNamespace); XmlTypeMapping map = importer.ImportTypeMapping(name); exporter.ExportTypeMapping(map); } } }
void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs) { if (!SchemaContainsItem(item, ns)) { XmlSchema schema = schemas[ns]; if (schema == null) { schema = new XmlSchema(); schema.TargetNamespace = ns == null || ns.Length == 0 ? null : ns; #pragma warning disable 429 // unreachable code detected: elementFormDefault is const so it will never be Unqualified schema.ElementFormDefault = elementFormDefault == XmlSchemaForm.Unqualified ? XmlSchemaForm.None : elementFormDefault; #pragma warning restore 429 schemas.Add(schema); } schema.Items.Add(item); } if (referencingNs != null) { AddSchemaImport(ns, referencingNs); } }
private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace) { XmlSchema xsd; stream.Seek(0, SeekOrigin.Begin); using (stream) { xsd = XmlSchema.Read(stream, null); } XmlSchemas xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds); // create the codedom CodeNamespace codeNamespace = new CodeNamespace(nameSpace); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace); List<XmlTypeMapping> maps = new List<XmlTypeMapping>(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } this.RemoveUnusedStuff(codeNamespace); return codeNamespace; }
public void Run(string src, string dest) { // Load the schema to process. XmlSchema xsd; using (Stream stm = File.OpenRead(src)) xsd = XmlSchema.Read(stm, null); // Collection of schemas for the XmlSchemaImporter XmlSchemas xsds = new XmlSchemas(); xsds.Add(xsd); XmlSchemaImporter imp = new XmlSchemaImporter(xsds); // System.CodeDom namespace for the XmlCodeExporter to put classes in CodeNamespace ns = new CodeNamespace("NHibernate.Mapping.Hbm"); CodeCompileUnit ccu = new CodeCompileUnit(); XmlCodeExporter exp = new XmlCodeExporter(ns, ccu, ~CodeGenerationOptions.GenerateProperties); // Iterate schema items (top-level elements only) and generate code for each foreach (XmlSchemaObject item in xsd.Items) { if (item is XmlSchemaElement) { // Import the mapping first XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, xsd.TargetNamespace)); // Export the code finally exp.ExportTypeMapping(map); } } ns.Imports.Add(new CodeNamespaceImport("Ayende.NHibernateQueryAnalyzer.SchemaEditing")); AddRequiredTags(ns, xsd); // Code generator to build code with. CodeDomProvider generator = new CSharpCodeProvider(); // Generate untouched version using (StreamWriter sw = new StreamWriter(dest, false)) generator.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions()); }
public static CodeNamespace Process(string xsdSchema, string targetNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (var fs = new StringReader(xsdSchema)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); } XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } // execute extensions //var collectionsExt = new ArraysToCollectionsExtension(); //collectionsExt.Process(ns, xsd); //var filedsExt = new FieldsToPropertiesExtension(); //filedsExt.Process(ns, xsd); return ns; }
protected override void ImportPartsBySchemaElement (QName qname, List<MessagePartDescription> parts, Message msg, MessagePart msgPart) { if (schema_set_cache != schema_set_in_use) { schema_set_cache = schema_set_in_use; var xss = new XmlSchemas (); foreach (XmlSchema xs in schema_set_cache.Schemas ()) xss.Add (xs); schema_importer = new XmlSchemaImporter (xss); if (ccu.Namespaces.Count == 0) ccu.Namespaces.Add (new CodeNamespace ()); var cns = ccu.Namespaces [0]; code_exporter = new XmlCodeExporter (cns, ccu); } var part = new MessagePartDescription (qname.Name, qname.Namespace); part.XmlSerializationImporter = this; var mbrNS = msg.ServiceDescription.TargetNamespace; var xmm = schema_importer.ImportMembersMapping (qname); code_exporter.ExportMembersMapping (xmm); // FIXME: use of ElementName is a hack! part.CodeTypeReference = new CodeTypeReference (xmm.ElementName); parts.Add (part); }
/// <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); } var exporter = new XmlCodeExporter(ns); var generationOptions = CodeGenerationOptions.None; if (generatorParams.Serialization.GenerateOrderXmlAttributes) { generationOptions = CodeGenerationOptions.GenerateOrder; } 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 (XmlSchemaType type in xsd.Items.OfType<XmlSchemaType>()) { var mapping = importer.ImportSchemaType(type.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(); } }
public string Convert(CodeDomProvider codeProvider) { StringBuilder code = new StringBuilder(); List<XmlQualifiedName> arrayTypeList = BuildDataContractArrayTypeList(); try { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace namespace2 = new CodeNamespace(); compileUnit.Namespaces.Add(namespace2); XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, compileUnit, codeProvider, CodeGenerationOptions.GenerateProperties, null); // XmlSchemaImporter needs XmlSchemas and not XmlSchemaSet XmlSchemas userSchemas = new XmlSchemas(); foreach (XmlSchema schema in schemas.Schemas()) { userSchemas.Add(schema); } XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, CodeGenerationOptions.GenerateProperties, codeProvider, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchema schema in userSchemas) { if (schema != null) { foreach (XmlSchemaElement element in schema.Elements.Values) { // Don't generate code for abstract elements or array types if (!element.IsAbstract && !arrayTypeList.Contains(element.QualifiedName)) { XmlTypeMapping mapping = schemaImporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(mapping); } } } } CodeTypeDeclarationCollection types = namespace2.Types; if ((types == null) || (types.Count == 0)) { //RtlAwareMessageBox.Show( PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match. Please ensure it contains a root element with some nested elements inside of it."); //, "Error", // MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); } else { CodeGenerator.ValidateIdentifiers(namespace2); // Now we have to run Silverlight-specific fix-up //DC // ServiceContractGenerator generator = new ServiceContractGenerator(compileUnit); // WcfSilverlightCodeGenerationExtension fixupExtension = new WcfSilverlightCodeGenerationExtension(); // fixupExtension.ClientGenerated(generator); using (StringWriter writer = new StringWriter(code, CultureInfo.CurrentCulture)) { foreach (CodeTypeDeclaration type in namespace2.Types) { codeProvider.GenerateCodeFromType(type, writer, null); } } } } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } //RtlAwareMessageBox.Show( //DC PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match." + Environment.NewLine + Environment.NewLine + exception.Message); //, "Error", // MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0); } return code.ToString(); }
void ImportSchemasAsClasses( string outputdir, ICodeGenerator codeGen, string fileExtension, IList fileNames, string ns, string uri, IList elements) { XmlSchemas schemasToCompile = new XmlSchemas(); XmlSchemas userSchemas = new XmlSchemas(); string outputSchemaName = ""; // Create parent schema XmlSchema parent = new XmlSchema(); foreach (string fileName in fileNames) { schemasToCompile.Add(ReadSchema(fileName, false)); userSchemas.Add(ReadSchema(fileName, true)); outputSchemaName += Path.ChangeExtension(fileName,"").Replace('.','_'); } Hashtable includeSchemas = new Hashtable(); foreach (XmlSchema schema in schemasToCompile) { CollectIncludes(schema, includeSchemas, false); } Compile(schemasToCompile); includeSchemas = new Hashtable(); foreach (XmlSchema schema in userSchemas) { CollectIncludes(schema, includeSchemas, true); } try { outputSchemaName = outputSchemaName.Substring(0, outputSchemaName.Length - 1); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); GenerateVersionComment(codeNamespace); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit); AddImports(codeNamespace, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) })); for (int i = 0; i < userSchemas.Count; i++) { XmlSchema schema = userSchemas[i]; for (int j = 0; j < schema.Items.Count; j++) { object item = schema.Items[j]; if (item is XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement)item; if (!element.IsAbstract) { if (uri.Length == 0 || schema.TargetNamespace == uri) { bool found; if (elements.Count == 0) { found = true; } else { found = false; foreach (string e in elements) { if (e == element.Name) { found = true; break; } } } if (found) { XmlTypeMapping xmlTypeMapping = schemaImporter.ImportTypeMapping(new XmlQualifiedName(element.Name, schema.TargetNamespace)); codeExporter.ExportTypeMapping(xmlTypeMapping); } } } } } } CodeTypeDeclarationCollection classes = codeNamespace.Types; if (classes == null || classes.Count == 0) { Console.WriteLine(Res.GetString(Res.NoClassesGenerated)); } else { TextWriter writer = CreateOutputWriter(outputdir, outputSchemaName, fileExtension); codeGen.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null); writer.Close(); } } catch (Exception e) { throw new InvalidOperationException(Res.GetString(Res.ErrGenerateClassesForSchema, outputSchemaName), e); } }
XmlSchemas GetXmlSchemas(DiscoveryClientProtocol protocol) { XmlSchemas schemas = new XmlSchemas(); foreach (DictionaryEntry entry in protocol.References) { SchemaReference schemaRef = entry.Value as SchemaReference; if (schemaRef != null) { schemas.Add(schemaRef.Schema); } } return schemas; }
private void ParseWsdl(ServiceDescription svcDesc, List<string> schemaRefs, XmlReaderSettings settings, List<string> importFiles) { foreach (Import imp in svcDesc.Imports) { string fileName = imp.Location; XmlReader reader; // Create the reader settings.ValidationEventHandler += new ValidationEventHandler(Settings_ValidationEventHandler); if (!importFiles.Contains(fileName)) { reader = XmlReader.Create(fileName, settings); ServiceDescription sd = ServiceDescription.Read(reader, true); for(int i=0; i<sd.Bindings.Count;i++) { m_svcDesc.Bindings.Add(sd.Bindings[i]); } reader.Close(); importFiles.Add(fileName); ParseWsdl(sd, schemaRefs, settings, importFiles); } } // Add Import schemas foreach (XmlElement element in svcDesc.Types.Extensions) { string schemaNs = null; string schemaLocation = null; if (element.LocalName == "import") { foreach (XmlAttribute attribute in element.Attributes) { if (attribute.LocalName == "schemaLocation") schemaLocation = attribute.Value; else if (attribute.LocalName == "namespace") schemaNs = attribute.Value; } schemaNs = schemaNs == null ? svcDesc.TargetNamespace : schemaNs; // If schemaLocation attribute is null check for external command line reference if (schemaLocation == null) { XmlSchema extSchema = GetExternalSchema(schemaNs, schemaRefs); if (extSchema == null) { throw new Exception("Invalid schema import element. Schema location for namespace" + schemaNs + "could not be resolved."); } else { Logger.WriteLine("Importing external schema. ", LogLevel.Normal); m_svcDesc.Types.Schemas.Add(extSchema); } } else { Logger.WriteLine("Importing Schema: " + schemaLocation, LogLevel.Normal); XmlReader reader = XmlReader.Create(schemaLocation, settings); XmlSchema xmlSchema = XmlSchema.Read(reader, null); m_svcDesc.Types.Schemas.Add(xmlSchema); reader.Close(); } } } XmlSchemas schemas = new XmlSchemas(); foreach (System.Xml.Schema.XmlSchema wsdlSchema in svcDesc.Types.Schemas) { foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes) { if (externalSchema is System.Xml.Schema.XmlSchemaInclude) { string schemaLocation = ((XmlSchemaInclude)externalSchema).SchemaLocation; // If schemaLocation attribute is null check for external command line reference if (schemaLocation == null) { XmlSchema extSchema = GetExternalSchema(wsdlSchema.TargetNamespace, schemaRefs); if (extSchema == null) { throw new Exception("Invalid schema include element. Schema location for namespace \"" + wsdlSchema.TargetNamespace + "\" could not be resolved."); } else { Logger.WriteLine("Including external schema. ", LogLevel.Normal); schemas.Add(extSchema); } } else { Logger.WriteLine("Including Schema: " + schemaLocation, LogLevel.Normal); XmlReader reader = XmlReader.Create(schemaLocation, settings); XmlSchema xmlSchema = XmlSchema.Read(reader, null); schemas.Add(xmlSchema); reader.Close(); } } else if (externalSchema is System.Xml.Schema.XmlSchemaImport) { string schemaLocation = ((XmlSchemaImport)externalSchema).SchemaLocation; // If schemaLocation attribute is null check for external command line reference if (schemaLocation == null) { XmlSchema extSchema = GetExternalSchema(((XmlSchemaImport)externalSchema).Namespace, schemaRefs); if (extSchema == null) { throw new Exception("Invalid schema import element. Schema location for namespace \"" + ((XmlSchemaImport)externalSchema).Namespace + "\" could not be resolved."); } else { Logger.WriteLine("Importing external schema. ", LogLevel.Normal); schemas.Add(extSchema); } } else { Logger.WriteLine("Importing Schema: " + schemaLocation, LogLevel.Normal); XmlReader reader = XmlReader.Create(schemaLocation, settings); XmlSchema xmlSchema = XmlSchema.Read(reader, null); schemas.Add(xmlSchema); reader.Close(); } } } } if (schemas.Count > 0) { foreach (XmlSchema schema in schemas) m_svcDesc.Types.Schemas.Add(schema); } }
public void GenerateClasses () { if (namesp == null) namesp = "Schemas"; if (uri == null) uri = ""; string targetFile = ""; XmlSchemas schemas = new XmlSchemas(); foreach (string fileName in schemaNames) { StreamReader sr = new StreamReader (fileName); schemas.Add (XmlSchema.Read (sr, new ValidationEventHandler (HandleValidationError))); sr.Close (); if (targetFile == "") targetFile = Path.GetFileNameWithoutExtension (fileName); else targetFile += "_" + Path.GetFileNameWithoutExtension (fileName); } targetFile += "." + provider.FileExtension; CodeCompileUnit cunit = new CodeCompileUnit (); CodeNamespace codeNamespace = new CodeNamespace (namesp); cunit.Namespaces.Add (codeNamespace); codeNamespace.Comments.Add (new CodeCommentStatement ("\nThis source code was auto-generated by MonoXSD\n")); // Locate elements to generate ArrayList qnames = new ArrayList (); if (elements.Count > 0) { foreach (string name in elements) qnames.Add (new XmlQualifiedName (name, uri)); } else { foreach (XmlSchema schema in schemas) { if (!schema.IsCompiled) schema.Compile (new ValidationEventHandler (HandleValidationError)); foreach (XmlSchemaElement el in schema.Elements.Values) if (!qnames.Contains (el.QualifiedName)) qnames.Add (el.QualifiedName); } } // Import schemas and generate the class model XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlCodeExporter sx = new XmlCodeExporter (codeNamespace, cunit); ArrayList maps = new ArrayList(); foreach (XmlQualifiedName qname in qnames) { XmlTypeMapping tm = importer.ImportTypeMapping (qname); if (tm != null) maps.Add (tm); } foreach (XmlTypeMapping tm in maps) { sx.ExportTypeMapping (tm); } // Generate the code ICodeGenerator gen = provider.CreateGenerator(); string genFile = Path.Combine (outputDir, targetFile); StreamWriter sw = new StreamWriter(genFile, false); gen.GenerateCodeFromCompileUnit (cunit, sw, new CodeGeneratorOptions()); sw.Close(); Console.WriteLine ("Written file " + genFile); }
public ObjectCollection GenerateClasses(XmlSchema schema) { #region Generate the CodeDom from the XSD CodeNamespace codeNamespace = new CodeNamespace("TestNameSpace"); XmlSchemas xmlSchemas = new XmlSchemas(); xmlSchemas.Add(schema); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas); XmlCodeExporter codeExporter = new XmlCodeExporter( codeNamespace, new CodeCompileUnit(), CodeGenerationOptions.GenerateProperties); foreach (XmlSchemaElement element in schema.Elements.Values) { try { XmlTypeMapping map = schemaImporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(map); } catch (Exception ex) { throw new Exception("Error Loading Schema: ", ex); } } #endregion #region Modify the CodeDom foreach (ICodeModifier codeModifier in m_codeModifiers) codeModifier.Execute(codeNamespace); #endregion #region Generate the code CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(codeNamespace); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); #if DEBUG StringWriter sw = new StringWriter(); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.VerbatimOrder = true; provider.GenerateCodeFromCompileUnit(compileUnit, sw, options); m_codeString = sw.ToString(); #endif #endregion #region Compile an assembly CompilerParameters compilerParameters = new CompilerParameters(); #region add references to assemblies // reference for // System.CodeDom.Compiler // System.CodeDom // System.Diagnostics compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("mscorlib.dll"); // System.Xml compilerParameters.ReferencedAssemblies.Add("system.xml.dll"); // reference to this assembly for the custom collection editor compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); compilerParameters.ReferencedAssemblies.Add("System.Drawing.dll"); // System.ComponentModel #endregion compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; CompilerResults results = provider.CompileAssemblyFromDom(compilerParameters, new CodeCompileUnit[] { compileUnit }); // handle the errors if there are any if (results.Errors.HasErrors) { m_errorStrings = new StringCollection(); m_errorStrings.Add("Error compiling assembly:\r\n"); foreach (CompilerError error in results.Errors) m_errorStrings.Add(error.ErrorText + "\r\n"); return null; } #endregion #region Find the exported classes Assembly assembly = results.CompiledAssembly; Type[] exportedTypes = assembly.GetExportedTypes(); // try to create an instance of the exported types ObjectCollection objectCollection = new ObjectCollection(); objectCollection.Clear(); foreach (Type type in exportedTypes) { object obj = Activator.CreateInstance(type); objectCollection.Add(new ObjectItem(type.Name, obj)); } #endregion return objectCollection; }
//Helper methods XmlSchemas GetSchemas (XmlSchemaSet set) { XmlSchemas schemas = new XmlSchemas (); foreach (XmlSchema schema in set.Schemas ()) schemas.Add (schema); return schemas; }
// Segregate the schemas containing abstract types from those // containing regular XML definitions. This is important because // when you import something returning the ur-type (object), then // you need to import ALL types/elements within ALL schemas. We // don't want the RPC-based types leaking over into the XML-based // element definitions or literal types in the encoded schemas, // beacase it can cause schema coimpilation falure. static void CollectEncodedAndLiteralSchemas(WsdlNS.ServiceDescriptionCollection serviceDescriptions, XmlSchemas encodedSchemas, XmlSchemas literalSchemas, XmlSchemaSet allSchemas) { XmlSchema wsdl = StockSchemas.CreateWsdl(); XmlSchema soap = StockSchemas.CreateSoap(); XmlSchema soapEncoding = StockSchemas.CreateSoapEncoding(); Hashtable references = new Hashtable(); if (!allSchemas.Contains(wsdl.TargetNamespace)) { references[soap] = wsdl; } if (!allSchemas.Contains(soap.TargetNamespace)) { references[soap] = soap; } if (!allSchemas.Contains(soapEncoding.TargetNamespace)) { references[soapEncoding] = soapEncoding; } foreach (WsdlNS.ServiceDescription description in serviceDescriptions) { foreach (WsdlNS.Message message in description.Messages) { foreach (WsdlNS.MessagePart part in message.Parts) { bool isEncoded; bool isLiteral; FindUse(part, out isEncoded, out isLiteral); if (part.Element != null && !part.Element.IsEmpty) { XmlSchemaElement element = FindSchemaElement(allSchemas, part.Element); if (element != null) { AddSchema(element.Parent as XmlSchema, isEncoded, isLiteral, encodedSchemas, literalSchemas, references); if (element.SchemaTypeName != null && !element.SchemaTypeName.IsEmpty) { XmlSchemaType type = FindSchemaType(allSchemas, element.SchemaTypeName); if (type != null) { AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, encodedSchemas, literalSchemas, references); } } } } if (part.Type != null && !part.Type.IsEmpty) { XmlSchemaType type = FindSchemaType(allSchemas, part.Type); if (type != null) { AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, encodedSchemas, literalSchemas, references); } } } } } Hashtable imports; foreach (XmlSchemas schemas in new XmlSchemas[] { encodedSchemas, literalSchemas }) { // collect all imports imports = new Hashtable(); foreach (XmlSchema schema in schemas) { AddImport(schema, imports, allSchemas); } // make sure we add them to the corresponding schema collections foreach (XmlSchema schema in imports.Keys) { if (references[schema] == null && !schemas.Contains(schema)) { schemas.Add(schema); } } } // If a schema was not referenced by either a literal or an encoded message part, // add it to both collections. There's no way to tell which it should be. imports = new Hashtable(); foreach (XmlSchema schema in allSchemas.Schemas()) { if (!encodedSchemas.Contains(schema) && !literalSchemas.Contains(schema)) { AddImport(schema, imports, allSchemas); } } // make sure we add them to the corresponding schema collections foreach (XmlSchema schema in imports.Keys) { if (references[schema] != null) continue; if (!encodedSchemas.Contains(schema)) { encodedSchemas.Add(schema); } if (!literalSchemas.Contains(schema)) { literalSchemas.Add(schema); } } if (encodedSchemas.Count > 0) { foreach (XmlSchema schema in references.Values) { encodedSchemas.AddReference(schema); } } if (literalSchemas.Count > 0) { foreach (XmlSchema schema in references.Values) { literalSchemas.AddReference(schema); } } AddSoapEncodingSchemaIfNeeded(literalSchemas); }
public void DuplicateIdentifiers () { XmlSchema xs = XmlSchema.Read (File.OpenText ("Test/XmlFiles/xsd/82078.xsd"), null); XmlSchemas xss = new XmlSchemas (); xss.Add (xs); XmlSchemaImporter imp = new XmlSchemaImporter (xss); CodeNamespace cns = new CodeNamespace (); XmlCodeExporter exp = new XmlCodeExporter (cns); XmlQualifiedName qname = new XmlQualifiedName ( "Operation", "http://tempuri.org/"); exp.ExportTypeMapping (imp.ImportTypeMapping (qname)); CodeCompileUnit ccu = new CodeCompileUnit (); ccu.Namespaces.Add (cns); CodeDomProvider provider = new CSharpCodeProvider (); ICodeCompiler compiler = provider.CreateCompiler (); CompilerParameters options = new CompilerParameters (); options.ReferencedAssemblies.Add ("System.dll"); options.ReferencedAssemblies.Add ("System.Xml.dll"); options.GenerateInMemory = true; CompilerResults result = compiler.CompileAssemblyFromDom (options, ccu); Assert.AreEqual (0, result.Errors.Count, "#1"); Assert.IsNotNull (result.CompiledAssembly, "#2"); }
public model.WebSvcMethodContainer GenerateSampleData() { Dictionary<string, model.WebSvcMethod> results = new Dictionary<string, model.WebSvcMethod>(); List<string> methodList = GetMethodList(); foreach (string method in methodList) { ServiceDescriptionCollection descCol = new ServiceDescriptionCollection(); foreach (ServiceDescription sd in _descriptions) { descCol.Add(sd); } XmlSchemas schemaCol; if (_schemas.Count > 0) { schemaCol = new XmlSchemas(); foreach (XmlSchema sc in _schemas) { schemaCol.Add(sc); } } else { schemaCol = descCol[0].Types.Schemas; } string req; string resp; SampleGeneratorWebSvc sg = new SampleGeneratorWebSvc(descCol, schemaCol); sg.GenerateMessages(method, null, "Soap", out req, out resp); int indexOfReqMsg = req.IndexOf(@"<soap:Envelope"); string reqHeaderMsg = req.Substring(0, indexOfReqMsg); string sampleReqMsg = req.Substring(indexOfReqMsg); int indexOfRespMsg = resp.IndexOf(@"<soap:Envelope"); string respHeaderMsg = resp.Substring(0, indexOfRespMsg); string sampleRespMsg = resp.Substring(indexOfRespMsg); string[] reqHeaderLines = reqHeaderMsg.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string soapAction = GetHeader(reqHeaderLines, "SOAPAction:"); string reqContentType = GetHeader(reqHeaderLines, "Content-Type:"); string[] respHeaderLines = respHeaderMsg.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string respContentType = GetHeader(respHeaderLines, "Content-Type:"); model.WebSvcMessageRequest messageRequest = new model.WebSvcMessageRequest(); messageRequest.Body = sampleReqMsg; messageRequest.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE] = reqContentType; messageRequest.Headers[model.WebSvcMessageRequest.HEADER_NAME_SOAP_ACTION] = soapAction; model.WebSvcMessageResponse messageResponse = new model.WebSvcMessageResponse(); messageResponse.Body = sampleRespMsg; messageResponse.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE] = respContentType; model.WebSvcMethod webMethod = new model.WebSvcMethod(method, _serviceURI) { Request = messageRequest, Response = messageResponse }; results[method] = webMethod; } return new model.WebSvcMethodContainer(results); }
/* protected override IList GetMethodParameterAttributes(MethodInfo method, ParameterInfo paramInfo) { IList attrs = base.GetMethodParameterAttributes(method, paramInfo); // Add the XmlElementAttribute if needed XmlMemberMapping inMemberMapping = inputMembersMapping[paramInfo.Position]; if (inMemberMapping.Namespace != inputMembersMapping.Namespace) { CustomAttributeBuilderBuilder cabb = new CustomAttributeBuilderBuilder(typeof(XmlElementAttribute)); cabb.AddPropertyValue("Namespace", inMemberMapping.Namespace); attrs.Add(cabb.Build()); } return attrs; } */ #endregion #region Private Methods private void Initialize(DiscoveryClientDocumentCollection wsDocuments, string bindingName) { // Service descriptions this.wsDescriptions = new ServiceDescriptionCollection(); XmlSchemas schemas = new XmlSchemas(); foreach (DictionaryEntry entry in wsDocuments) { if (entry.Value is ServiceDescription) { this.wsDescriptions.Add((ServiceDescription)entry.Value); } if (entry.Value is XmlSchema) { schemas.Add((XmlSchema)entry.Value); } } // XmlSchemaImporter foreach (ServiceDescription serviceDescription in this.wsDescriptions) { foreach (XmlSchema schema in serviceDescription.Types.Schemas) { if (schemas[schema.TargetNamespace] == null) { schemas.Add(schema); } } } this.schemaImporter = new XmlSchemaImporter(schemas); this.wsBinding = GetWsBinding(this.wsDescriptions, bindingName); this.wsUrl = GetWsUrl(this.wsDescriptions, this.wsBinding); }
private static void AddSchema(XmlSchema schema, bool isEncoded, bool isLiteral, XmlSchemas abstractSchemas, XmlSchemas concreteSchemas, Hashtable references) { if (schema != null) { if (isEncoded && !abstractSchemas.Contains(schema)) { if (references.Contains(schema)) { abstractSchemas.AddReference(schema); } else { abstractSchemas.Add(schema); } } if (isLiteral && !concreteSchemas.Contains(schema)) { if (references.Contains(schema)) { concreteSchemas.AddReference(schema); } else { concreteSchemas.Add(schema); } } } }
static void AddSoapEncodingSchemaIfNeeded(XmlSchemas schemas) { XmlSchema fakeXsdSchema = StockSchemas.CreateFakeXsdSchema(); foreach (XmlSchema schema in schemas) { foreach (object include in schema.Includes) { XmlSchemaImport import = include as XmlSchemaImport; if (import != null && import.Namespace == fakeXsdSchema.TargetNamespace) { schemas.Add(fakeXsdSchema); return; } } } }
public void ExportSimpleContentExtensionEnum () { string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:b='urn:bar' targetNamespace='urn:bar'> <xs:element name='Foo' type='b:DayOfWeek' /> <xs:complexType name='DayOfWeek'> <xs:simpleContent> <xs:extension base='b:WeekDay' /> </xs:simpleContent> </xs:complexType> <xs:simpleType name='WeekDay'> <xs:restriction base='xs:string'> <xs:enumeration value='Sunday'/> <xs:enumeration value='Monday'/> <xs:enumeration value='Tuesday'/> <xs:enumeration value='Wednesday'/> <xs:enumeration value='Thursday'/> <xs:enumeration value='Friday'/> <xs:enumeration value='Saturday'/> </xs:restriction> </xs:simpleType> </xs:schema>"; XmlSchema xs = XmlSchema.Read (new StringReader (xsd), null); XmlSchemas xss = new XmlSchemas (); xss.Add (xs); XmlSchemaImporter imp = new XmlSchemaImporter (xss); XmlTypeMapping m = imp.ImportTypeMapping (new XmlQualifiedName ("Foo", "urn:bar")); CodeNamespace cns = new CodeNamespace (); XmlCodeExporter exp = new XmlCodeExporter (cns); exp.ExportTypeMapping (m); CodeTypeDeclaration enumType = null; foreach (CodeTypeDeclaration ctd in cns.Types) if (ctd.Name == "WeekDay") enumType = ctd; Assert.IsNotNull (enumType); }
static void AddSchema(XmlSchema schema, bool isEncoded, bool isLiteral, XmlSchemas encodedSchemas, XmlSchemas literalSchemas, Hashtable references) { if (schema != null) { if (isEncoded && !encodedSchemas.Contains(schema)) { if (references.Contains(schema)) { encodedSchemas.AddReference(schema); } else { encodedSchemas.Add(schema); } } if (isLiteral && !literalSchemas.Contains(schema)) { if (references.Contains(schema)) { literalSchemas.AddReference(schema); } else { literalSchemas.Add(schema); } } } }