Esempio n. 1
0
        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);
        }
Esempio n. 2
0
 private static void ImportXmlSchema(XmlSchema schema, XmlSchemaImporter importer, XmlCodeExporter exporter)
 {
     foreach (XmlSchemaElement element in schema.Elements.Values)
     {
         exporter.ExportTypeMapping(importer.ImportTypeMapping(element.QualifiedName));
     }
 }
Esempio n. 3
0
        private QName ImportInternal(XmlSchemaSet schemas, QName qname)
        {
            if (qname.Namespace == KnownTypeCollection.MSSimpleNamespace)
            {
                //Primitive type
                return(qname);
            }

            if (imported_names.ContainsKey(qname))
            {
                return(imported_names [qname]);
            }

            XmlSchemas xss = new XmlSchemas();

            foreach (XmlSchema schema in schemas.Schemas())
            {
                xss.Add(schema);
            }

            XmlSchemaImporter xsi = new XmlSchemaImporter(xss);
            XmlTypeMapping    xtm = xsi.ImportTypeMapping(qname);

            ImportFromTypeMapping(xtm);
            return(qname);
        }
Esempio n. 4
0
        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);
        }
        /// <summary>
        /// Performs building codedom tree objects from Xsd schema
        /// </summary>
        /// <param name="xsdContext">Holds data about XSD schema</param>
        /// <param name="codeDomContext">Holds codeDomTree</param>
        public void Execute(XsdContext xsdContext, CodeDomContext codeDomContext)
        {
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsdContext.XmlSchemas);

            // Step 1:  Create code namespace
            xsdContext.CodeExporter = new XmlCodeExporter(codeDomContext.CodeNamespace);

            List <object> maps = new List <object>();

            // Find out schema types of objects and add to collection
            foreach (XmlSchema xsd in xsdContext.XmlSchemaList)
            {
                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));
                }
            }

            // export object collection to namespace. Now defined namespace will have all schema objects such as complexTypes, simpleTypes etc.
            foreach (XmlTypeMapping map in maps)
            {
                xsdContext.CodeExporter.ExportTypeMapping(map);
            }
        }
Esempio n. 6
0
        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();
        }
Esempio n. 7
0
 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);
     }
 }
Esempio n. 8
0
        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();
        }
Esempio n. 9
0
        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);
            }
        }
Esempio n. 10
0
        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);
            }
        }
Esempio n. 11
0
        /// <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);
                }
            }
        }
Esempio n. 12
0
        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);
            }
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var xmlSchemas = new XmlSchemas();

            xmlSchemas.Add(XmlSchema.Read(File.OpenRead("contacts.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 (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    Console.WriteLine($"{schemaElement.Name} is {schemaElement.GetType().Name}");
                    var t = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName);
                    codeExporter.ExportTypeMapping(t);
                }
                foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType
                {
                    var t = schemaImporter.ImportSchemaType(schemaType.QualifiedName);
                    Console.WriteLine($"{schemaType.Name} is a {schemaType.GetType().Name}");
                    // Generates far to many xmlroot attributes
                    //codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
                }
            }

            RemoveAttributes(codeNamespace);
            CodeGenerator.ValidateIdentifiers(codeNamespace);
            CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions opts         = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = false,
                VerbatimOrder            = true
            };

            codeProvider.GenerateCodeFromNamespace(codeNamespace, Console.Out, opts);

            foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
            {
                Console.WriteLine($"{codeType.Name} is a {codeType.GetType().Name}");
                var t = codeType.TypeParameters;
            }

            Console.ReadLine();
        }
Esempio n. 14
0
        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());
            }
        }
Esempio n. 15
0
        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);
        }
Esempio n. 16
0
        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);
        }
Esempio n. 17
0
        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);
            }
        }
    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());
    }
Esempio n. 19
0
        /// <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());
                }
            }
        }
Esempio n. 20
0
        public static void BuildElementName2TargetNamespaceMapping(ICodeGeneratorContext codeGeneratorContext)
        {
            XmlSchemas    xmlSchemas    = codeGeneratorContext.XmlSchemas;
            CodeNamespace codeNamespace = new CodeNamespace();

            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;
            var exporter = new XmlCodeExporter(codeNamespace);
            var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace;
                }
            }
        }
Esempio n. 21
0
        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);
            }
        }
        XmlTypeMapping ImportOutMembersMapping(Message msg)
        {
            if (msg.Parts.Count == 0)
            {
                return(null);
            }

            if (msg.Parts[0].Name == "Body" && msg.Parts[0].Element == XmlQualifiedName.Empty)
            {
                return(xmlReflectionImporter.ImportTypeMapping(typeof(XmlNode)));
            }
            else
            {
                // This is a bit hacky. The issue is that types such as string[] are to be imported
                // as such, not as ArrayOfString class. ImportTypeMapping will return a
                // class if the type has not been imported as an array before, hence the
                // call to ImportMembersMapping.
                xmlImporter.ImportMembersMapping(new XmlQualifiedName[] { msg.Parts[0].Element });
                return(xmlImporter.ImportTypeMapping(msg.Parts[0].Element));
            }
        }
        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);
        }
Esempio n. 24
0
        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);
        }
Esempio n. 25
0
        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);
                }
            }
        }
Esempio n. 26
0
        }         //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
Esempio n. 27
0
        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);
        }
Esempio n. 28
0
        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
            }
Esempio n. 30
0
        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());
        }