Exemple #1
0
        void AddIncludingSchema(XmlSchemas list, string ns)
        {
            XmlSchema sc = Schemas [ns];

            if (sc == null || list.Contains(sc))
            {
                return;
            }
            list.Add(sc);
            foreach (XmlSchemaObject ob in sc.Includes)
            {
                XmlSchemaImport import = ob as XmlSchemaImport;
                if (import != null)
                {
                    AddIncludingSchema(list, import.Namespace);
                }
            }
        }
Exemple #2
0
        private void AddDocument(string path, object document, XmlSchemas schemas,
                                 ServiceDescriptionCollection descriptions)
        {
            var serviceDescription = document as ServiceDescription;

            if (serviceDescription != null)
            {
                if (descriptions[serviceDescription.TargetNamespace] == null)
                {
                    descriptions.Add(serviceDescription);
                    var w      = new StringWriter();
                    var writer = new XmlTextWriter(w);
                    writer.Formatting = Formatting.Indented;
                    serviceDescription.Write(writer);
                    wsdls.Add(w.ToString());
                }
                else
                {
                    CheckPoint(MessageType.Warning,
                               string.Format(duplicateService, serviceDescription.TargetNamespace, path));
                }
            }
            else
            {
                var schema = document as XmlSchema;
                if (schema != null)
                {
                    if (schemas[schema.TargetNamespace] == null)
                    {
                        schemas.Add(schema);
                        var writer3 = new StringWriter();
                        var writer4 = new XmlTextWriter(writer3);
                        writer4.Formatting = Formatting.Indented;
                        schema.Write(writer4);
                        xsds.Add(writer3.ToString());
                    }
                    else
                    {
                        CheckPoint(MessageType.Warning,
                                   string.Format(duplicateSchema, serviceDescription.TargetNamespace, path));
                    }
                }
            }
        }
Exemple #3
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);
            }
        }
Exemple #4
0
        private void AddDocument(string path, object document, XmlSchemas schemas,
                                 ServiceDescriptionCollection descriptions)
        {
            ServiceDescription description1 = document as ServiceDescription;

            if (description1 != null)
            {
                if (descriptions[description1.TargetNamespace] == null)
                {
                    descriptions.Add(description1);
                    StringWriter  writer1 = new StringWriter();
                    XmlTextWriter writer2 = new XmlTextWriter(writer1);
                    writer2.Formatting = Formatting.Indented;
                    description1.Write(writer2);
                    wsdls.Add(writer1.ToString());
                }
                else
                {
                    CheckPoint(MessageType.Warning, string.Format(duplicateService, description1.TargetNamespace, path));
                }
            }
            else
            {
                XmlSchema schema1 = document as XmlSchema;
                if (schema1 != null)
                {
                    if (schemas[schema1.TargetNamespace] == null)
                    {
                        schemas.Add(schema1);
                        StringWriter  writer3 = new StringWriter();
                        XmlTextWriter writer4 = new XmlTextWriter(writer3);
                        writer4.Formatting = Formatting.Indented;
                        schema1.Write(writer4);
                        xsds.Add(writer3.ToString());
                    }
                    else
                    {
                        CheckPoint(MessageType.Warning,
                                   string.Format(duplicateSchema, description1.TargetNamespace, path));
                    }
                }
            }
        }
    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());
    }
Exemple #6
0
        /// <summary>
        /// Loads external schemas for each schema in the collection.
        /// </summary>
        /// <param name="schemas">Collection of XML schemas.</param>
        /// <remarks>
        /// External schemas are those schemas referenced by import and include schema elements.
        /// </remarks>
        private void ReadExternalSchemas(XmlSchemas schemas)
        {
            Dictionary <string, XmlSchema> externalSchemas = new Dictionary <string, XmlSchema>();

            foreach (XmlSchema schema in schemas)
            {
                if (schema.TargetNamespace != null && schema.TargetNamespace.Length == 0)
                {
                    schema.TargetNamespace = null;
                }

                this.ReadExternalSchemas(schema, externalSchemas, schema);
            }

            foreach (XmlSchema schema in externalSchemas.Values)
            {
                schemas.Add(schema);
            }
        }
Exemple #7
0
        public void ExportEndpoint()
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "ExportEndpoint");

            try
            {
                System.Web.Services.Description.ServiceDescription wsdl = _exporter.GeneratedWsdlDocuments[0];
                XmlSchemaSet schemaSet = _exporter.GeneratedXmlSchemas;
                XmlSchemas   imports   = new XmlSchemas();

                foreach (XmlSchema schema in _exporter.GeneratedXmlSchemas.Schemas())
                {
                    imports.Add(schema);
                }
                foreach (XmlSchema schema in imports)
                {
                    schema.Includes.Clear();
                }

                wsdl.Types.Schemas.Clear();
                wsdl.Types.Schemas.Add(imports);
                //List<XmlSchema> importsList = new List<XmlSchema>();

                //    foreach (XmlSchema schema in wsdl.Types.Schemas)
                //    {
                //        AddImportedSchemas(schema, schemaSet, importsList);
                //    }

                //    wsdl.Types.Schemas.Clear();

                //    foreach (XmlSchema schema in importsList)
                //    {
                //        RemoveXsdImports(schema);
                //        wsdl.Types.Schemas.Add(schema);
                //    }
                //}
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
        }
