internal static StringCollection Compile(XmlSchemas schemas)
 {
     AddImports(schemas);
     Warnings.Clear();
     schemas.Compile(new ValidationEventHandler(SchemaCompiler.ValidationCallbackWithErrorCode), true);
     return Warnings;
 }
Beispiel #2
0
        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;
        }
        private static void Main(string[] args)
        {
            XmlSchema rootSchema = GetSchemaFromFile("fpml-main-4-2.xsd");

            var schemaSet = new List<XmlSchemaExternal>();

            ExtractIncludes(rootSchema, ref schemaSet);

            var schemas = new XmlSchemas { rootSchema };

            schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation)));

            schemas.Compile(null, true);

            var xmlSchemaImporter = new XmlSchemaImporter(schemas);

            var codeNamespace = new CodeNamespace("Hosca.FpML4_2");
            var xmlCodeExporter = new XmlCodeExporter(codeNamespace);

            var xmlTypeMappings = new List<XmlTypeMapping>();

            foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName));
            foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName));

            xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping);

            CodeGenerator.ValidateIdentifiers(codeNamespace);

            foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types)
            {
                for (int i = codeTypeDeclaration.CustomAttributes.Count - 1; i >= 0; i--)
                {
                    CodeAttributeDeclaration cad = codeTypeDeclaration.CustomAttributes[i];
                    if (cad.Name == "System.CodeDom.Compiler.GeneratedCodeAttribute")
                        codeTypeDeclaration.CustomAttributes.RemoveAt(i);
                }
            }

            using (var writer = new StringWriter())
            {
                new CSharpCodeProvider().GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());

                //Console.WriteLine(writer.GetStringBuilder().ToString());

                File.WriteAllText(Path.Combine(rootFolder, "FpML4_2.Generated.cs"), writer.GetStringBuilder().ToString());
            }

            Console.ReadLine();
        }
 internal SchemaGraph(Hashtable scope, XmlSchemas schemas)
 {
     this.scope = scope;
     schemas.Compile(null, false);
     this.schemas = schemas;
     items        = 0;
     foreach (XmlSchema s in schemas)
     {
         items += s.Items.Count;
         foreach (XmlSchemaObject item in s.Items)
         {
             Depends(item);
         }
     }
 }
 internal SchemaGraph(Hashtable scope, XmlSchemas schemas)
 {
     this.scope = scope;
     schemas.Compile(null, false);
     this.schemas = schemas;
     this.items = 0;
     foreach (XmlSchema schema in schemas)
     {
         this.items += schema.Items.Count;
         foreach (XmlSchemaObject obj2 in schema.Items)
         {
             this.Depends(obj2);
         }
     }
 }
 internal SchemaGraph(Hashtable scope, XmlSchemas schemas)
 {
     this.scope = scope;
     schemas.Compile(null, false);
     this.schemas = schemas;
     this.items   = 0;
     foreach (XmlSchema schema in schemas)
     {
         this.items += schema.Items.Count;
         foreach (XmlSchemaObject obj2 in schema.Items)
         {
             this.Depends(obj2);
         }
     }
 }
