public static CodeNamespace Process() { CodeNamespace codeNameSpace = new CodeNamespace("MilkyWay.SolarSystem"); XmlSchemas schemas = new XmlSchemas(); XmlSchema xsd; using (var fs = new FileStream(Path.GetFileName("world.xsd"), FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); schemas.Add(xsd); } XmlSchemaImporter schImporter = new XmlSchemaImporter(schemas); XmlCodeExporter exCode = new XmlCodeExporter(codeNameSpace); foreach (XmlSchemaElement element in xsd.Elements.Values) { var importTypeMapping = schImporter.ImportTypeMapping(element.QualifiedName); exCode.ExportTypeMapping(importTypeMapping); } return(codeNameSpace); }
public static CodeNamespace ProcessXsd(this string xsdFile, string targetNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (FileStream fs = new FileStream(xsdFile, 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); }
protected override CodeMemberMethod GenerateMethod() { try { HttpOperationBinding httpOper = OperationBinding.Extensions.Find(typeof(HttpOperationBinding)) as HttpOperationBinding; if (httpOper == null) { throw new Exception("Http operation binding not found"); } XmlMembersMapping inputMembers = ImportInMembersMapping(InputMessage); XmlTypeMapping outputMember = ImportOutMembersMapping(OutputMessage); CodeMemberMethod met = GenerateMethod(memberIds, httpOper, inputMembers, outputMember); xmlExporter.ExportMembersMapping(inputMembers); if (outputMember != null) { xmlExporter.ExportTypeMapping(outputMember); } return(met); } catch (Exception ex) { UnsupportedOperationBindingWarning(ex.Message); return(null); } }
private static void ImportXmlSchema(XmlSchema schema, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaElement element in schema.Elements.Values) { exporter.ExportTypeMapping(importer.ImportTypeMapping(element.QualifiedName)); } }
private static void GenerateForElements(XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaElement element in xsd.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } }
public void XsdToClassTest() { // identify the path to the xsd string xsdFileName = "Account.xsd"; string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string xsdPath = Path.Combine(path, xsdFileName); // load the xsd XmlSchema xsd; using (FileStream stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(stream, null); } Console.WriteLine("xsd.IsCompiled {0}", xsd.IsCompiled); XmlSchemas xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds); // create the codedom CodeNamespace codeNamespace = new CodeNamespace("Generated"); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace); List maps = new List(); 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); } RemoveAttributes(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code CSharpCodeProvider codeProvider = new CSharpCodeProvider(); using (StringWriter writer = new StringWriter()) { codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); Console.WriteLine(writer.GetStringBuilder().ToString()); } Console.ReadLine(); }
static void MapTypes(XmlSchema schema, XmlSchemaImporter importer, CodeNamespace cns, CodeCompileUnit ccu, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) { XmlCodeExporter exporter = new XmlCodeExporter(cns, ccu, codeProvider, options, mappings); foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } }
public void Start(string sDirIn, string sDirCppXmlOut, string sDirCppBinOut, string sDirJsBinOut, ValidationEventHandler oValidationEventHandler) { string sXsdPath = sDirIn + "xlsx-ext/" + gc_sXsd; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += oValidationEventHandler; schemaSet.Add(null, sXsdPath); schemaSet.Compile(); XmlSchema chartSchema = null; XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { if (schema.TargetNamespace == gc_sTargetNamespace) { 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 = FilterClassesSlicer(aGenClasses); (new CodegenSlicerCPP()).Process(sDirCppXmlOut, aGenClasses, gc_sTargetNamespace); //(new CodegenJS()).Process(sDirJsBinOut, aGenClasses); } }
private static void GenerateForComplexTypes(XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaObject type in xsd.SchemaTypes.Values) { XmlSchemaComplexType ct = type as XmlSchemaComplexType; if (ct != null) { XmlTypeMapping mapping = importer.ImportSchemaType(ct.QualifiedName); exporter.ExportTypeMapping(mapping); } } }
/// <summary> /// Imports XML type definitions as .NET classes. /// </summary> /// <param name="schema">Compiled XML schema.</param> /// <param name="schemaImporter">XML Schema Importer.</param> /// <param name="codeExporter">XML Code Exporter.</param> /// <param name="namespace">Namespace where .NET classes are generated.</param> private static void ImportSchemaAsClasses(XmlSchema schema, XmlSchemaImporter schemaImporter, XmlCodeExporter codeExporter, CodeNamespace @namespace) { foreach (XmlSchemaElement element in schema.Elements.Values) { if (!element.IsAbstract) { XmlTypeMapping xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(xmlTypeMapping); GenerateLoadMethod(xmlTypeMapping, @namespace); } } }
static void Main(string[] args) { var xmlSchemas = new XmlSchemas(); xmlSchemas.Add(XmlSchema.Read(File.OpenRead("name5.xsd"), validationHandler)); xmlSchemas.Compile(validationHandler, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas); CodeNamespace codeNamespace = new CodeNamespace("CSharpGenerated"); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, null, CodeGenerationOptions.None); foreach (XmlSchema xsd in xmlSchemas) { foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType { //Console.WriteLine(schemaType.GetType().Name); codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { //Console.WriteLine(schemaElement.GetType().Name); codeExporter.ExportTypeMapping(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } } RemoveAttributes(codeNamespace); CodeGenerator.ValidateIdentifiers(codeNamespace); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions opts = new CodeGeneratorOptions { BlankLinesBetweenMembers = false, VerbatimOrder = true }; codeProvider.GenerateCodeFromNamespace(codeNamespace, Console.Out, opts); Console.ReadLine(); }
public static void GenerateCode(string xsdFilepath, string codeOutPath, string nameSpace) { FileStream stream = File.OpenRead(xsdFilepath); XmlSchema xsd = XmlSchema.Read(stream, ValidationCallbackOne); // Remove namespaceattribute from schema xsd.TargetNamespace = null; XmlSchemas xsds = new XmlSchemas { xsd }; XmlSchemaImporter imp = new XmlSchemaImporter(xsds); //imp.Extensions.Add(new CustomSchemaImporterExtension()); CodeNamespace ns = new CodeNamespace(nameSpace); XmlCodeExporter exp = new XmlCodeExporter(ns); foreach (XmlSchemaObject item in xsd.Items) { if (!(item is XmlSchemaElement)) { continue; } XmlSchemaElement xmlSchemaElement = (XmlSchemaElement)item; XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(xmlSchemaElement.Name, xsd.TargetNamespace); XmlTypeMapping map = imp.ImportTypeMapping(xmlQualifiedName); exp.ExportTypeMapping(map); } // Remove all the attributes from each type in the CodeNamespace, except // System.Xml.Serialization.XmlTypeAttribute RemoveAttributes(ns); ToProperties(ns); CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(ns); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter(codeOutPath, false)) { CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(compileUnit, sw, codeGeneratorOptions); } }
static void Main(string[] args) { // identify the path to the xsd const string xsdFileName = @"schema.xsd"; var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var xsdPath = Path.Combine(path, xsdFileName); // load the xsd XmlSchema xsd; using (var stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace("Generated"); var codeExporter = new XmlCodeExporter(codeNamespace); var 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 (var map in maps) { codeExporter.ExportTypeMapping(map); } PostProcess(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code var codeProvider = new CSharpCodeProvider(); using (var writer = new StringWriter()) { codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); Console.WriteLine(writer.GetStringBuilder().ToString()); } }
private CodeCompileUnit GenerateTypesWithXmlSchemaImporter(XmlSchemaSet schemas) { CodeNamespace ns = new CodeNamespace(this.targetNamespace); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); schemas.ValidationEventHandler += this.validationEventHandler; try { // Validate schemas schemas.Compile(); XmlSchemas xsds = new XmlSchemas(); foreach (XmlSchema xsd in schemas.Schemas()) { xsds.Add(xsd); } foreach (XmlSchema schema in xsds) { XmlSchemaImporter importer = new XmlSchemaImporter(xsds); XmlCodeExporter exporter = new XmlCodeExporter(ns, unit); // export only elements foreach (XmlSchemaElement schemaElement in schema.Elements.Values) { exporter.ExportTypeMapping(importer.ImportTypeMapping(schemaElement.QualifiedName)); } CodeGenerator.ValidateIdentifiers(ns); } } catch (ArgumentException argumentException) { throw new InvalidOperationException(argumentException.Message, argumentException.InnerException); } finally { schemas.ValidationEventHandler -= this.validationEventHandler; } return(unit); }
private static CodeNamespace CreateCodeNamespaceFromXsds(string[] xsdFiles, string targetNamespace) { XmlSchemaSet schemas = new XmlSchemaSet(); List <XmlQualifiedName> xmlTypes = new List <XmlQualifiedName>(); // Load the XmlSchema and its collection. foreach (string xsdFile in xsdFiles) { using (FileStream fs = new FileStream(xsdFile, FileMode.Open)) { XmlSchema xsd; xsd = XmlSchema.Read(fs, null); schemas.Add(xsd); foreach (XmlSchemaElement element in xsd.Elements.Values) { if (!xmlTypes.Contains(element.QualifiedName)) { xmlTypes.Add(element.QualifiedName); } } } } schemas.Compile(); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(MoveSchemaSetToXmlSchemas(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 (XmlQualifiedName xmlType in xmlTypes) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping(xmlType); // Export the code finally. exporter.ExportTypeMapping(mapping); } RemoveAttributes(ns); return(ns); }
public void XsdToClassTest(IEnumerable <Func <TextReader> > xsds, TextWriter codeWriter) { var schemas = new XmlSchemas(); foreach (var getReader in xsds) { using (var reader = getReader()) { var xsd = XmlSchema.Read(reader, null); schemas.Add(xsd); } } schemas.Compile(null, true); var schemaImporter = new XmlSchemaImporter(schemas); var maps = new List <XmlTypeMapping>(); foreach (XmlSchema xsd in schemas) { 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)); } } // create the codedom var codeNamespace = new CodeNamespace(this.Namespace); var codeExporter = new XmlCodeExporter(codeNamespace); foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } ModifyGeneratedCode(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code var codeProvider = new CSharpCodeProvider(); codeProvider.GenerateCodeFromNamespace(codeNamespace, codeWriter, new CodeGeneratorOptions()); }
private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace) { try { XmlSchema xsd; stream.Seek(0, SeekOrigin.Begin); using (stream) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace(nameSpace); var codeExporter = new XmlCodeExporter(codeNamespace); var 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); } return(codeNamespace); } catch (Exception e) { return(null); } }
/// <summary> /// Generate code for the elements in the Schema /// </summary> /// <param name="xsd"></param> /// <param name="importer"></param> /// <param name="exporter"></param> private void GenerateForElements( XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaElement element in xsd.Elements.Values) { Trace.TraceInformation("Generating for element: {0}", element.Name); try { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } catch (Exception ex) { Trace.TraceEvent(TraceEventType.Error, 10, ex.ToString()); } } }
private void ImportSchemaAsClasses(XmlSchema schema, string uri, IList elements, XmlSchemaImporter schemaImporter, XmlCodeExporter codeExporter) { if (schema == null) { return; } ArrayList arrayList = new ArrayList(); foreach (XmlSchemaElement xmlSchemaElement in schema.Elements.Values) { if (!xmlSchemaElement.IsAbstract && (uri.Length == 0 || xmlSchemaElement.QualifiedName.Namespace == uri)) { bool flag; if (elements.Count == 0) { flag = true; } else { flag = false; foreach (string a in elements) { if (a == xmlSchemaElement.Name) { flag = true; break; } } } if (flag) { arrayList.Add(schemaImporter.ImportTypeMapping(xmlSchemaElement.QualifiedName)); } } } foreach (XmlTypeMapping xmlTypeMapping in arrayList) { codeExporter.ExportTypeMapping(xmlTypeMapping); } }
private static CodeNamespace ProcessSchema(SchemaDefinition schemaDefinition, bool includeDataContractAttributes) { var ns = new CodeNamespace(schemaDefinition.Namespace); var reader = XmlReader.Create(schemaDefinition.SchemaPath); var xsd = XmlSchema.Read(reader, Validate); var schemas = new XmlSchemas(); 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 (var mapping in xsd.Items.OfType <XmlSchemaType>().Select(item => importer.ImportSchemaType(item.QualifiedName))) { exporter.ExportTypeMapping(mapping); } var includes = Helper.GetSchemaIncludes(schemaSet); FilterIncludedTypes(ns, xsd); AddIncludeImports(ns, includes); RemoveXmlRootAttributeForNoneRootTypes(ns, schemaSet); if (includeDataContractAttributes) { AddDataContractAttributes(ns, schemaDefinition.XmlNamespace); } return(ns); }
private CodeCompileUnit ExportCodeFromSchemas(XmlSchemas schemas) { CodeNamespace ns = new CodeNamespace(this.TargetNamespace); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); XmlSchemaImporter importer = new XmlSchemaImporter(schemas, CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync, new ImportContext(new CodeIdentifiers(), true)); XmlCodeExporter exporter = new XmlCodeExporter(ns, unit, CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties); List <XmlTypeMapping> mappings = new List <XmlTypeMapping>(); foreach (XmlSchema xsd in schemas) { foreach (XmlSchemaType type in xsd.SchemaTypes.Values) { mappings.Add(importer.ImportSchemaType(type.QualifiedName)); } if (!this.ProcessComplexTypesOnly) { foreach (XmlSchemaElement element in xsd.Elements.Values) { mappings.Add(importer.ImportTypeMapping(element.QualifiedName)); } } } foreach (XmlTypeMapping mapping in mappings) { exporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(ns); return(unit); }
internal static CodeNamespaceResult CreateCodeNamespace(PhysicalSchema schema, string targetNamespace) { XmlSchemaSet xset = new XmlSchemaSet(); foreach (var file in schema.Files) { var sr = new StringReader(file.Content); xset.Add(XmlSchema.Read(sr, null)); } xset.Compile(); XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema xmlSchema in xset.Schemas()) { schemas.Add(xmlSchema); } XmlSchemaImporter importer = new XmlSchemaImporter(schemas); var ns = new CodeNamespace(targetNamespace); var exporter = new XmlCodeExporter(ns); var result = new CodeNamespaceResult(); foreach (XmlSchemaElement element in xset.GlobalElements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); if (string.IsNullOrEmpty(result.RootElementName)) { result.RootElementName = mapping.TypeName; } exporter.ExportTypeMapping(mapping); } result.Code = ns; return(result); }
private static void ImportSchemaAsClasses(XmlSchema schema, string uri, IList elements, XmlSchemaImporter schemaImporter, XmlCodeExporter codeExporter) { if (schema != null) { ArrayList list = new ArrayList(); foreach (XmlSchemaElement element in schema.Elements.Values) { bool flag; if (element.IsAbstract || ((uri.Length != 0) && !(element.QualifiedName.Namespace == uri))) { continue; } if (elements.Count == 0) { flag = true; } else { flag = false; foreach (string str in elements) { if (str == element.Name) { flag = true; break; } } } if (flag) { list.Add(schemaImporter.ImportTypeMapping(element.QualifiedName)); } } foreach (XmlTypeMapping mapping in list) { codeExporter.ExportTypeMapping(mapping); } } }
} //method GenerateSchemaForDocument private CodeNamespace GenerateCodeForSchema(XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter imp = new XmlSchemaImporter(schemas); CodeNamespace tempSpace = new CodeNamespace(); XmlCodeExporter exp = new XmlCodeExporter(tempSpace); // Iterate schema items (top-level elements only) and generate code for each foreach (XmlSchemaObject item in schema.Items) { if (item is XmlSchemaElement) { // Import the mapping first XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace)); // Export the code finally exp.ExportTypeMapping(map); } //if } //foreach return(tempSpace); } //method GenerateCodeForSchema
public static CodeNamespace Process(string xsdSchema, string modelsNamespace) { // 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(modelsNamespace); 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); }
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); } } }
private static void AddTypes(CodeNamespace codeNamespace, XmlSchemaSet schemaSet) { var schemas = new XmlSchemas(); foreach (var schema in schemaSet.Schemas().Cast <XmlSchema>()) { schemas.Add(schema); } var schemaImporter = new XmlSchemaImporter(schemas); #if NETFRAMEWORK schemaImporter.Extensions.Add(new NodaTimeSchemaImporterExtension()); var codeExporter = new XmlCodeExporter(codeNamespace); foreach (var schemaObject in schemas.SelectMany(e => e.Items.Cast <XmlSchemaObject>())) { XmlTypeMapping mapping; switch (schemaObject) { case XmlSchemaType schemaType: mapping = schemaImporter.ImportSchemaType(schemaType.QualifiedName); break; case XmlSchemaElement schemaElement: mapping = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName); break; default: continue; } codeExporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(codeNamespace); #else throw new PlatformNotSupportedException($"{nameof(XmlCodeExporterAssemblyCreator)} is not available"); #endif }
void ImportHeader(CodeMemberMethod method, SoapHeaderBinding hb, SoapHeaderDirection direction) { Message msg = ServiceDescriptions.GetMessage(hb.Message); if (msg == null) { throw new InvalidOperationException("Message " + hb.Message + " not found"); } MessagePart part = msg.Parts [hb.Part]; if (part == null) { throw new InvalidOperationException("Message part " + hb.Part + " not found in message " + hb.Message); } XmlTypeMapping map; string hname; if (hb.Use == SoapBindingUse.Literal) { map = xmlImporter.ImportDerivedTypeMapping(part.Element, typeof(SoapHeader)); hname = part.Element.Name; xmlExporter.ExportTypeMapping(map); } else { map = soapImporter.ImportDerivedTypeMapping(part.Type, typeof(SoapHeader), true); hname = part.Type.Name; soapExporter.ExportTypeMapping(map); } string varName = headerVariables [map] as string; if (varName == null) { if (hname == map.TypeName) { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname + "Value"), hb); } else { varName = memberIds.AddUnique(CodeIdentifier.MakeValid(hname), hb); } #if NET_2_0 string propName = varName; varName = varName + "Field"; #endif headerVariables.Add(map, varName); CodeMemberField codeField = new CodeMemberField(map.TypeFullName, varName); CodeTypeDeclaration.Members.Add(codeField); #if NET_2_0 codeField.Attributes = MemberAttributes.Private; CodeMemberProperty codeProperty = new CodeMemberProperty(); codeProperty.Name = propName; codeProperty.Type = new CodeTypeReference(map.TypeFullName); codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProperty.HasGet = codeProperty.HasSet = true; CodeExpression ce = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), varName); codeProperty.SetStatements.Add(new CodeAssignStatement(ce, new CodePropertySetValueReferenceExpression())); codeProperty.GetStatements.Add(new CodeMethodReturnStatement(ce)); CodeTypeDeclaration.Members.Add(codeProperty); varName = propName; #else codeField.Attributes = MemberAttributes.Public; #endif } CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.SoapHeaderAttribute"); att.Arguments.Add(GetArg(varName)); #if ONLY_1_0 att.Arguments.Add(GetArg("Required", false)); #endif if (direction != SoapHeaderDirection.In) { att.Arguments.Add(GetEnumArg("Direction", "System.Web.Services.Protocols.SoapHeaderDirection", direction.ToString())); } AddCustomAttribute(method, att, true); }
public void Generate(IList <String> schemas, TextWriter output) { if (Options == null) { Options = new XsdCodeGeneratorOptions { UseLists = true, PropertyNameCapitalizer = new FirstCharacterCapitalizer(), OutputNamespace = "Xsd2", UseNullableTypes = true, AttributesToRemove = { "System.Diagnostics.DebuggerStepThroughAttribute" } }; } if (Options.Imports != null) { foreach (var import in Options.Imports) { if (File.Exists(import)) { ImportImportedSchema(import); } else if (Directory.Exists(import)) { foreach (var file in Directory.GetFiles("*.xsd")) { ImportImportedSchema(file); } } else { throw new InvalidOperationException(String.Format("Import '{0}' is not a file nor a directory.", import)); } } } var inputs = new List <XmlSchema>(); foreach (var path in schemas) { using (var r = File.OpenText(path)) { XmlSchema xsd = XmlSchema.Read(r, null); xsds.Add(xsd); inputs.Add(xsd); } } xsds.Compile(null, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds); // create the codedom CodeNamespace codeNamespace = new CodeNamespace(Options.OutputNamespace); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace); List <XmlTypeMapping> maps = new List <XmlTypeMapping>(); foreach (var xsd in inputs) { foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { if (!ElementBelongsToImportedSchema(schemaElement)) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } } } foreach (var xsd in inputs) { foreach (XmlSchemaComplexType schemaElement in xsd.Items.OfType <XmlSchemaComplexType>()) { maps.Add(schemaImporter.ImportSchemaType(schemaElement.QualifiedName)); } } foreach (var xsd in inputs) { foreach (XmlSchemaSimpleType schemaElement in xsd.Items.OfType <XmlSchemaSimpleType>()) { maps.Add(schemaImporter.ImportSchemaType(schemaElement.QualifiedName)); } } foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } foreach (var xsd in inputs) { ImproveCodeDom(codeNamespace, xsd); } if (OnValidateGeneratedCode != null) { foreach (var xsd in inputs) { OnValidateGeneratedCode(codeNamespace, xsd); } } // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); if (Options.WriteFileHeader) { // output the header string lineCommentCharacter; switch (Options.Language) { case XsdCodeGeneratorOutputLanguage.VB: lineCommentCharacter = "'"; break; default: lineCommentCharacter = "//"; break; } output.WriteLine("{0}------------------------------------------------------------------------------", lineCommentCharacter); output.WriteLine("{0} <auto-generated>", lineCommentCharacter); output.WriteLine("{0} This code has been generated by a tool.", lineCommentCharacter); output.WriteLine("{0} </auto-generated>", lineCommentCharacter); output.WriteLine("{0}------------------------------------------------------------------------------", lineCommentCharacter); output.WriteLine(); } // output the C# code CodeDomProvider codeProvider; switch (Options.Language) { case XsdCodeGeneratorOutputLanguage.VB: codeProvider = new VBCodeProvider(); break; default: codeProvider = new CSharpCodeProvider(); break; } codeProvider.GenerateCodeFromNamespace(codeNamespace, output, new CodeGeneratorOptions()); }
/// <summary> /// Generates the <see cref="CodeNamespace"/> based on the provide context. /// </summary> /// <param name="codeGeneratorContext">The code generator context.</param> public CodeNamespace GenerateCode(ICodeGeneratorContext codeGeneratorContext) { CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions; XmlSchemas xmlSchemas = codeGeneratorContext.XmlSchemas; CodeNamespace codeNamespace = new CodeNamespace(); // Generate DataContracts const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; var exporter = new XmlCodeExporter(codeNamespace); var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); // TypeName to XmlSchemaType mapping IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping; IDictionary <XmlQualifiedName, string> elementName2TypeNameMapping = codeGeneratorContext.ElementName2TypeNameMapping; IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping; foreach (XmlSchema schema in xmlSchemas) { foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName); if (element.IsAbstract) { continue; } exporter.ExportTypeMapping(typeMapping); if (typeMapping.XsdTypeName == "anyType") { continue; // ignore no type element } if (string.IsNullOrWhiteSpace(typeMapping.XsdTypeName)) { throw new Exception("Cannot use anonymous type for Request/Response element: " + element.Name + "."); } typeName2schemaTypeMapping[typeMapping.XsdTypeName] = element.ElementSchemaType; elementName2TypeNameMapping[element.QualifiedName] = typeMapping.XsdTypeName; elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace; } foreach (XmlSchemaType complexType in schema.SchemaTypes.Values) { XmlTypeMapping typeMapping = importer.ImportSchemaType(complexType.QualifiedName); if (DataContractGenerator.CouldBeAnArray(complexType)) { continue; } exporter.ExportTypeMapping(typeMapping); typeName2schemaTypeMapping[typeMapping.TypeName] = complexType; } } if (codeNamespace.Types.Count == 0) { throw new Exception("No types were generated."); } // Build type name to code type declaration mapping codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespace); // Decorate data contracts code ICodeExtension codeExtension = new CodeExtension(); codeExtension.Process(codeNamespace, codeGeneratorContext); codeNamespace.ImplementsBaijiSerialization(codeGeneratorContext); // Generate interface code string wsdlFile = codeGeneratorContext.CodeGenOptions.MetadataLocation; InterfaceContract interfaceContract = ServiceDescriptionEngine.GetInterfaceContract(wsdlFile); CodeTypeDeclaration codeType; CodeNamespaceImportCollection imports; this.buildInterfaceCode(codeGeneratorContext, interfaceContract, out codeType, out imports); codeNamespace.Types.Add(codeType); foreach (CodeNamespaceImport @import in imports) { codeNamespace.Imports.Add(@import); } // Import SOA common type namespace before removing code types codeNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE)); // Remove SOA common types since they have already been included in CSerivceStack DLL CodeExtension.RemoveSOACommonTypes(codeNamespace); CodeExtension.RemoveDefaultTypes(codeNamespace); return(codeNamespace); }