Exemple #8
0
        private static CodeNamespace ProcessSchema(SchemaDefinition schemaDefinition, bool includeDataContractAttributes)
        {
            var ns = new CodeNamespace(schemaDefinition.Namespace);

            var reader = XmlReader.Create(schemaDefinition.SchemaPath);
            var xsd    = XmlSchema.Read(reader, Validate);

            var schemas = new XmlSchemas();

            var schemaSet = new XmlSchemaSet();

            schemaSet.Add(xsd);
            schemaSet.Compile();

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

            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder;
            var exporter = new XmlCodeExporter(ns);
            var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            foreach (var mapping in
                     xsd.Items.OfType <XmlSchemaType>().Select(item => importer.ImportSchemaType(item.QualifiedName)))
            {
                exporter.ExportTypeMapping(mapping);
            }

            var includes = Helper.GetSchemaIncludes(schemaSet);

            FilterIncludedTypes(ns, xsd);
            AddIncludeImports(ns, includes);
            RemoveXmlRootAttributeForNoneRootTypes(ns, schemaSet);
            if (includeDataContractAttributes)
            {
                AddDataContractAttributes(ns, schemaDefinition.XmlNamespace);
            }

            return(ns);
        }
        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);
        }
Exemple #10
0
        public static XmlSchema GetDataSetSchema(XmlTypeMapping mapping, string dataSetName, string dataTableName)
        {
            // create schema
            XmlSchema xsd = new XmlSchema();

            xsd.Id = dataSetName;

            // create dataset-element
            XmlSchemaElement xsdDataset = new XmlSchemaElement();

            xsdDataset.Name = dataSetName;
            // anonymous complextype
            XmlSchemaComplexType xsdDatasetType = new XmlSchemaComplexType();
            // anonymous sequence
            XmlSchemaSequence xsdDatasetSequence = new XmlSchemaSequence();

            // add sequence to complextype
            xsdDatasetType.Particle = xsdDatasetSequence;
            // add complextype to dataset-element
            xsdDataset.SchemaType = xsdDatasetType;

            // add mapped type
            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(xsd);
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

            exporter.ExportTypeMapping(mapping);

            // get datatable-element and move it to dataset-sequence
            XmlSchemaObject o = xsd.Items[0];

            xsd.Items.RemoveAt(0);
            xsdDatasetSequence.Items.Add(o);
            // add dataset-element to xsd
            xsd.Items.Add(xsdDataset);

            //schemas.Compile(null, false);		// we only need the string
            return(schemas[mapping.Namespace]);
        }
        internal static void ExportEndpoint(WsdlExporter wsdlExporter)
        {
            if (wsdlExporter.GeneratedWsdlDocuments.Count > 1)
            {
                throw new ApplicationException("Single file option is not supported in multiple wsdl files");
            }

            ServiceDescription rootDescription = wsdlExporter.GeneratedWsdlDocuments[0];
            XmlSchemas         imports         = new XmlSchemas();

            foreach (XmlSchema schema in wsdlExporter.GeneratedXmlSchemas.Schemas())
            {
                imports.Add(schema);
            }
            foreach (XmlSchema schema in imports)
            {
                schema.Includes.Clear();
            }

            rootDescription.Types.Schemas.Clear();
            rootDescription.Types.Schemas.Add(imports);
        }
        }         //method GenerateSchemaForDocument

        private CodeNamespace GenerateCodeForSchema(XmlSchema schema)
        {
            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(schema);
            XmlSchemaImporter imp       = new XmlSchemaImporter(schemas);
            CodeNamespace     tempSpace = new CodeNamespace();
            XmlCodeExporter   exp       = new XmlCodeExporter(tempSpace);

            // Iterate schema items (top-level elements only) and generate code for each
            foreach (XmlSchemaObject item in schema.Items)
            {
                if (item is XmlSchemaElement)
                {
                    // Import the mapping first
                    XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace));
                    // Export the code finally
                    exp.ExportTypeMapping(map);
                } //if
            }     //foreach
            return(tempSpace);
        }         //method GenerateCodeForSchema
        public static CodeNamespace Process(string xsdSchema, string modelsNamespace)
        {
            // Load the XmlSchema and its collection.
            XmlSchema xsd;

            using (var fs = new StringReader(xsdSchema))
            {
                xsd = XmlSchema.Read(fs, null);
                xsd.Compile(null);
            }
            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(xsd);
            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace   ns       = new CodeNamespace(modelsNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);

            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in xsd.Elements.Values)
            {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            // execute extensions

            //var collectionsExt = new ArraysToCollectionsExtension();
            //collectionsExt.Process(ns, xsd);

            //var filedsExt = new FieldsToPropertiesExtension();
            //filedsExt.Process(ns, xsd);

            return(ns);
        }
        static void Main(string[] args)
        {
            var xmlSchemas = new XmlSchemas();

            xmlSchemas.Add(XmlSchema.Read(File.OpenRead("name5.xsd"), validationHandler));
            xmlSchemas.Compile(validationHandler, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas);

            CodeNamespace   codeNamespace = new CodeNamespace("CSharpGenerated");
            XmlCodeExporter codeExporter  = new XmlCodeExporter(codeNamespace, null, CodeGenerationOptions.None);

            foreach (XmlSchema xsd in xmlSchemas)
            {
                foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType
                {
                    //Console.WriteLine(schemaType.GetType().Name);
                    codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
                }
                foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    //Console.WriteLine(schemaElement.GetType().Name);
                    codeExporter.ExportTypeMapping(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
                }
            }

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

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

            Console.ReadLine();
        }
        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
            }
