public static XmlTextReader Get_XSD_Clase(Type Tipo_Searializar, String strNamespace)
        {
            XmlReflectionImporter importer = new XmlReflectionImporter();
            XmlSchemas            schemas  = new XmlSchemas();
            XmlSchemaExporter     exporter = new XmlSchemaExporter(schemas);

            XmlTypeMapping mapping = importer.ImportTypeMapping(Tipo_Searializar, strNamespace);

            exporter.ExportTypeMapping(mapping);
            XmlSchema schema;

            if (!String.IsNullOrEmpty(strNamespace))
            {
                schema = schemas[strNamespace];
            }
            else
            {
                schema = schemas[0];
            }
            StringWriter sWriter = new StringWriter();

            schema.Write(sWriter);
            XmlTextReader txtReader = new XmlTextReader(new StringReader(sWriter.ToString()));

            return(txtReader);
        }
Beispiel #2
0
        public XmlSchema GetSchema(int schemaId)
        {
            this.ThrowIfNotReady();
            try
            {
                XmlSchemas schemaCollection = new XmlSchemas();

                XmlReflectionImporter importer = new XmlReflectionImporter("http://openiz.org/model");
                XmlSchemaExporter     exporter = new XmlSchemaExporter(schemaCollection);

                foreach (var cls in typeof(IImsiServiceContract).GetCustomAttributes <ServiceKnownTypeAttribute>().Select(o => o.Type))
                {
                    exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://openiz.org/model"));
                }

                if (schemaId > schemaCollection.Count)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
                    return(null);
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode  = System.Net.HttpStatusCode.OK;
                    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
                    return(schemaCollection[schemaId]);
                }
            }
            catch (Exception e)
            {
//                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                var remoteEndpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, String.Format("{0} - {1}", remoteEndpoint?.Address, e.ToString()));
                return(null);
            }
        }
        public static XmlSchemaSet Infer(Type type)
        {
            XmlSchemaSet          schemaSet      = new XmlSchemaSet();
            XmlReflectionImporter importer       = new XmlReflectionImporter();
            XmlSchemas            schemas        = new XmlSchemas();
            XmlSchemaExporter     exporter       = new XmlSchemaExporter(schemas);
            XmlTypeMapping        xmlTypeMapping = importer.ImportTypeMapping(type);

            exporter.ExportTypeMapping(xmlTypeMapping);
            schemas.Compile(new ValidationEventHandler(delegate(object sender, ValidationEventArgs args)
            {
                throw args.Exception;
            }), false);

            for (int i = 0; i < schemas.Count; i++)
            {
                XmlSchema schema = schemas[i];
                schema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");

                try
                {
                    schemaSet.Add(schema);
                }
                catch (Exception exception2)
                {
                    if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException))
                    {
                        throw;
                    }
                    throw;
                }
            }
            return(schemaSet);
        }
Beispiel #4
0
        public void SaveSchema(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ApplicationConfiguration));

            using (TextWriter writer = new StreamWriter(filePath))
            {
                serializer.Serialize(writer, this);
            }


            XmlSchemas        schemas  = new XmlSchemas();
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

            //Import the type as an XML mapping
            XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(ApplicationConfiguration));

            //Export the XML mapping into schemas
            exporter.ExportTypeMapping(mapping);

            using (TextWriter writer = new StreamWriter(filePath))
            {
                foreach (object schema in schemas)
                {
                    ((XmlSchema)schema).Write(writer);
                    writer.WriteLine();
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Gets the schema for the administrative interface.
        /// </summary>
        /// <param name="schemaId">The id of the schema to be retrieved.</param>
        /// <returns>Returns the administrative interface schema.</returns>
        public XmlSchema GetSchema(int schemaId)
        {
            try
            {
                XmlSchemas schemaCollection = new XmlSchemas();

                XmlReflectionImporter importer = new XmlReflectionImporter("http://openiz.org/ami");
                XmlSchemaExporter     exporter = new XmlSchemaExporter(schemaCollection);

                foreach (var cls in typeof(IAmiContract).GetCustomAttributes <ServiceKnownTypeAttribute>().Select(o => o.Type))
                {
                    exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://openiz.org/ami"));
                }

                if (schemaId > schemaCollection.Count)
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                    return(null);
                }
                else
                {
                    WebOperationContext.Current.OutgoingResponse.StatusCode  = System.Net.HttpStatusCode.OK;
                    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
                    return(schemaCollection[schemaId]);
                }
            }
            catch (Exception e)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                this.traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                return(null);
            }
        }