Beispiel #7
0
        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;
        }
        /// <summary>
        /// Generate a set of schemas from the given types
        /// </summary>
        /// <param name="types">Array of types to generate schemas from</param>
        /// <returns>An array of schemas</returns>
        public IList<XmlSchema> GenerateSchemas(Type[] types)
        {
            Trace.Assert(types != null);
            if (types.Length == 0) return null;

            #region generate the schema from the type
            XmlReflectionImporter reflectionImporter = new XmlReflectionImporter();

            XmlSchemas schemas = new XmlSchemas();

            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

            foreach (Type type in types)
            {
                // we can provide the default namespace as a parameter here
                XmlTypeMapping map = reflectionImporter.ImportTypeMapping(type);

                exporter.ExportTypeMapping(map);
            }
            #endregion

            // compile the schemas to make sure they were generated correctly
            schemas.Compile(null, true);

            ResolveImportedSchemas(schemas, types[0].Name);

            // convert the generated schemas to an array of schemas
            return XmlSchemasToArray(schemas);
        }
 internal SchemaGraph(Hashtable scope, XmlSchemas schemas) {
     this.scope = scope;
     schemas.Compile(null, false);
     this.schemas = schemas;
     items = 0;
     foreach(XmlSchema s in schemas) {
         items += s.Items.Count;
         foreach (XmlSchemaObject item in s.Items) {
             Depends(item);
         }
     }
 }
 private static void Compile(XmlSchemas userSchemas, Hashtable uris, Hashtable includeSchemas)
 {
     foreach (XmlSchema schema in userSchemas)
     {
         if ((schema.TargetNamespace != null) && (schema.TargetNamespace.Length == 0))
         {
             schema.TargetNamespace = null;
         }
         Uri baseUri = (Uri)uris[schema];
         CollectIncludes(schema, baseUri, includeSchemas, baseUri.ToString().ToLower(CultureInfo.InvariantCulture));
     }
     try
     {
         userSchemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true);
     }
     catch (Exception ex)
     {
         throw new ArgumentException("Compile Xsd Error!", ex);
     }
     if (!userSchemas.IsCompiled)
     {
         throw new ArgumentException("Compile Xsd Error!");
     }
 }
        private ServiceDescriptionImportWarnings Import(CodeNamespace codeNamespace, ImportContext importContext, Hashtable exportContext, StringCollection warnings) {
            allSchemas = new XmlSchemas();
            foreach (XmlSchema schema in schemas) {
                allSchemas.Add(schema);
            }
            foreach (ServiceDescription description in serviceDescriptions) {
                foreach (XmlSchema schema in description.Types.Schemas) {
                    allSchemas.Add(schema);
                }
            }
            Hashtable references = new Hashtable();
            if (!allSchemas.Contains(ServiceDescription.Namespace)) {
                allSchemas.AddReference(ServiceDescription.Schema);
                references[ServiceDescription.Schema] = ServiceDescription.Schema;
            }
            if (!allSchemas.Contains(Soap.Encoding)) { 
                allSchemas.AddReference(ServiceDescription.SoapEncodingSchema);
                references[ServiceDescription.SoapEncodingSchema] = ServiceDescription.SoapEncodingSchema;
            }
            allSchemas.Compile(null, false);

            // Segregate the schemas containing abstract types from those 
            // containing regular XML definitions.  This is important because
            // when you import something returning the ur-type (object), then
            // you need to import ALL types/elements within ALL schemas.  We
            // don't want the RPC-based types leaking over into the XML-based
            // element definitions.  This also occurs when you have derivation:
            // we need to search the schemas for derived types: but WHICH schemas
            // should we search.
            foreach (ServiceDescription description in serviceDescriptions) {
                foreach (Message message in description.Messages) {
                    foreach (MessagePart part in message.Parts) {
                        bool isEncoded;
                        bool isLiteral;
                        FindUse(part, out isEncoded, out isLiteral);
                        if (part.Element != null && !part.Element.IsEmpty) {
                            if (isEncoded) throw new InvalidOperationException(Res.GetString(Res.CanTSpecifyElementOnEncodedMessagePartsPart, part.Name, message.Name));
                            XmlSchemaElement element = (XmlSchemaElement)allSchemas.Find(part.Element, typeof(XmlSchemaElement));
                            if (element != null) {
                                AddSchema(element.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                                if (element.SchemaTypeName != null && !element.SchemaTypeName.IsEmpty) {
                                    XmlSchemaType type = (XmlSchemaType)allSchemas.Find(element.SchemaTypeName, typeof(XmlSchemaType));
                                    if (type != null) {
                                        AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                                    }
                                }
                            }
                        }
                        if (part.Type != null && !part.Type.IsEmpty) {
                            XmlSchemaType type = (XmlSchemaType)allSchemas.Find(part.Type, typeof(XmlSchemaType));
                            if (type != null) {
                                AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                            }
                        }
                    }
                }
            }

            Hashtable imports;
            foreach (XmlSchemas xmlschemas in new XmlSchemas[] { abstractSchemas, concreteSchemas }) {
                // collect all imports
                imports = new Hashtable();
                foreach (XmlSchema schema in xmlschemas) {
                    AddImport(schema, imports);
                }
                // make sure we add them to the corresponding schema collections
                foreach (XmlSchema schema in imports.Keys) {
                    if (references[schema] == null && !xmlschemas.Contains(schema)) {
                        xmlschemas.Add(schema);
                    }
                }
            }

            // If a schema was not referenced by either a literal or an encoded message part,
            // add it to both collections. There's no way to tell which it should be.
            imports = new Hashtable();
            foreach (XmlSchema schema in allSchemas) {
                if (!abstractSchemas.Contains(schema) && !concreteSchemas.Contains(schema)) {
                    AddImport(schema, imports);
                }
            }

            // make sure we add them to the corresponding schema collections
            foreach (XmlSchema schema in imports.Keys) {
                if (references[schema] != null)
                    continue;
                if (!abstractSchemas.Contains(schema)) {
                    abstractSchemas.Add(schema);
                }
                if (!concreteSchemas.Contains(schema)) {
                    concreteSchemas.Add(schema);
                }
            }
            if (abstractSchemas.Count > 0) {
                foreach (XmlSchema schema in references.Values) {
                    abstractSchemas.AddReference(schema);
                }
                StringCollection schemaWarnings = SchemaCompiler.Compile(abstractSchemas);
                foreach (string warning in schemaWarnings)
                    warnings.Add(warning);
            }
            if (concreteSchemas.Count > 0) {
                foreach (XmlSchema schema in references.Values) {
                    concreteSchemas.AddReference(schema);
                }
                StringCollection schemaWarnings = SchemaCompiler.Compile(concreteSchemas);
                foreach (string warning in schemaWarnings)
                    warnings.Add(warning);
            }
            if (ProtocolName.Length > 0) {
                // If a protocol was specified, only try that one
                ProtocolImporter importer = FindImporterByName(ProtocolName);
                if (importer.GenerateCode(codeNamespace, importContext, exportContext)) return importer.Warnings;
            }
            else {
                // Otherwise, do "best" protocol (first one that generates something)
                for (int i = 0; i < importers.Length; i++) {
                    ProtocolImporter importer = importers[i];
                    if (importer.GenerateCode(codeNamespace, importContext, exportContext)) {
                        return importer.Warnings;
                    }
                }
            }
            return ServiceDescriptionImportWarnings.NoCodeGenerated;
        }
Beispiel #12
0
 /// <summary>
 /// Compiles collection of XML schemas.
 /// </summary>
 /// <param name="schemas">Collection of XML schemas.</param>
 private void CompileSchemas(XmlSchemas schemas)
 {
     schemas.Compile(this.ValidationErrorHandler, true);
     if (!schemas.IsCompiled)
     {
         CompilerError error = new CompilerError();
         error.FileName = Host.TemplateFile;
         error.ErrorText = "Schema could not be compiled";
         error.IsWarning = true;
         this.Errors.Add(error);
     }
 }
Beispiel #13
0
        public Program(params string[] args)
        {
            XmlSchemas xsds = new XmlSchemas();
            var i = 0;
            while (!args[i].StartsWith("/o:") || i >= args.Length)
            {
                xsds.Add(GetSchema(args[i]));
                i++;
            }

            var output = string.Empty;
            if (args[i].StartsWith("/o:"))
            {
                output = args[i].Substring(3);
            }

            xsds.Compile(null, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds, CodeGenerationOptions.GenerateOrder, null);

            // create the codedom
            var codeNamespace = new CodeNamespace("QbSync.QbXml.Objects");
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            compileUnit.Namespaces.Add(codeNamespace);
            var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateOrder);

            foreach (XmlSchema xsd in xsds)
            {
                ArrayList maps = new ArrayList();
                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);
                }
            }

            var typeEnhancer = new TypeEnhancer(codeNamespace, xsds);
            typeEnhancer.Enhance();

            // Add a comment at the top of the file
            var x = fileComment.Split('\n').Select(m => new CodeCommentStatement(m)).ToArray();
            codeNamespace.Comments.AddRange(x);

            // 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
                {
                    BlankLinesBetweenMembers = true,
                    BracingStyle = "C",
                    ElseOnClosing = true,
                    IndentString = "    "
                });

                string content = writer.GetStringBuilder().ToString();
                if (string.IsNullOrEmpty(output))
                {
                    Console.WriteLine(content);
                    Console.ReadLine();
                }
                else
                {
                    File.WriteAllText(output, content);
                }
            }
        }