Exemple #17
0
        public void Generate()
        {
            CheckPoint(MessageType.Begin, "Initializing");
            var descriptions = new ServiceDescriptionCollection();
            var schemas      = new XmlSchemas();
            var urls         = new StringCollection();
            var localPaths   = new StringCollection();

            GetPaths(localPaths, urls);
            descriptions.Clear();
            schemas.Clear();
            if ((localPaths != null) && (localPaths.Count > 0))
            {
                string path      = localPaths[0];
                string extension = Path.GetExtension(path);
                if ((string.Compare(extension, ".exe", true) == 0) || (string.Compare(extension, ".dll", true) == 0))
                {
                    CheckPoint(MessageType.Begin, "Loading Assembly");
                    proxyAssembly = Assembly.LoadFrom(path);
                    if (proxyAssembly != null)
                    {
                        CheckPoint(MessageType.Success, "Loaded Assembly");
                    }
                    else
                    {
                        CheckPoint(MessageType.Failure, "Failed to load Assembly");
                    }
                    return;
                }
            }
            CheckPoint(MessageType.Begin, "Generating WSDL");
            try
            {
                System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                DiscoveryClientProtocol client = CreateDiscoveryClient();
                ProcessLocalPaths(client, localPaths, schemas, descriptions);
                ProcessRemoteUrls(client, urls, schemas, descriptions);
            }
            catch (Exception exception)
            {
                CheckPoint(MessageType.Failure, exception.ToString());
                return;
            }
            try
            {
                ICodeGenerator generator;
                string         str3;
                CheckPoint(MessageType.Begin, "Generating Proxy");
                CreateCodeGenerator(out generator, out str3);
                var userSchemas = new XmlSchemas();
                userSchemas.Add(schemas);
                foreach (ServiceDescription description in descriptions)
                {
                    userSchemas.Add(description.Types.Schemas);
                }
                var includeSchemas = new Hashtable();
                foreach (XmlSchema schema in userSchemas)
                {
                    CollectIncludes(schema, includeSchemas);
                }
                Compile(userSchemas);
                GenerateCode(descriptions, schemas, "http://tempuri.org", generator, str3);
                CheckPoint(MessageType.Begin, "Compiling Proxy");
                GenerateAssembly();
                CheckPoint(MessageType.Success, "Generated Assembly");
            }
            catch (Exception exception2)
            {
                CheckPoint(MessageType.Failure, exception2.ToString());
            }
        }
Exemple #18
0
        public void Generate()
        {
            this.CheckPoint(MessageType.Begin, "Initializing");
            ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection();
            XmlSchemas       schemas    = new XmlSchemas();
            StringCollection urls       = new StringCollection();
            StringCollection localPaths = new StringCollection();

            this.GetPaths(localPaths, urls);
            descriptions.Clear();
            schemas.Clear();
            if ((localPaths != null) && (localPaths.Count > 0))
            {
                string path      = localPaths[0];
                string extension = Path.GetExtension(path);
                if ((string.Compare(extension, ".exe", true) == 0) || (string.Compare(extension, ".dll", true) == 0))
                {
                    this.CheckPoint(MessageType.Begin, "Loading Assembly");
                    this.proxyAssembly = Assembly.LoadFrom(path);
                    if (this.proxyAssembly != null)
                    {
                        this.CheckPoint(MessageType.Success, "Loaded Assembly");
                    }
                    else
                    {
                        this.CheckPoint(MessageType.Failure, "Failed to load Assembly");
                    }
                    return;
                }
            }
            this.CheckPoint(MessageType.Begin, "Generating WSDL");
            try
            {
                DiscoveryClientProtocol client = this.CreateDiscoveryClient();
                this.ProcessLocalPaths(client, localPaths, schemas, descriptions);
                this.ProcessRemoteUrls(client, urls, schemas, descriptions);
            }
            catch (Exception exception)
            {
                this.CheckPoint(MessageType.Failure, exception.ToString());
                return;
            }
            try
            {
                this.CheckPoint(MessageType.Begin, "Generating Proxy");
                this.CreateCodeGenerator();
                XmlSchemas userSchemas = new XmlSchemas();
                userSchemas.Add(schemas);
                foreach (ServiceDescription description in descriptions)
                {
                    userSchemas.Add(description.Types.Schemas);
                }
                Hashtable includeSchemas = new Hashtable();
                foreach (XmlSchema schema in userSchemas)
                {
                    CollectIncludes(schema, includeSchemas);
                }
                this.Compile(userSchemas);
                this.GenerateCode(descriptions, schemas, "http://tempuri.org");
                this.CheckPoint(MessageType.Begin, "Compiling Proxy");
                this.GenerateAssembly();
                this.CheckPoint(MessageType.Success, "Generated Assembly");
            }
            catch (Exception exception2)
            {
                this.CheckPoint(MessageType.Failure, exception2.ToString());
            }
        }