Beispiel #6
0
        internal static IEnumerable <XmlSchema> InferXmlSchema(Type type)
        {
            var reflectedType = Reflector.GetReflectedType(type);
            var isDataEntity  = reflectedType.IsDataEntity;

            if (isDataEntity || reflectedType.IsList)
            {
                var innerTypes = new HashSet <Type>();
                var isArray    = !isDataEntity;

                var elementName = reflectedType.XmlElementName;
                var schemaXml   = new StringBuilder();
                schemaXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><xs:schema elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">");
                schemaXml.AppendFormat("<xs:element name=\"{0}\" nillable=\"true\" type=\"{1}\" />", (isArray ? "ArrayOf" : "") + elementName, Reflector.ClrToXmlType(type));
                WriteTypeSchema(type, schemaXml, innerTypes);
                schemaXml.Append("</xs:schema>");

                var schema = XmlSchema.Read(new StringReader(schemaXml.ToString()), null);
                return(schema.Return());
            }
            else
            {
                var importer = new XmlReflectionImporter();
                var schemas  = new XmlSchemas();
                var exporter = new XmlSchemaExporter(schemas);

                var xmlTypeMapping = importer.ImportTypeMapping(type);
                exporter.ExportTypeMapping(xmlTypeMapping);

                schemas.Compile(null, false);
                return(schemas);
            }
        }
Beispiel #7
0
        public static void SaveSchema()
        {
            String path = System.AppDomain.CurrentDomain.BaseDirectory;

            String schemaFilename = Path.Combine(path, SchemaFilename);

            try
            {
                Type type = typeof(Config);

                XmlAttributeOverrides xao = new XmlAttributeOverrides();
                AttachXmlAttributes(xao, type);

                XmlReflectionImporter importer = new XmlReflectionImporter(xao);
                XmlSchemas            schemas  = new XmlSchemas();
                XmlSchemaExporter     exporter = new XmlSchemaExporter(schemas);

                XmlTypeMapping map = importer.ImportTypeMapping(type);
                exporter.ExportTypeMapping(map);


                TextWriter tw = new StreamWriter(schemaFilename);
                schemas[0].Write(tw);
                tw.Close();
            }
            catch (Exception ex)
            {
            }
        }
        /// <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));
        }
Beispiel #9
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];
        }	
Beispiel #10
0
 private static XmlSchema GetXmlSchema<T>()
 {
     var schemas = new XmlSchemas();
     var xmlImporter = new XmlReflectionImporter();
     var xmlExporter = new XmlSchemaExporter(schemas);
     xmlExporter.ExportTypeMapping(xmlImporter.ImportTypeMapping(typeof(T)));
     return schemas.Single();
 }
        // If the user schema is generated by WCF, it may contain references to some primitive WCF
        // types in the following namespaces. We need add those schemas to the schema set by default
        // so these types can be resolved correctly.
        //
        // * http://schemas.microsoft.com/2003/10/Serialization
        // * http://schemas.microsoft.com/2003/10/Serialization/Arrays
        // * http://microsoft.com/wsdl/types/
        // * http://schemas.datacontract.org/2004/07/System
        private void AddSchemasForPrimitiveTypes(XmlSchemaSet schemas)
        {
            // Add DCS special types
            XsdDataContractExporter dataContractExporter = new XsdDataContractExporter(schemas);

            // We want to export Guid, Char, and TimeSpan, however even a single call causes all
            // schemas to be exported.
            dataContractExporter.Export(typeof(Guid));

            // Export DateTimeOffset, DBNull, array types
            dataContractExporter.Export(typeof(DateTimeOffset));
            dataContractExporter.Export(typeof(DBNull));
            dataContractExporter.Export(typeof(bool[]));
            dataContractExporter.Export(typeof(DateTime[]));
            dataContractExporter.Export(typeof(decimal[]));
            dataContractExporter.Export(typeof(double[]));
            dataContractExporter.Export(typeof(float[]));
            dataContractExporter.Export(typeof(int[]));
            dataContractExporter.Export(typeof(long[]));
            dataContractExporter.Export(typeof(XmlQualifiedName[]));
            dataContractExporter.Export(typeof(short[]));
            dataContractExporter.Export(typeof(string[]));
            dataContractExporter.Export(typeof(uint[]));
            dataContractExporter.Export(typeof(ulong[]));
            dataContractExporter.Export(typeof(ushort[]));
            dataContractExporter.Export(typeof(Char[]));
            dataContractExporter.Export(typeof(TimeSpan[]));
            dataContractExporter.Export(typeof(Guid[]));
            // Arrays of DateTimeOffset and DBNull are not supported

            // Add XS special types

            // XmlSchemaExporter takes XmlSchemas so we need that temporarily
            XmlSchemas            xmlSchemas  = new XmlSchemas();
            XmlReflectionImporter importer    = new XmlReflectionImporter();
            XmlSchemaExporter     xmlExporter = new XmlSchemaExporter(xmlSchemas);

            xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Guid)));
            xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Char)));

            foreach (XmlSchema schema in xmlSchemas)
            {
                schemas.Add(schema);
            }
        }
