public ImportTypeMapping ( |
||
name | ||
리턴 |
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 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; }
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(); }
public void ImportTypeMapping_Struct () { XmlSchemas schemas = ExportType (typeof (TimeSpan)); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#2"); Assert.AreEqual ("TimeSpan", map.ElementName, "#3"); Assert.AreEqual ("NSTimeSpan", map.Namespace, "#4"); Assert.AreEqual ("TimeSpan", map.TypeFullName, "#5"); Assert.AreEqual ("TimeSpan", map.TypeName, "#6"); }
[Category ("NotWorking")] // mark it NotWorking until fixes have landed in svn public void ImportTypeMapping_XsdPrimitive_AnyType () { XmlSchemas schemas = ExportType (typeof (object)); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#2"); Assert.AreEqual ("anyType", map.ElementName, "#3"); Assert.AreEqual ("NSObject", map.Namespace, "#4"); Assert.AreEqual ("System.Object", map.TypeFullName, "#5"); Assert.AreEqual ("Object", map.TypeName, "#6"); }
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); } }
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); } } }
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()); }
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 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; }
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; }
/// <summary> /// Generates the data contracts for given xsd file(s). /// </summary> public CodeNamespace GenerateCode() { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(options.ClrNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); // Build the code generation options. GenerationOptions generationOptions = GenerationOptions.None; if (options.GenerateProperties) { generationOptions |= GenerationOptions.GenerateProperties; } if (options.EnableDataBinding) { generationOptions |= GenerationOptions.EnableDataBinding; } if (options.GenerateOrderIdentifiers) { generationOptions |= GenerationOptions.GenerateOrder; } // Build the CodeDom object graph. XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit, generationOptions, null); CodeIdentifiers codeIdentifiers = new CodeIdentifiers(); ImportContext importContext = new ImportContext(codeIdentifiers, false); XmlSchemaImporter schemaimporter = new XmlSchemaImporter(schemas, generationOptions, codeProvider, importContext); for (int si = 0; si < schemas.Count; si++) { XmlSchema schema = schemas[si]; IEnumerator enumerator = schema.Elements.Values.GetEnumerator(); IEnumerator enumerator2 = schema.SchemaTypes.Values.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlSchemaElement element = (XmlSchemaElement)enumerator.Current; if (element.IsAbstract) continue; XmlTypeMapping typemapping = schemaimporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(typemapping); } while (enumerator2.MoveNext()) { XmlSchemaType type = (XmlSchemaType)enumerator2.Current; if (CouldBeAnArray(type)) continue; XmlTypeMapping typemapping = schemaimporter.ImportSchemaType(type.QualifiedName); codeExporter.ExportTypeMapping(typemapping); } } finally { IDisposable disposableobject = enumerator as IDisposable; if (disposableobject != null) { disposableobject.Dispose(); } IDisposable disposableobject2 = enumerator2 as IDisposable; if (disposableobject2 != null) { disposableobject2.Dispose(); } } } if (codeNamespace.Types.Count == 0) { throw new Exception("No types were generated."); } return codeNamespace; }
/// <summary> /// Processes the schema. /// </summary> /// <param name="xsdFile">The full path to the WXS file to process.</param> /// <param name="targetNamespace">The namespace to put generated classes in.</param> /// <returns>The CodeDom tree generated from the schema.</returns> public static CodeNamespace Process(string xsdFile, string targetNamespace, CodeDomProvider Provider) { // Load the XmlSchema and its collection. //XmlSchema xsd; //using ( FileStream fs = new FileStream( xsdFile, FileMode.Open ) ) //{ // xsd = XmlSchema.Read( fs, VH1 ); // xsd.Compile( VH2 ); //} XmlSchemaSet set = new XmlSchemaSet(); XmlSchema xsd = set.Add(null, xsdFile); set.Compile(); 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 set.GlobalElements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } #region Execute extensions XPathNavigator nav; using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) { nav = new XPathDocument(fs).CreateNavigator(); } XPathNodeIterator it = nav.Select(Extensions); while (it.MoveNext()) { Dictionary<string, string> values = ParsePEValue(it.Current.Value); Type t = Type.GetType(values["extension-type"], true); // Is the type an ICodeExtension? Type iface = t.GetInterface(typeof(ICodeExtension).Name); if (iface == null) throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value)); ICodeExtension ext = (ICodeExtension)Activator.CreateInstance(t); ext.Initialize(values); // Run it! ext.Process(ns, xsd, Provider); } #endregion Execute extensions return ns; }
public void ImportTypeMapping_XsdPrimitive_AnyURI () { string schemaFragment = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<xs:schema xmlns:tns=\"NSAnyURI\" elementFormDefault=\"qualified\" targetNamespace=\"NSAnyURI\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"anyURI\" type=\"xs:anyURI\" />" + "</xs:schema>"; XmlSchemas schemas = new XmlSchemas (); schemas.Add (XmlSchema.Read (new StringReader (schemaFragment), null)); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlQualifiedName qname = (XmlQualifiedName) qnames[0]; Assert.AreEqual ("anyURI", qname.Name, "#2"); Assert.AreEqual ("NSAnyURI", qname.Namespace, "#3"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#4"); Assert.AreEqual ("anyURI", map.ElementName, "#5"); Assert.AreEqual ("NSAnyURI", map.Namespace, "#6"); Assert.AreEqual ("System.String", map.TypeFullName, "#7"); Assert.AreEqual ("String", map.TypeName, "#8"); }
public void ImportTypeMapping_EnumSimpleContent () { string schemaFragment = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<s:schema xmlns:tns=\"NSDate\" elementFormDefault=\"qualified\" targetNamespace=\"NSDate\" xmlns:s=\"http://www.w3.org/2001/XMLSchema\">" + " <s:element name=\"trans\" type=\"tns:TranslationStatus\" />" + " <s:complexType name=\"TranslationStatus\">" + " <s:simpleContent>" + " <s:extension base=\"tns:StatusType\">" + " <s:attribute name=\"Language\" type=\"s:int\" use=\"required\" />" + " </s:extension>" + " </s:simpleContent>" + " </s:complexType>" + " <s:simpleType name=\"StatusType\">" + " <s:restriction base=\"s:string\">" + " <s:enumeration value=\"Untouched\" />" + " <s:enumeration value=\"Touched\" />" + " <s:enumeration value=\"Complete\" />" + " <s:enumeration value=\"None\" />" + " </s:restriction>" + " </s:simpleType>" + "</s:schema>"; XmlSchemas schemas = new XmlSchemas (); schemas.Add (XmlSchema.Read (new StringReader (schemaFragment), null)); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlQualifiedName qname = (XmlQualifiedName) qnames[0]; Assert.AreEqual ("trans", qname.Name, "#2"); Assert.AreEqual ("NSDate", qname.Namespace, "#3"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#4"); Assert.AreEqual ("trans", map.ElementName, "#5"); Assert.AreEqual ("NSDate", map.Namespace, "#6"); Assert.AreEqual ("TranslationStatus", map.TypeFullName, "#7"); Assert.AreEqual ("TranslationStatus", map.TypeName, "#8"); CodeNamespace codeNamespace = ExportCode (map); Assert.IsNotNull (codeNamespace, "#9"); CodeTypeDeclaration type = FindType (codeNamespace, "TranslationStatus"); Assert.IsNotNull (type, "#10"); #if NET_2_0 CodeMemberProperty property = FindMember (type, "Value") as CodeMemberProperty; Assert.IsNotNull (property, "#A1"); Assert.IsTrue (property.HasGet, "#A2"); Assert.IsTrue (property.HasSet, "#A3"); Assert.AreEqual ("StatusType", property.Type.BaseType, "#A4"); CodeMemberField field = FindMember (type, "valueField") as CodeMemberField; Assert.IsNotNull (field, "#A5"); Assert.AreEqual ("StatusType", field.Type.BaseType, "#A6"); property = FindMember (type, "Language") as CodeMemberProperty; Assert.IsNotNull (property, "#B1"); Assert.IsTrue (property.HasGet, "#B2"); Assert.IsTrue (property.HasSet, "#B3"); Assert.AreEqual ("System.Int32", property.Type.BaseType, "#B4"); field = FindMember (type, "languageField") as CodeMemberField; Assert.IsNotNull (field, "#B5"); Assert.AreEqual ("System.Int32", field.Type.BaseType, "#B6"); #else CodeMemberField field = FindMember (type, "Value") as CodeMemberField; Assert.IsNotNull (field, "#A1"); Assert.AreEqual ("StatusType", field.Type.BaseType, "#A2"); field = FindMember (type, "Language") as CodeMemberField; Assert.IsNotNull (field, "#B1"); Assert.AreEqual ("System.Int32", field.Type.BaseType, "#B2"); #endif }
public void ImportTypeMapping_XsdPrimitive_UnsignedLong () { XmlSchemas schemas = ExportType (typeof (ulong)); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#2"); Assert.AreEqual ("unsignedLong", map.ElementName, "#3"); Assert.AreEqual ("NSUInt64", map.Namespace, "#4"); Assert.AreEqual ("System.UInt64", map.TypeFullName, "#5"); Assert.AreEqual ("UInt64", map.TypeName, "#6"); }
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 void ImportTypeMapping_XsdPrimitive_Guid () { string schemaFragment = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<xs:schema xmlns:tns=\"NSGuid\" elementFormDefault=\"qualified\" targetNamespace=\"NSGuid\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"guid\" type=\"xs:guid\" />" + "</xs:schema>"; XmlSchemas schemas = new XmlSchemas (); schemas.Add (XmlSchema.Read (new StringReader (schemaFragment), null)); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping (new XmlQualifiedName ("guid", "NSGuid")); Assert.IsNotNull (map, "#A1"); Assert.AreEqual ("guid", map.ElementName, "#A2"); Assert.AreEqual ("NSGuid", map.Namespace, "#A3"); Assert.AreEqual ("System.String", map.TypeFullName, "#A4"); Assert.AreEqual ("String", map.TypeName, "#A5"); #if ONLY_1_1 schemas = ExportType (typeof (Guid)); importer = new XmlSchemaImporter (schemas); map = importer.ImportTypeMapping (new XmlQualifiedName ("guid", "NSGuid")); Assert.IsNotNull (map, "#B1"); Assert.AreEqual ("guid", map.ElementName, "#B2"); Assert.AreEqual ("NSGuid", map.Namespace, "#B3"); Assert.AreEqual ("System.Guid", map.TypeFullName, "#B4"); Assert.AreEqual ("Guid", map.TypeName, "#B5"); #endif }
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(); }
public void ImportTypeMapping_XsdPrimitive_Base64Binary () { XmlSchemas schemas = ExportType (typeof (byte[])); ArrayList qnames = GetXmlQualifiedNames (schemas); Assert.AreEqual (1, qnames.Count, "#1"); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping ((XmlQualifiedName) qnames[0]); Assert.IsNotNull (map, "#2"); Assert.AreEqual ("base64Binary", map.ElementName, "#3"); Assert.AreEqual ("NSByte[]", map.Namespace, "#4"); Assert.AreEqual ("System.Byte[]", map.TypeFullName, "#5"); Assert.AreEqual ("Byte[]", map.TypeName, "#6"); }
public void DefaultTypeTopLevelElementImportsAllComplexTypes () { string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Root' /> <xs:complexType name='FooType'> <xs:sequence> <xs:element name='Child1' type='xs:string' /> <xs:element name='Child2' type='xs:string' /> <xs:element name='Child3' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:complexType name='BarType' /> </xs:schema>"; XmlSchemas xss = new XmlSchemas (); xss.Add (XmlSchema.Read (new XmlTextReader (new StringReader (xsd)), null)); XmlSchemaImporter imp = new XmlSchemaImporter (xss); CodeNamespace cns = new CodeNamespace (); XmlCodeExporter exp = new XmlCodeExporter (cns); exp.ExportTypeMapping (imp.ImportTypeMapping (new XmlQualifiedName ("Root"))); bool foo = false, bar = false; foreach (CodeTypeDeclaration td in cns.Types) { if (td.Name == "FooType") foo = true; else if (td.Name == "BarType") bar = true; } Assert.IsTrue (foo, "FooType not found"); Assert.IsTrue (bar, "BarType not found"); }
public void ImportTypeMappingNonExistent () { XmlSchemas xss = new XmlSchemas (); xss.Add (new XmlSchema ()); XmlSchemaImporter imp = new XmlSchemaImporter (xss); imp.ImportTypeMapping (new XmlQualifiedName ("foo")); }
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); }
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; }
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); } }
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); } } }
/// <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 void ImportTypeMapping_XsdPrimitive_TimePeriod () { string schemaFragment = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + "<xs:schema xmlns:tns=\"NSTimePeriod\" elementFormDefault=\"qualified\" targetNamespace=\"NSTimePeriod\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + " <xs:element name=\"timePeriod\" type=\"xs:timePeriod\" />" + "</xs:schema>"; XmlSchemas schemas = new XmlSchemas (); schemas.Add (XmlSchema.Read (new StringReader (schemaFragment), null)); XmlSchemaImporter importer = new XmlSchemaImporter (schemas); XmlTypeMapping map = importer.ImportTypeMapping (new XmlQualifiedName ("timePeriod", "NSTimePeriod")); Assert.IsNotNull (map, "#4"); Assert.AreEqual ("timePeriod", map.ElementName, "#5"); Assert.AreEqual ("NSTimePeriod", map.Namespace, "#6"); Assert.AreEqual ("System.String", map.TypeFullName, "#7"); Assert.AreEqual ("String", map.TypeName, "#8"); }
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); }
/// <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); } } }