Exemple #19
0
        private ServiceDescriptionImportWarnings Import(CodeNamespace codeNamespace, System.Xml.Serialization.ImportContext importContext, Hashtable exportContext, StringCollection warnings)
        {
            Hashtable hashtable2;

            this.allSchemas = new XmlSchemas();
            foreach (XmlSchema schema in this.schemas)
            {
                this.allSchemas.Add(schema);
            }
            foreach (ServiceDescription description in this.serviceDescriptions)
            {
                foreach (XmlSchema schema2 in description.Types.Schemas)
                {
                    this.allSchemas.Add(schema2);
                }
            }
            Hashtable references = new Hashtable();

            if (!this.allSchemas.Contains("http://schemas.xmlsoap.org/wsdl/"))
            {
                this.allSchemas.AddReference(ServiceDescription.Schema);
                references[ServiceDescription.Schema] = ServiceDescription.Schema;
            }
            if (!this.allSchemas.Contains("http://schemas.xmlsoap.org/soap/encoding/"))
            {
                this.allSchemas.AddReference(ServiceDescription.SoapEncodingSchema);
                references[ServiceDescription.SoapEncodingSchema] = ServiceDescription.SoapEncodingSchema;
            }
            this.allSchemas.Compile(null, false);
            foreach (ServiceDescription description2 in this.serviceDescriptions)
            {
                foreach (Message message in description2.Messages)
                {
                    foreach (MessagePart part in message.Parts)
                    {
                        bool flag;
                        bool flag2;
                        this.FindUse(part, out flag, out flag2);
                        if ((part.Element != null) && !part.Element.IsEmpty)
                        {
                            if (flag)
                            {
                                throw new InvalidOperationException(System.Web.Services.Res.GetString("CanTSpecifyElementOnEncodedMessagePartsPart", new object[] { part.Name, message.Name }));
                            }
                            XmlSchemaElement element = (XmlSchemaElement)this.allSchemas.Find(part.Element, typeof(XmlSchemaElement));
                            if (element != null)
                            {
                                AddSchema(element.Parent as XmlSchema, flag, flag2, this.abstractSchemas, this.concreteSchemas, references);
                                if ((element.SchemaTypeName != null) && !element.SchemaTypeName.IsEmpty)
                                {
                                    XmlSchemaType type = (XmlSchemaType)this.allSchemas.Find(element.SchemaTypeName, typeof(XmlSchemaType));
                                    if (type != null)
                                    {
                                        AddSchema(type.Parent as XmlSchema, flag, flag2, this.abstractSchemas, this.concreteSchemas, references);
                                    }
                                }
                            }
                        }
                        if ((part.Type != null) && !part.Type.IsEmpty)
                        {
                            XmlSchemaType type2 = (XmlSchemaType)this.allSchemas.Find(part.Type, typeof(XmlSchemaType));
                            if (type2 != null)
                            {
                                AddSchema(type2.Parent as XmlSchema, flag, flag2, this.abstractSchemas, this.concreteSchemas, references);
                            }
                        }
                    }
                }
            }
            foreach (XmlSchemas schemas in new XmlSchemas[] { this.abstractSchemas, this.concreteSchemas })
            {
                hashtable2 = new Hashtable();
                foreach (XmlSchema schema3 in schemas)
                {
                    this.AddImport(schema3, hashtable2);
                }
                foreach (XmlSchema schema4 in hashtable2.Keys)
                {
                    if ((references[schema4] == null) && !schemas.Contains(schema4))
                    {
                        schemas.Add(schema4);
                    }
                }
            }
            hashtable2 = new Hashtable();
            foreach (XmlSchema schema5 in this.allSchemas)
            {
                if (!this.abstractSchemas.Contains(schema5) && !this.concreteSchemas.Contains(schema5))
                {
                    this.AddImport(schema5, hashtable2);
                }
            }
            foreach (XmlSchema schema6 in hashtable2.Keys)
            {
                if (references[schema6] == null)
                {
                    if (!this.abstractSchemas.Contains(schema6))
                    {
                        this.abstractSchemas.Add(schema6);
                    }
                    if (!this.concreteSchemas.Contains(schema6))
                    {
                        this.concreteSchemas.Add(schema6);
                    }
                }
            }
            if (this.abstractSchemas.Count > 0)
            {
                foreach (XmlSchema schema7 in references.Values)
                {
                    this.abstractSchemas.AddReference(schema7);
                }
                foreach (string str in SchemaCompiler.Compile(this.abstractSchemas))
                {
                    warnings.Add(str);
                }
            }
            if (this.concreteSchemas.Count > 0)
            {
                foreach (XmlSchema schema8 in references.Values)
                {
                    this.concreteSchemas.AddReference(schema8);
                }
                foreach (string str2 in SchemaCompiler.Compile(this.concreteSchemas))
                {
                    warnings.Add(str2);
                }
            }
            if (this.ProtocolName.Length > 0)
            {
                ProtocolImporter importer = this.FindImporterByName(this.ProtocolName);
                if (importer.GenerateCode(codeNamespace, importContext, exportContext))
                {
                    return(importer.Warnings);
                }
            }
            else
            {
                for (int i = 0; i < this.importers.Length; i++)
                {
                    ProtocolImporter importer2 = this.importers[i];
                    if (importer2.GenerateCode(codeNamespace, importContext, exportContext))
                    {
                        return(importer2.Warnings);
                    }
                }
            }
            return(ServiceDescriptionImportWarnings.NoCodeGenerated);
        }
        public IEnumerable <CodeTypeDeclaration> CreateCodeTypeDeclarations(XmlSchemaSet schemaSet, string[] targetNamespaces)
        {
            XmlSchemas allSchemas = new XmlSchemas();

            foreach (XmlSchema schema in schemaSet.Schemas().Cast <XmlSchema>())
            {
                allSchemas.Add(schema);
            }

            allSchemas.Compile(UblSettings.XsdValidationEvent, true);
            if (!allSchemas.IsCompiled)
            {
                Console.WriteLine("Warning: allSchemas is not compiled!!! .NET BUG?");
            }
            XmlSchemaImporter importer = new XmlSchemaImporter(allSchemas);

            importer.Extensions.Clear();                                               // Remove System.Data.SqlTypes.TypeXxxx stuff
            CodeNamespace bigBlobCodeNamespace = new CodeNamespace("UblDummyLibrary"); // temporary to hold everything

            CodeGenerationOptions opts = CodeGenerationOptions.GenerateOrder;

            if (UblSettings.OptionMemberTypeToGenerate == UblXsdSettings.FieldTypesEnum.Property)
            {
                opts |= CodeGenerationOptions.GenerateProperties;
            }
            XmlCodeExporter exporter = new XmlCodeExporter(bigBlobCodeNamespace, null, opts);

            foreach (var ns in targetNamespaces)
            {
                XmlSchema schema = allSchemas[ns];
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }
            }

            IEnumerable <CodeTypeDeclaration> allCodeDecls = bigBlobCodeNamespace.Types.Cast <CodeTypeDeclaration>().ToList();

            foreach (var codeDecl in allCodeDecls)
            {
                // clear auto generated comment "<remarks/>"
                codeDecl.Comments.Clear();
                foreach (var item in codeDecl.Members.OfType <CodeTypeMember>())
                {
                    item.Comments.Clear();
                }

                // populate userdata with things we often query from xsd files
                XmlQualifiedName qname  = codeDecl.GetQualifiedName();
                XmlSchema        schema = allSchemas[qname.Namespace];
                codeDecl.UserData[Constants.XmlSchemaLabel] = schema;
                XmlSchemaType xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname];
                codeDecl.UserData[Constants.XmlSchemaTypeLabel] = xmlSchemaType;

                if (xmlSchemaType == null)
                {
                    Console.WriteLine($"Warning: {codeDecl.Name} is missing schema information {qname}");
                }
            }

            return(allCodeDecls);
        }
        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());
        }
        /// <summary>
        /// Add documents to either service description collection or
        /// schema collection
        /// </summary>
        /// <param name="path"></param>
        /// <param name="document"></param>
        private void AddDocument(string path, object document)
        {
            ServiceDescription serviceDescription = document as ServiceDescription;

            if (serviceDescription != null)
            {
                // if the service description has not already been imported,
                // add it to the "descriptions" collection
                if (!m_descriptions.Contains(serviceDescription))
                {
                    m_descriptions.Add(serviceDescription);

                    #region write out the WSDL string to the m_wsdl
                    StringWriter stringWriter = new StringWriter();
                    using (XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter))
                    {
                        xmlWriter.Formatting = Formatting.Indented;
                        serviceDescription.Write(xmlWriter);
                    }

                    m_wsdl = stringWriter.ToString();
                    #endregion
                }
                else
                {
                    Trace.TraceWarning(
                        string.Format("Warning: Ignoring duplicate service description with TargetNamespace='{0}' from '{1}'.",
                                      serviceDescription.TargetNamespace,
                                      path));
                }
            }
            else
            {
                XmlSchema schema = document as XmlSchema;
                if (schema != null)
                {
                    // if this schema is no already in the "schemas" collection,
                    // then add it
                    if (!m_schemas.Contains(schema.TargetNamespace))
                    {
                        m_schemas.Add(schema);

                        #region write the schema text out to the m_xsds StringCollection
                        //StringWriter stringWriter = new StringWriter();
                        //using (XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter))
                        //{
                        //    xmlWriter.Formatting = Formatting.Indented;
                        //    schema.Write(xmlWriter);
                        //}
                        //this.m_xsds.Add(stringWriter.ToString());
                        #endregion
                    }
                    else
                    {
                        Trace.TraceWarning(string.Format("Warning: Ignoring duplicate schema description with TargetNamespace='{0}' from '{1}'.",
                                                         schema.TargetNamespace,
                                                         path));
                    }
                }
            }
        }