Beispiel #12
0
        public void GenerateSchemas()
        {
            Assembly assembly = null;

            try
            {
                assembly = Assembly.LoadFrom((string)assemblies [0]);
            }
            catch (Exception ex)
            {
                Error(errLoadAssembly, ex.Message);
            }

            Type[] types;

            if (lookupTypes.Count > 0)
            {
                types = new Type [lookupTypes.Count];
                for (int n = 0; n < lookupTypes.Count; n++)
                {
                    Type t = assembly.GetType((string)lookupTypes[n]);
                    if (t == null)
                    {
                        Error(typeNotFound, (string)lookupTypes[n]);
                    }
                    types[n] = t;
                }
            }
            else
            {
                types = assembly.GetExportedTypes();
            }

            XmlReflectionImporter ri      = new XmlReflectionImporter();
            XmlSchemas            schemas = new XmlSchemas();
            XmlSchemaExporter     sx      = new XmlSchemaExporter(schemas);

            foreach (Type type in types)
            {
                XmlTypeMapping tm = ri.ImportTypeMapping(type);
                sx.ExportTypeMapping(tm);
            }

            if (schemas.Count == 1)
            {
                string fileName = Path.Combine(outputDir, "schema.xsd");
                WriteSchema(fileName, schemas [0]);
            }
            else
            {
                for (int n = 0; n < schemas.Count; n++)
                {
                    string fileName = Path.Combine(outputDir, "schema" + n + ".xsd");
                    WriteSchema(fileName, schemas [n]);
                }
            }
        }
        public static String Get_XSD_String_Clase(Type Tipo_Searializar)
        {
            XmlReflectionImporter importer = new XmlReflectionImporter();
            XmlSchemas            schemas  = new XmlSchemas();
            XmlSchemaExporter     exporter = new XmlSchemaExporter(schemas);
            XmlTypeMapping        mapping  = importer.ImportTypeMapping(Tipo_Searializar);

            exporter.ExportTypeMapping(mapping);
            System.Xml.Schema.XmlSchema schema  = schemas[0];
            System.IO.StringWriter      sWriter = new System.IO.StringWriter();
            schema.Write(sWriter);
            return(sWriter.ToString());
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            Sensor se = new Sensor()
            {
                Data      = 5,
                otherData = 10,
                MoreData  = 15
            };
            XmlSchemas        schemas  = new XmlSchemas();
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
            XmlTypeMapping    mapping  = new XmlReflectionImporter().ImportTypeMapping(typeof(Sensor));

            exporter.ExportTypeMapping(mapping);
            StringWriter schemaWriter = new StringWriter();

            foreach (XmlSchema schema in schemas)
            {
                schema.Write(schemaWriter);
            }
            XDocument  doc  = XDocument.Parse(schemaWriter.ToString());
            XElement   root = doc.Root;
            XNamespace xs   = root.GetNamespaceOfPrefix("xs");

            foreach (XElement _class in doc.Descendants(xs + "complexType"))
            {
                List <XElement> elements = _class.Descendants(xs + "element").ToList();
                if (elements.Count > 0)
                {
                    XElement complexType = new XElement(xs + "complexType");
                    _class.Add(complexType);
                    XElement sequence = new XElement(xs + "sequence");
                    complexType.Add(sequence);
                    foreach (var prop in se.GetType().GetProperties())
                    {
                        string   name       = prop.Name;
                        string   value      = prop.GetValue(se, null).ToString();
                        XElement element    = elements.Where(x => (string)x.Attribute("name") == name).FirstOrDefault();
                        string   strType    = (string)element.Attribute("type");
                        XElement newElement = new XElement(xs + "simpleType", new object[] {
                            new XElement(xs + "restriction", new object[] {
                                new XAttribute("base", strType),
                                new XElement(xs + "enumeration", new XAttribute("value", value))
                            })
                        });
                        sequence.Add(newElement);
                    }
                }
            }
            doc.Save(FILENAME);
        }
