private XmlSchemas Export (Type type, XmlAttributeOverrides overrides, string defaultNamespace) { XmlReflectionImporter ri = new XmlReflectionImporter (overrides, defaultNamespace); XmlSchemas schemas = new XmlSchemas (); XmlSchemaExporter sx = new XmlSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (type); sx.ExportTypeMapping (tm); return schemas; }
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(); }
/// <summary> /// Generate a set of schemas from the given type. /// /// Every serializable .NET class can be represented by a schema. /// If that class inherits from another class, then this method will generate more than one schema. /// The number of schemas is determines by .NET's own magic formula for when a new schema is needed /// but this is probably determined by the namespace attributes added (in the form of XmlRoot and /// XmlType attribute) to the class. /// /// We assume that the first schema in the array of generated schemas contains the schema /// of the type we requested. /// /// </summary> /// <param name="type">A type to generate schemas from</param> /// <returns>An array of schemas</returns> public IList<XmlSchema> GenerateSchema(Type type) { Type typeToGenerate = type.IsByRef ? type.GetElementType() : type; #region generate the schema from the type XmlReflectionImporter reflectionImporter = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping map = reflectionImporter.ImportTypeMapping(typeToGenerate); exporter.ExportTypeMapping(map); #endregion #region compile the schemas to make sure they were generated correctly XmlSchemaSet schemaSet = new XmlSchemaSet(); try { foreach (XmlSchema schema in schemas) schemaSet.Add(schema); // some generated classes contain xs:any elements // disabling this check allows us to avoid a compilation error schemaSet.CompilationSettings.EnableUpaCheck = false; schemaSet.XmlResolver = null; // we don't want to resolve any outside schemas schemaSet.ValidationEventHandler += new ValidationEventHandler(schemaSet_ValidationEventHandler); schemaSet.Compile(); } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } #endregion #region this is a special case for certain types of generated classes // when you use the System.Reflection.Emit namespace to generate a type, // and then try to generate schemas from that type, the schemas don't // contain "imports" for types in other namespaces. // This code block adds those imports. // if the number of schemas generated is greater than 1 (meaning there are // potentially types in other namespaces (and hence other schemas) // AND if the first schema generated does not include any other schemas // we know we're generating a schema that has the charateristics we're // expecting if (schemas.Count > 1 && schemas[0].Includes.Count == 0) { // create a list of schemas to process IList<XmlSchema> schemaArray = XmlSchemasToArray(schemas); // since the number of schemas is greater than one we know that there // are at least 2 schemas, so we can safely index from 1 for (int i = 1; i < schemaArray.Count; i++) { // create a new schema import, and set the namespace XmlSchemaImport import = new XmlSchemaImport(); import.Namespace = schemaArray[i].TargetNamespace; // import it into the first schema schemaArray[0].Includes.Add(import); } schemaSet.Compile(); } #endregion #region "fix" the pointers to the included schemas for the generated schemas ResolveImportedSchemas(schemas, XmlConvert.EncodeName(typeToGenerate.Name)); #endregion // convert the generated schemas to an array of schemas return XmlSchemasToArray(schemas); }
/// <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); }
public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) { _exporter.ExportTypeMapping(xmlTypeMapping); }
// 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); } }
void ExportSchemas(string outputdir, IList dlls, IList typeNames) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); foreach (string dll in dlls) { Assembly a = Assembly.LoadFrom(dll); if (a == null) throw new InvalidOperationException(Res.GetString(Res.ErrLoadAssembly, dll)); try { foreach (Type type in a.GetTypes()) { if (!type.IsPublic) continue; if (type.IsInterface) continue; bool found; if (typeNames.Count == 0) { found = true; } else { found = false; foreach (string typeName in typeNames) { if (type.FullName == typeName || type.Name == typeName || (typeName.EndsWith(".*") && type.FullName.StartsWith(typeName.Substring(0, typeName.Length - 2)))) { found = true; break; } } } if (found) { XmlTypeMapping xmlTypeMapping = importer.ImportTypeMapping(type); exporter.ExportTypeMapping(xmlTypeMapping); } } } catch (Exception e) { throw new InvalidOperationException(Res.GetString(Res.ErrGeneral, dll), e); } } for (int i = 0; i < schemas.Count; i++) { XmlSchema schema = schemas[i]; try { TextWriter writer = CreateOutputWriter(outputdir, "schema" + i.ToString(), ".xsd"); schemas[i].Write(writer); writer.Close(); } catch (Exception e) { throw new InvalidOperationException(Res.GetString(Res.ErrGeneral, schema.TargetNamespace), e); } } }
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]); } } }
Message CreateExample(Type type, OperationDescription od, bool generateJson) { bool usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior)); XmlQualifiedName name; XmlSchemaSet schemaSet = new XmlSchemaSet(); IDictionary<XmlQualifiedName, Type> knownTypes = new Dictionary<XmlQualifiedName, Type>(); if (usesXmlSerializer) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(type); name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(typeMapping); foreach (XmlSchema schema in schemas) { schemaSet.Add(schema); } } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); List<Type> listTypes = new List<Type>(od.KnownTypes); listTypes.Add(type); exporter.Export(listTypes); if (!exporter.CanExport(type)) { throw new NotSupportedException(String.Format("Example generation is not supported for type '{0}'", type)); } name = exporter.GetRootElementName(type); foreach (Type knownType in od.KnownTypes) { XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType); if (!knownTypes.ContainsKey(knownTypeName)) { knownTypes.Add(knownTypeName, knownType); } } foreach (XmlSchema schema in exporter.Schemas.Schemas()) { schemaSet.Add(schema); } } schemaSet.Compile(); XmlWriterSettings settings = new XmlWriterSettings { CloseOutput = false, Indent = true, }; if (generateJson) { var jsonExample = new XDocument(); using (XmlWriter writer = XmlWriter.Create(jsonExample.CreateWriter(), settings)) { HelpExampleGenerator.GenerateJsonSample(schemaSet, name, writer, knownTypes); } var reader = jsonExample.CreateReader(); reader.MoveToContent(); var message = Message.CreateMessage(MessageVersion.None, (string)null, reader); WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; message.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Json); return message; } else { var xmlExample = new XDocument(); using (XmlWriter writer = XmlWriter.Create(xmlExample.CreateWriter(), settings)) { HelpExampleGenerator.GenerateXmlSample(schemaSet, name, writer); } var reader = xmlExample.CreateReader(); reader.MoveToContent(); var message = Message.CreateMessage(MessageVersion.None, (string)null, reader); message.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Xml); WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; return message; } }
Message CreateSchema(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 w = XmlWriter.Create(stream, xws)) { w.WriteStartElement("Schemas"); foreach (XmlSchema schema in schemas) { if (schema.TargetNamespace != "http://www.w3.org/2001/XMLSchema") { schema.Write(w); } } } stream.Seek(0, SeekOrigin.Begin); using (XmlReader reader = XmlReader.Create(stream)) { return Message.CreateMessage(MessageVersion.None, null, XElement.Load(reader, LoadOptions.PreserveWhitespace)); } } }
private static XmlSchemas ExportType (Type type) { XmlReflectionImporter ri = new XmlReflectionImporter ("NS" + type.Name); XmlSchemas schemas = new XmlSchemas (); XmlSchemaExporter sx = new XmlSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (type); sx.ExportTypeMapping (tm); return schemas; }
internal MessageHelpInformation(OperationDescription od, bool isRequest, Type type, bool wrapped) { this.Type = type; this.SupportsJson = WebHttpBehavior.SupportsJsonFormat(od); string direction = isRequest ? SR2.GetString(SR2.HelpPageRequest) : SR2.GetString(SR2.HelpPageResponse); if (wrapped && !typeof(void).Equals(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsWrapped, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(void).Equals(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsEmpty, direction); this.FormatString = SR2.GetString(SR2.HelpPageNA); } else if (typeof(Message).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsMessage, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(Stream).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsStream, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(Atom10FeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Feed, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(Atom10ItemFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Entry, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(AtomPub10ServiceDocumentFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubServiceDocument, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(AtomPub10CategoriesDocumentFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubCategoriesDocument, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(Rss20FeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsRSS20Feed, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(SyndicationFeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsSyndication, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(XElement).IsAssignableFrom(type) || typeof(XmlElement).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsXML, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else { try { bool usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior)); XmlQualifiedName name; this.SchemaSet = new XmlSchemaSet(); IDictionary<XmlQualifiedName, Type> knownTypes = new Dictionary<XmlQualifiedName, Type>(); if (usesXmlSerializer) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(this.Type); name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(typeMapping); foreach (XmlSchema schema in schemas) { this.SchemaSet.Add(schema); } } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); List<Type> listTypes = new List<Type>(od.KnownTypes); bool isQueryable; Type dataContractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(this.Type, out isQueryable); listTypes.Add(dataContractType); exporter.Export(listTypes); if (!exporter.CanExport(dataContractType)) { this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); return; } name = exporter.GetRootElementName(dataContractType); DataContract typeDataContract = DataContract.GetDataContract(dataContractType); if (typeDataContract.KnownDataContracts != null) { foreach (XmlQualifiedName dataContractName in typeDataContract.KnownDataContracts.Keys) { knownTypes.Add(dataContractName, typeDataContract.KnownDataContracts[dataContractName].UnderlyingType); } } foreach (Type knownType in od.KnownTypes) { XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType); if (!knownTypes.ContainsKey(knownTypeName)) { knownTypes.Add(knownTypeName, knownType); } } foreach (XmlSchema schema in exporter.Schemas.Schemas()) { this.SchemaSet.Add(schema); } } this.SchemaSet.Compile(); XmlWriterSettings settings = new XmlWriterSettings { CloseOutput = false, Indent = true, }; if (this.SupportsJson) { XDocument exampleDocument = new XDocument(); using (XmlWriter writer = XmlWriter.Create(exampleDocument.CreateWriter(), settings)) { HelpExampleGenerator.GenerateJsonSample(this.SchemaSet, name, writer, knownTypes); } this.JsonExample = exampleDocument.Root; } if (name.Namespace != "http://schemas.microsoft.com/2003/10/Serialization/") { foreach (XmlSchema schema in this.SchemaSet.Schemas(name.Namespace)) { this.Schema = schema; } } XDocument XmlExampleDocument = new XDocument(); using (XmlWriter writer = XmlWriter.Create(XmlExampleDocument.CreateWriter(), settings)) { HelpExampleGenerator.GenerateXmlSample(this.SchemaSet, name, writer); } this.XmlExample = XmlExampleDocument.Root; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); this.Schema = null; this.JsonExample = null; this.XmlExample = null; } } }
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(); } } }
private string ConstructXsdFromType(Type type) { try { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping mapping = importer.ImportTypeMapping(type); XmlSchemas xmlSchemas = new XmlSchemas(); XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas); using (var writer = new StringWriter()) { xmlSchemaExporter.ExportTypeMapping(mapping); xmlSchemas[0].Write(writer); return XElement.Parse(writer.ToString()).ToString(); } } catch (Exception e) { return e.Message; } }