Exemple #23
0
        // SERIALIZE
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Can't do anything if the result hasn't been set as a ViewResult
            if (!(filterContext.Result is ViewResult))
            {
                return;
            }

            // Don't change anything if an error code has been set
            try
            {
                if (filterContext.HttpContext.Response.StatusCode >= 300)
                {
                    return;
                }
            }
            catch { }

            // SETUP
            UTF8Encoding    utf8        = new UTF8Encoding(false);
            HttpRequestBase request     = filterContext.RequestContext.HttpContext.Request;
            String          contentType = request.ContentType ?? string.Empty;
            ViewResult      view        = (ViewResult)(filterContext.Result);
            var             data        = view.ViewData.Model;


            // Did caller request the XSD?
            if (request.QueryString.ToString().IndexOf("XSD", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                // Generate an XSD document from the class
                string finalXSD = string.Empty;
                var    soapReflectionImporter = new SoapReflectionImporter();
                var    xmlTypeMapping         = soapReflectionImporter.ImportTypeMapping(data.GetType());
                var    xmlSchemas             = new XmlSchemas();
                var    xmlSchema = new XmlSchema();
                xmlSchemas.Add(xmlSchema);
                var xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);
                xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);
                MemoryStream ms = new MemoryStream();
                xmlSchema.Write(ms);
                ms.Position = 0;
                ms.Capacity = Convert.ToInt32(ms.Length);
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);
                finalXSD = xmldoc.InnerXml;
                ms.Close();
                ms.Dispose();

                filterContext.Result = new ContentResult
                {
                    ContentType     = "text/xml",
                    Content         = finalXSD,
                    ContentEncoding = System.Text.Encoding.UTF8
                };
            }
            // Did caller request XML result?
            else if (request.QueryString.ToString().IndexOf("XML", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                string objectAsXml = SerializeObjectAsXML(data, null);
                filterContext.Result = new ContentResult
                {
                    ContentType     = "text/xml",
                    Content         = objectAsXml,
                    ContentEncoding = System.Text.Encoding.UTF8
                };
            }
            // Did caller request JSON result?
            else if (request.QueryString.ToString().IndexOf("JSON", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                using (var stream = new MemoryStream())
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();

                    String content = js.Serialize(data);
                    filterContext.Result = new ContentResult
                    {
                        ContentType     = "application/json",
                        Content         = content,
                        ContentEncoding = System.Text.Encoding.UTF8
                    };
                }
            }
            // Did caller request HTML result?
            else if (request.QueryString.ToString().IndexOf("HTML", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                filterContext.Result = filterContext.Result; // Nothing to modify here
            }
            // Not specified, so we will default response to XML
            else
            {
                string objectAsXml = SerializeObjectAsXML(data, null);
                filterContext.Result = new ContentResult
                {
                    ContentType     = "text/xml",
                    Content         = objectAsXml,
                    ContentEncoding = System.Text.Encoding.UTF8
                };
            }
        }
Exemple #24
0
        public void Start(string sDirIn, string sDirCppXmlOut, string sDirCppBinOut, string sDirJsBinOut, ValidationEventHandler oValidationEventHandler)
        {
            string sChartNamespace = "http://purl.oclc.org/ooxml/drawingml/chart";

            string[]     aFiles    = Directory.GetFiles(sDirIn);
            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.ValidationEventHandler += oValidationEventHandler;
            for (int i = 0; i < aFiles.Length; i++)
            {
                string sFile = aFiles[i];
                if (".xsd" == Path.GetExtension(sFile))
                {
                    schemaSet.Add(null, sFile);
                }
            }
            schemaSet.Compile();
            XmlSchema  chartSchema = null;
            XmlSchemas schemas     = new XmlSchemas();

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                if (schema.TargetNamespace == sChartNamespace)
                {
                    chartSchema = schema;
                    schemas.Add(schema);
                }
            }
            if (null != chartSchema)
            {
                CodeNamespace   ns       = new CodeNamespace();
                XmlCodeExporter exporter = new XmlCodeExporter(ns);

                CodeGenerationOptions generationOptions = CodeGenerationOptions.None;


                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 <GenClass> aGenClasses = PreProcess(ns, chartSchema);

                aGenClasses = FilterClasses(aGenClasses);

                (new CodegenCPP()).Process(sDirCppXmlOut, sDirCppBinOut, aGenClasses);
                (new CodegenJS()).Process(sDirJsBinOut, aGenClasses);
            }
        }