Beispiel #15
0
        public Program()
        {
            XmlReflectionImporter _XmlReflectionImporter = new XmlReflectionImporter();
            XmlSchemas            _XmlSchemas            = new XmlSchemas();
            XmlSchemaExporter     _XmlSchemaExporter     = new XmlSchemaExporter(_XmlSchemas);

            XmlTypeMapping map = _XmlReflectionImporter.ImportTypeMapping(typeof(Database));

            _XmlSchemaExporter.ExportTypeMapping(map);

            TextWriter _TextWriter = new StreamWriter("asd.xsd");

            _XmlSchemas[0].Write(_TextWriter);
            _TextWriter.Close();
        }
Beispiel #16
0
        static void SerializarSchema(Type tipo, string nomeArquivo)
        {
            var schemas  = new XmlSchemas();
            var exporter = new XmlSchemaExporter(schemas);
            var mapping  = new XmlReflectionImporter().ImportTypeMapping(tipo);

            exporter.ExportTypeMapping(mapping);

            TextWriter writer = new StreamWriter(nomeArquivo);

            foreach (XmlSchema schema in schemas)
            {
                schema.Write(writer);
            }
            writer.Dispose();
        }
Beispiel #17
0
        static XmlSchema GetSchema(Type t)
        {
            XmlReflectionImporter xri     = new XmlReflectionImporter();
            XmlTypeMapping        xtm     = xri.ImportTypeMapping(t);
            XmlSchemas            schemas = new XmlSchemas();
            XmlSchemaExporter     xse     = new XmlSchemaExporter(schemas);

            xse.ExportTypeMapping(xtm);

            foreach (XmlSchema xs in schemas)
            {
                return(xs);
            }

            return(null);
        }
Beispiel #18
0
            static XmlQualifiedName StaticGetSchema(XmlSchemaSet schemaSet)
            {
                XmlReflectionImporter importer       = new XmlReflectionImporter();
                XmlTypeMapping        xmlTypeMapping = importer.ImportTypeMapping(typeof(T));
                XmlSchemas            schemas        = new XmlSchemas();
                XmlSchemaExporter     exporter       = new XmlSchemaExporter(schemas);

                exporter.ExportTypeMapping(xmlTypeMapping);
                schemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true);
                for (int i = 0; i < schemas.Count; i++)
                {
                    XmlSchema schema = schemas[i];
                    schemaSet.Add(schema);
                }
                return(new XmlQualifiedName(xmlTypeMapping.TypeName, xmlTypeMapping.Namespace));
            }
Beispiel #19
0
        /// <summary>
        /// Get schema
        /// </summary>
        public XmlSchema GetSchema(int schemaId)
        {
            this.ThrowIfNotReady();

            XmlSchemas schemaCollection = new XmlSchemas();

            XmlReflectionImporter importer = new XmlReflectionImporter("http://hl7.org/fhir");
            XmlSchemaExporter     exporter = new XmlSchemaExporter(schemaCollection);

            foreach (var cls in typeof(FhirServiceBehavior).Assembly.GetTypes().Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null && !o.IsGenericTypeDefinition))
            {
                exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://hl7.org/fhir"));
            }

            return(schemaCollection[schemaId]);
        }
Beispiel #20
0
        public static void SchemaDoc(String[] args)
        {
            var docParameters = new ParameterParser <SchemaDocParameters>().Parse(args);

            XmlSchema  outputXsd          = new XmlSchema();
            XmlSchemas outputSchemas      = new XmlSchemas();
            var        schemaExporter     = new XmlSchemaExporter(outputSchemas);
            var        reflectionImporter = new XmlReflectionImporter();

            Assembly loadedAssembly = Assembly.LoadFile(docParameters.Assembly);

            // Load the specified types
            foreach (var t in loadedAssembly.ExportedTypes.Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null))
            {
                var typeMapping = reflectionImporter.ImportTypeMapping(t);
                schemaExporter.ExportTypeMapping(typeMapping);
            }

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(docParameters.XmlDocFile ?? Path.ChangeExtension(docParameters.Assembly, "xml"));

            // Schema set objects
            foreach (XmlSchema itm in outputSchemas)
            {
                foreach (object xtype in itm.Items)
                {
                    if (xtype is XmlSchemaComplexType)
                    {
                        CreateAssemblyDoc(xtype as XmlSchemaComplexType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaComplexType).Name), xmlDoc);
                    }
                    else if (xtype is XmlSchemaSimpleType)
                    {
                        CreateAssemblyDoc(xtype as XmlSchemaSimpleType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaSimpleType).Name), xmlDoc);
                    }
                }
            }

            // Schema writer
            using (var xwriter = File.Create(docParameters.Output ?? "out.xsd"))
                foreach (XmlSchema itm in outputSchemas)
                {
                    itm.Write(xwriter);
                }
        }
Beispiel #21
0
 /// <summary>
 /// Get Schema for a given body
 /// </summary>
 /// <param name="body"></param>
 /// <param name="isXmlSerializerType"></param>
 /// <returns></returns>
 private static Message GetXmlSchemaAsMessage(Type body, bool isXmlSerializerType)
 {
     System.Collections.IEnumerable schemas;
     if (isXmlSerializerType)
     {
         XmlReflectionImporter importer    = new XmlReflectionImporter();
         XmlTypeMapping        typeMapping = importer.ImportTypeMapping(body);
         XmlSchemas            s           = new XmlSchemas();
         XmlSchemaExporter     exporter    = new XmlSchemaExporter(s);
         exporter.ExportTypeMapping(typeMapping);
         schemas = s.GetSchemas(null);
     }
     else
     {
         XsdDataContractExporter exporter = new XsdDataContractExporter();
         exporter.Export(body);
         schemas = exporter.Schemas.Schemas();
     }
     using (MemoryStream stream = new MemoryStream())
     {
         XmlWriterSettings xws = new XmlWriterSettings {
             Indent = true
         };
         using (XmlWriter writer = XmlWriter.Create(stream, xws))
         {
             if (writer != null)
             {
                 writer.WriteStartElement("Schemas");
                 foreach (XmlSchema schema in schemas)
                 {
                     if (schema.TargetNamespace != "http://www.w3.org/2001/XMLSchema")
                     {
                         schema.Write(writer);
                     }
                 }
             }
         }
         stream.Seek(0, SeekOrigin.Begin);
         using (XmlReader reader = XmlReader.Create(stream))
         {
             return(Message.CreateMessage(MessageVersion.None, null, XElement.Load(reader, LoadOptions.PreserveWhitespace)));
         }
     }
 }