Exemple #25
0
        private CodeCompileUnit CreateCodeNamespace(XmlSchemaSet schemaSet, CodeNamespaceProvider namespaceProvider)
        {
            var compileUnit = new CodeCompileUnit();
            var schemas     = new XmlSchemas();

            foreach (var s in schemaSet.Schemas())
            {
                schemas.Add((XmlSchema)s);
            }

            schemas.Compile(_options.ValidationHandler, true);

            foreach (XmlSchema schema in schemas)
            {
                var codeNamespace = namespaceProvider.CreateCodeNamespace(schema);
                compileUnit.Namespaces.Add(codeNamespace);
            }

            var codeOptions = CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateNewAsync;

            // foreach (var ns in rootNamespaces.Concat(extensionNamespaces))
            foreach (XmlSchema schema in schemas)
            {
                var schemaImporter = new XmlSchemaImporter(schemas);
                schemaImporter.Extensions.Clear();

                // var schema = schemas[ns];
                var codeNamespace = compileUnit.Namespaces.OfType <CodeNamespace>().Single(x => x.UserData[CodeTypeMemberExtensions.XmlSchemaKey] == schema);

                Console.WriteLine($"Import root namespace: {schema.TargetNamespace}");

                var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, codeOptions);

                foreach (XmlSchemaElement element in schema.Elements.Values.OfType <XmlSchemaElement>())
                {
                    Console.WriteLine($"Import type mapping for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}");
                    var xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                    codeExporter.ExportTypeMapping(xmlTypeMapping);
                }

                var baseTypes = schema.Elements.Values.OfType <XmlSchemaElement>().Select(x => x.SchemaTypeName.Name).ToList();

                foreach (XmlSchemaComplexType element in schema.SchemaTypes.Values.OfType <XmlSchemaComplexType>().Where(x => !baseTypes.Contains(x.Name)))
                {
                    Console.WriteLine($"Import schema type for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}");

                    var xmlTypeMapping = schemaImporter.ImportSchemaType(element.QualifiedName);
                    codeExporter.ExportTypeMapping(xmlTypeMapping);
                }
            }

            var codeDeclarations = compileUnit.Namespaces.OfType <CodeNamespace>().SelectMany(x => x.Types.Cast <CodeTypeDeclaration>()).ToList();

            foreach (var codeDecl in codeDeclarations)
            {
                codeDecl.Comments.Clear();
                foreach (var item in codeDecl.Members.OfType <CodeTypeMember>())
                {
                    item.Comments.Clear();
                }

                var qname = codeDecl.GetQualifiedName();
                codeDecl.UserData[CodeTypeMemberExtensions.QualifiedNameKey] = qname;
                // Note, this can fail when there are multiple schemas for one namespace, like urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2
                var schema = schemas.GetSchemas(qname.Namespace).OfType <XmlSchema>().FirstOrDefault();
                // var schema = schemas[qname.Namespace];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaKey] = schema;
                var xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;

                foreach (CodeTypeMember member in codeDecl.Members)
                {
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaKey]     = schema;
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;
                }
            }

            return(compileUnit);
        }