Beispiel #22
0
        public static string GetSchema <T>()
        {
            var xao = new XmlAttributeOverrides();

            AttachXmlAttributes(xao, typeof(T));

            var importer = new XmlReflectionImporter(xao);
            var schemas  = new XmlSchemas();
            var exporter = new XmlSchemaExporter(schemas);
            var map      = importer.ImportTypeMapping(typeof(T));

            exporter.ExportTypeMapping(map);

            using (var ms = new MemoryStream())
            {
                schemas[0].Write(ms);
                ms.Position = 0;
                return(new StreamReader(ms).ReadToEnd());
            }
        }
        /// <summary>
        /// Saves the scheme into file.
        /// </summary>
        /// <param name="filename">The filename.</param>
        private static void SaveSchemeIntoFile(string filename, Type schemeForType)
        {
            XmlSchemas        schemas  = new XmlSchemas();
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

            //Import the type as an XML mapping
            XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(schemeForType);

            //Export the XML mapping into schemas
            exporter.ExportTypeMapping(mapping);

            //Print out the schemas
            using (FileStream fs = new FileStream(Path.Combine(@"C:\XMLFiles", filename), FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                foreach (object schema in schemas)
                {
                    ((System.Xml.Schema.XmlSchema)schema).Write(fs);
                }
            }
        }
Beispiel #24
0
        private static XmlReaderSettings CreateXmlReaderSettings <T>()
        {
            XmlSchemas        schemas  = new XmlSchemas();
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
            XmlTypeMapping    mapping  = new XmlReflectionImporter().ImportTypeMapping(typeof(T));

            exporter.ExportTypeMapping(mapping);
            XmlSchemaSet schemaSet = new XmlSchemaSet();

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

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.Schemas                 = schemaSet;
            settings.ValidationType          = ValidationType.Schema;
            settings.ValidationEventHandler += HandleXmlReaderValidation;
            return(settings);
        }
Beispiel #25
0
        public static void ExtractSchema <T>(string path, T schemaGenerateForObject)
        {
            //SoapReflectionImporter soapReflectionImporter = new SoapReflectionImporter();
            //XmlTypeMapping xmlTypeMapping = soapReflectionImporter.ImportTypeMapping(typeof(T));
            //XmlSchemas xmlSchemas = new XmlSchemas();
            //XmlSchema xmlSchema = new XmlSchema();
            //xmlSchemas.Add(xmlSchema);
            //StreamWriter writer = new StreamWriter(path);
            //xmlSchema.Write(writer);
            //XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);
            //xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);
            XmlSchemas        schemas  = new XmlSchemas();
            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
            XmlTypeMapping    mapping  = new XmlReflectionImporter().ImportTypeMapping(typeof(T));

            exporter.ExportTypeMapping(mapping);
            StreamWriter schemaWriter = new StreamWriter(path);

            foreach (XmlSchema schema in schemas)
            {
                schema.Write(schemaWriter);
            }
        }
Beispiel #26
0
        public static byte[] GetXmlSchemaFromType(Type type)
        {
            XmlSchemas            sms = new XmlSchemas();
            XmlSchemaExporter     ex  = new XmlSchemaExporter(sms);
            XmlReflectionImporter im  = new XmlReflectionImporter();
            XmlTypeMapping        map = im.ImportTypeMapping(type);

            ex.ExportTypeMapping(map);
            sms.Compile(null, false);

            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);

            foreach (System.Xml.Schema.XmlSchema sm in sms)
            {
                sm.Write(sw);
            }
            sw.Close();
            ms.Flush();

            byte[] data = ms.ToArray();
            return(data);
        }