Exemple #26
0
        public model.WebSvcMethodContainer GenerateSampleData()
        {
            Dictionary <string, model.WebSvcMethod> results = new Dictionary <string, model.WebSvcMethod>();

            List <string> methodList = GetMethodList();

            foreach (string method in methodList)
            {
                ServiceDescriptionCollection descCol = new ServiceDescriptionCollection();
                foreach (ServiceDescription sd in _descriptions)
                {
                    descCol.Add(sd);
                }

                XmlSchemas schemaCol;
                if (_schemas.Count > 0)
                {
                    schemaCol = new XmlSchemas();
                    foreach (XmlSchema sc in _schemas)
                    {
                        schemaCol.Add(sc);
                    }
                }
                else
                {
                    schemaCol = descCol[0].Types.Schemas;
                }

                string req;
                string resp;

                SampleGeneratorWebSvc sg = new SampleGeneratorWebSvc(descCol, schemaCol);
                sg.GenerateMessages(method, null, "Soap", out req, out resp);

                int    indexOfReqMsg = req.IndexOf(@"<soap:Envelope");
                string reqHeaderMsg  = req.Substring(0, indexOfReqMsg);
                string sampleReqMsg  = req.Substring(indexOfReqMsg);

                int    indexOfRespMsg = resp.IndexOf(@"<soap:Envelope");
                string respHeaderMsg  = resp.Substring(0, indexOfRespMsg);
                string sampleRespMsg  = resp.Substring(indexOfRespMsg);

                string[] reqHeaderLines = reqHeaderMsg.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                string   soapAction     = GetHeader(reqHeaderLines, "SOAPAction:");
                string   reqContentType = GetHeader(reqHeaderLines, "Content-Type:");

                string[] respHeaderLines = respHeaderMsg.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                string   respContentType = GetHeader(respHeaderLines, "Content-Type:");

                model.WebSvcMessageRequest messageRequest = new model.WebSvcMessageRequest();
                messageRequest.Body = sampleReqMsg;
                messageRequest.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE]       = reqContentType;
                messageRequest.Headers[model.WebSvcMessageRequest.HEADER_NAME_SOAP_ACTION] = soapAction;

                model.WebSvcMessageResponse messageResponse = new model.WebSvcMessageResponse();
                messageResponse.Body = sampleRespMsg;
                messageResponse.Headers[model.WebSvcMessage.HEADER_NAME_CONTENT_TYPE] = respContentType;

                model.WebSvcMethod webMethod = new model.WebSvcMethod(method, _serviceURI)
                {
                    Request  = messageRequest,
                    Response = messageResponse
                };


                results[method] = webMethod;
            }

            return(new model.WebSvcMethodContainer(results));
        }
Exemple #27
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());
        }
Exemple #28
0
        public void Generate(bool updateAssembly)
        {
            if (useLocalAssembly && !updateAssembly)
            {
                if (File.Exists(GetDllOutPutPath()))
                {
                    proxyAssembly = Assembly.LoadFrom(GetDllOutPutPath().ToString());
                    CheckPoint(MessageType.Success, "Local Assembly Path:" + GetDllOutPutPath().ToString());
                    return;
                }
            }

            CheckPoint(MessageType.Begin, "Initializing");
            ServiceDescriptionCollection collection1 = new ServiceDescriptionCollection();
            XmlSchemas       schemas1    = new XmlSchemas();
            StringCollection collection2 = new StringCollection();
            StringCollection collection3 = new StringCollection();

            GetPaths(collection3, collection2);
            collection1.Clear();
            schemas1.Clear();
            if ((collection3 != null) && (collection3.Count > 0))
            {
                string text1 = collection3[0];
                string text2 = Path.GetExtension(text1);
                if ((string.Compare(text2, ".exe", true) == 0) || (string.Compare(text2, ".dll", true) == 0))
                {
                    CheckPoint(MessageType.Begin, "Loading Assembly");
                    proxyAssembly = Assembly.LoadFrom(text1);

                    if (proxyAssembly != null)
                    {
                        CheckPoint(MessageType.Success, "Loaded Assembly");
                    }
                    else
                    {
                        CheckPoint(MessageType.Failure, "Failed to load Assembly");
                    }
                    return;
                }
            }
            CheckPoint(MessageType.Begin, "Generating WSDL");
            try
            {
                DiscoveryClientProtocol protocol1 = CreateDiscoveryClient();
                ProcessLocalPaths(protocol1, collection3, schemas1, collection1);
                ProcessRemoteUrls(protocol1, collection2, schemas1, collection1);
            }
            catch (Exception exception1)
            {
                CheckPoint(MessageType.Failure, exception1.ToString());
                return;
            }
            try
            {
                ICodeGenerator generator1;
                string         text3;
                CheckPoint(MessageType.Begin, "Generating Proxy");
                CreateCodeGenerator(out generator1, out text3);
                XmlSchemas schemas2 = new XmlSchemas();
                schemas2.Add(schemas1);
                foreach (ServiceDescription description1 in collection1)
                {
                    schemas2.Add(description1.Types.Schemas);
                }
                Hashtable hashtable1 = new Hashtable();
                foreach (XmlSchema schema1 in schemas2)
                {
                    CollectIncludes(schema1, hashtable1);
                }
                Compile(schemas2);
                GenerateCode(collection1, schemas1, "http://tempuri.org", generator1, text3);
                CheckPoint(MessageType.Begin, "Compiling Proxy");
                //if (proxyCode.Length < 1000)
                //{
                //    CheckPoint(MessageType.Failure, "Empty Assembly");
                //    return;
                //}

                if (updateAssembly)
                {
                    GenerateAssembly(true);
                }
                else
                {
                    GenerateAssembly();
                }
                CheckPoint(MessageType.Success, "Generated Assembly");
            }
            catch (Exception exception2)
            {
                CheckPoint(MessageType.Failure, exception2.ToString());
                return;
            }
        }
Exemple #29
0
        void ClasifySchemas(ArrayList importInfo)
        {
            // I don't like this, but I could not find any other way of clasifying
            // schemas between encoded and literal.

            xmlSchemas  = new XmlSchemas();
            soapSchemas = new XmlSchemas();

            foreach (ImportInfo info in importInfo)
            {
                foreach (Service service in info.ServiceDescription.Services)
                {
                    foreach (Port port in service.Ports)
                    {
                        this.iinfo = info;
                        this.port  = port;
                        binding    = ServiceDescriptions.GetBinding(port.Binding);
                        if (binding == null)
                        {
                            continue;
                        }
                        portType = ServiceDescriptions.GetPortType(binding.Type);
                        if (portType == null)
                        {
                            continue;
                        }

                        foreach (OperationBinding oper in binding.Operations)
                        {
                            operationBinding = oper;
                            operation        = FindPortOperation();
                            if (operation == null)
                            {
                                continue;
                            }

                            foreach (OperationMessage omsg in operation.Messages)
                            {
                                Message msg = ServiceDescriptions.GetMessage(omsg.Message);
                                if (msg == null)
                                {
                                    continue;
                                }

                                if (omsg is OperationInput)
                                {
                                    inputMessage = msg;
                                }
                                else
                                {
                                    outputMessage = msg;
                                }
                            }

                            if (GetMessageEncoding(oper.Input) == SoapBindingUse.Encoded)
                            {
                                AddMessageSchema(soapSchemas, oper.Input, inputMessage);
                            }
                            else
                            {
                                AddMessageSchema(xmlSchemas, oper.Input, inputMessage);
                            }

                            if (oper.Output != null)
                            {
                                if (GetMessageEncoding(oper.Output) == SoapBindingUse.Encoded)
                                {
                                    AddMessageSchema(soapSchemas, oper.Output, outputMessage);
                                }
                                else
                                {
                                    AddMessageSchema(xmlSchemas, oper.Output, outputMessage);
                                }
                            }
                        }
                    }
                }
            }

            XmlSchemas defaultList = xmlSchemas;

            if (xmlSchemas.Count == 0 && soapSchemas.Count > 0)
            {
                defaultList = soapSchemas;
            }

            // Schemas not referenced by any message
            foreach (XmlSchema sc in Schemas)
            {
                if (!soapSchemas.Contains(sc) && !xmlSchemas.Contains(sc))
                {
                    if (ImportsEncodedNamespace(sc))
                    {
                        soapSchemas.Add(sc);
                    }
                    else
                    {
                        defaultList.Add(sc);
                    }
                }
            }
        }
Exemple #30
0
        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);
        }