Beispiel #27
0
    public string Create(Type t)
    {
        string xsd;

        using (var stream = new MemoryStream()) {
            using (var writer = new StreamWriter(stream, Encoding.UTF8)) {
                var schemas  = new XmlSchemas();
                var exporter = new XmlSchemaExporter(schemas);
                var mapping  = new XmlReflectionImporter().ImportTypeMapping(t);
                exporter.ExportTypeMapping(mapping);
                foreach (XmlSchema schema in schemas)
                {
                    schema.Write(writer);
                }

                writer.Flush();
                xsd = Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        xsd = ManipulateXsdForScriptContent(xsd);
        return(xsd);
    }
Beispiel #28
0
        /// <summary>
        ///     .net assemblies (dll(s) when on disk) go in and .xsd file contents comes out
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="typeNames"></param>
        /// <returns></returns>
        public static List <string> ExportSchemas(Assembly assembly, List <string> typeNames = null, string xmlDefaultNamespace = null)
        {
            if (typeNames == null)
            {
                typeNames = new List <string>();
            }

            XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(xmlDefaultNamespace);
            XmlSchemas            xmlSchemas            = new XmlSchemas();
            XmlSchemaExporter     xmlSchemaExporter     = new XmlSchemaExporter(xmlSchemas);

            try
            {
                Type[] types = assembly.GetTypes();
                for (int i = 0; i < types.Length; i++)
                {
                    Type type = types[i];
                    if (type.IsPublic && (!type.IsAbstract || !type.IsSealed) && !type.IsInterface && !type.ContainsGenericParameters)
                    {
                        bool flag;
                        if (typeNames.Count == 0)
                        {
                            flag = true;
                        }
                        else
                        {
                            flag = false;
                            foreach (string text2 in typeNames)
                            {
                                if (type.FullName == text2 || type.Name == text2 || (text2.EndsWith(".*") && type.FullName.StartsWith(text2.Substring(0, text2.Length - 2))))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (flag)
                        {
                            XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type);
                            xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);
                        }
                    }
                }

                xmlSchemas.Compile(ValidationCallbackWithErrorCode, false);
            } catch (Exception ex)
            {
                if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
                {
                    throw;
                }
                throw new InvalidOperationException("General Error", ex);
            }

            List <string> xmlSchemasList = new List <string>(xmlSchemas.Count);

            foreach (XmlSchema _XmlSchema in xmlSchemas)
            {
                try
                {
                    using (StringWriter _StringWriter = new StringWriter())
                    {
                        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
                        //// the default namespace prefix of xs makes Microsoft word upset, it was found that a
                        //namespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                        _XmlSchema.Write(_StringWriter, namespaceManager);
                        xmlSchemasList.Add(_StringWriter.ToString());
                    }
                } catch (Exception ex2)
                {
                    if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
                    {
                        throw;
                    }
                    throw new InvalidOperationException(Res.GetString("ErrGeneral", _XmlSchema.TargetNamespace), ex2);
                }
            }

            return(xmlSchemasList);
        }
        public static bool TryAddSchemaTypeFromXmlSchemaProviderAttribute(this XmlDictionaryWriter writer, Type type, string name, SoapSerializer serializer, XmlNamespaceManager xmlNamespaceManager = null)
        {
            if (!useXmlSchemaProvider && !useXmlReflectionImporter)
            {
                return(false);
            }

            if (useXmlReflectionImporter)
            {
                var schemas     = new XmlSchemas();
                var xmlImporter = new XmlReflectionImporter();
                var exporter    = new XmlSchemaExporter(schemas);

                var xmlTypeMapping = xmlImporter.ImportTypeMapping(type, new XmlRootAttribute()
                {
                    ElementName = name
                });
                exporter.ExportTypeMapping(xmlTypeMapping);
                schemas.Compile(null, true);

                var memoryStream = new MemoryStream();
                foreach (XmlSchema schema in schemas)
                {
                    schema.Write(memoryStream);
                }
                memoryStream.Position = 0;

                var streamReader = new StreamReader(memoryStream);
                var result       = streamReader.ReadToEnd();

                var doc = new XmlDocument();
                doc.LoadXml(result);
                doc.DocumentElement.WriteContentTo(writer);

                return(true);
            }

            var xmlSchemaSet = xmlNamespaceManager == null ? new XmlSchemaSet() : new XmlSchemaSet(xmlNamespaceManager.NameTable);
            var xmlSchemaProviderAttribute = type.GetCustomAttribute <XmlSchemaProviderAttribute>(true);

            if (xmlSchemaProviderAttribute != null && true)
            {
                XmlSchema schema = new XmlSchema();
                if (xmlNamespaceManager != null)
                {
                    schema.Namespaces = xmlNamespaceManager.Convert();
                }
                if (xmlSchemaProviderAttribute.IsAny)
                {
                    //MetaWCFBodyWriter usage....
                    //writer.WriteAttributeString("name", name);
                    //writer.WriteAttributeString("nillable", "true");
                    //writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD);
                    //writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD);
                    //writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD);
                    //writer.WriteAttributeString("minOccurs", "0");
                    //writer.WriteAttributeString("processContents", "lax");
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    var sequence = new XmlSchemaSequence();
                    sequence.Items.Add(new XmlSchemaAny()
                    {
                        ProcessContents = XmlSchemaContentProcessing.Lax
                    });
                    var complex = new XmlSchemaComplexType()
                    {
                        Particle = sequence
                    };
                    var element = new XmlSchemaElement()
                    {
                        MinOccurs  = 0,
                        MaxOccurs  = 1,
                        Name       = name,
                        IsNillable = serializer == SoapSerializer.DataContractSerializer ? true : false,
                        SchemaType = complex
                    };
                    schema.Items.Add(element);
                }
                else
                {
                    var methodInfo    = type.GetMethod(xmlSchemaProviderAttribute.MethodName, BindingFlags.Static | BindingFlags.Public);
                    var xmlSchemaType = (XmlSchemaType)methodInfo.Invoke(null, new object[] { xmlSchemaSet });
                    var element       = new XmlSchemaElement()
                    {
                        MinOccurs  = 0,
                        MaxOccurs  = 1,
                        Name       = name,
                        SchemaType = xmlSchemaType
                    };
                    schema.Items.Add(element);
                }

                var memoryStream = new MemoryStream();
                schema.Write(memoryStream);
                memoryStream.Position = 0;

                var streamReader = new StreamReader(memoryStream);
                var result       = streamReader.ReadToEnd();

                var doc = new XmlDocument();
                doc.LoadXml(result);
                doc.DocumentElement.WriteContentTo(writer);

                return(true);
            }

            return(false);
        }
Beispiel #30
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
                };
            }
        }
Beispiel #31
0
Datei: test.cs Projekt: mono/gert
	static int Main ()
	{
		XmlReflectionImporter ri = new XmlReflectionImporter ("NSPrimitive");
		XmlSchemas schemas = new XmlSchemas ();
		XmlSchemaExporter sx = new XmlSchemaExporter (schemas);
		XmlTypeMapping tm = ri.ImportTypeMapping (typeof (int));
		sx.ExportTypeMapping (tm);

		StringWriter sw = new StringWriter ();
		schemas[0].Write (sw);

		int exitCode = 0;

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSPrimitive\" elementFormDefault=\"qualified\" targetNamespace=\"NSPrimitive\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"int\" type=\"xs:int\" />{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#1");

		ri = new XmlReflectionImporter ("NSString");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (string));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSString\" elementFormDefault=\"qualified\" targetNamespace=\"NSString\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"string\" nillable=\"true\" type=\"xs:string\" />{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#2");

		ri = new XmlReflectionImporter ("NSQName");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (XmlQualifiedName));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSQName\" elementFormDefault=\"qualified\" targetNamespace=\"NSQName\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
#if NET_2_0
			"  <xs:element name=\"QName\" nillable=\"true\" type=\"xs:QName\" />{0}" +
#else
			"  <xs:element name=\"QName\" type=\"xs:QName\" />{0}" +
#endif
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#3");

		ri = new XmlReflectionImporter ("NSDateTime");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (DateTime));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSDateTime\" elementFormDefault=\"qualified\" targetNamespace=\"NSDateTime\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"dateTime\" type=\"xs:dateTime\" />{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#4");

		ri = new XmlReflectionImporter ("NSByteArray");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (byte[]));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSByteArray\" elementFormDefault=\"qualified\" targetNamespace=\"NSByteArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"base64Binary\" nillable=\"true\" type=\"xs:base64Binary\" />{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#5");

		ri = new XmlReflectionImporter ("NSInt32Array");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (int[]));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSInt32Array\" elementFormDefault=\"qualified\" targetNamespace=\"NSInt32Array\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"ArrayOfInt\" nillable=\"true\" type=\"tns:ArrayOfInt\" />{0}" +
			"  <xs:complexType name=\"ArrayOfInt\">{0}" +
			"    <xs:sequence>{0}" +
			"      <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"int\" type=\"xs:int\" />{0}" +
			"    </xs:sequence>{0}" +
			"  </xs:complexType>{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#6");

		ri = new XmlReflectionImporter ("NSSimpleClassArray");
		schemas = new XmlSchemas ();
		sx = new XmlSchemaExporter (schemas);
		tm = ri.ImportTypeMapping (typeof (SimpleClass[]));
		sx.ExportTypeMapping (tm);

		sw = new StringWriter ();
		schemas[0].Write (sw);

		exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
			"<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
			"<xs:schema xmlns:tns=\"NSSimpleClassArray\" elementFormDefault=\"qualified\" targetNamespace=\"NSSimpleClassArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
			"  <xs:element name=\"ArrayOfSimpleClass\" nillable=\"true\" type=\"tns:ArrayOfSimpleClass\" />{0}" +
			"  <xs:complexType name=\"ArrayOfSimpleClass\">{0}" +
			"    <xs:sequence>{0}" +
			"      <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"SimpleClass\" nillable=\"true\" type=\"tns:SimpleClass\" />{0}" +
			"    </xs:sequence>{0}" +
			"  </xs:complexType>{0}" +
			"  <xs:complexType name=\"SimpleClass\" />{0}" +
			"</xs:schema>", Environment.NewLine), sw.ToString (), "#7");

		return exitCode;
	}