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 XmlStrippedSerializer GetSerializer(Type type) { XmlStrippedSerializer strippedSerializer; //Hashtable is thread safe for use by multiple reader threads and a single writing thread, //so the ContainsKey call is safe here if (cache.ContainsKey(type)) { strippedSerializer = cache[type] as XmlStrippedSerializer; } else { //create the serializer before locking so that other threads are not blocked here //Needed the element name of the root element, since we strip it out of our value stored in the database. XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(); XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type); //Create the new serializer strippedSerializer = new XmlStrippedSerializer(new XmlSerializer(type), xmlTypeMapping.XsdElementName, type); lock (_syncLock) { if (cache.ContainsKey(type)) { strippedSerializer = cache[type] as XmlStrippedSerializer; } else { //Add it to the cache cache.Add(type, strippedSerializer); } } } return(strippedSerializer); }
private static void ImportType(Type type, string defaultNamespace, List <XmlMapping> mappings, List <Type> importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors) { XmlTypeMapping xmlTypeMapping; var localImporter = new XmlReflectionImporter(defaultNamespace); try { xmlTypeMapping = localImporter.ImportTypeMapping(type, defaultNamespace); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (verbose) { Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoIgnoreType, type.FullName))); WriteWarning(e, parsableerrors); } return; } if (xmlTypeMapping != null) { xmlTypeMapping = importer.ImportTypeMapping(type, defaultNamespace); mappings.Add(xmlTypeMapping); importedTypes.Add(type); } }
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); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !uapaot _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { XmlSerializerImplementation contract = null; Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } else { // we found the pre-generated assembly, now make sure that the assembly has the right serializer // try to avoid the reflection step, need to get ElementName, namespace and the Key form the type _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); _tempAssembly = new TempAssembly(new XmlMapping[] { _mapping }, assembly, contract); } } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } #endif }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) { if (type == null) { throw new ArgumentNullException(nameof(type)); } DefaultNamespace = defaultNamespace; rootType = type; XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) { importer.IncludeType(extraTypes[i]); } } _mapping = importer.ImportTypeMapping(type, root, defaultNamespace); if (location != null) { DemandForUserLocationOrEvidence(); } #if !uapaot _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); #endif }
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); } }
static void Main () { XmlReflectionImporter importer = new XmlReflectionImporter (); XmlTypeMapping map = importer.ImportTypeMapping (typeof (ArrayType)); XmlSerializer xs = new XmlSerializer (map); xs.Serialize (Console.Out, new ArrayType ()); }
private static void PrecompileXmlSerializers(params Type[] types) { var xms = new XmlTypeMapping[types.Length]; var ind = 0; var importer = new XmlReflectionImporter(); foreach (var t in types) { xms[ind++] = importer.ImportTypeMapping(t); Console.WriteLine("> type {0}", t); } var outDir = Path.GetDirectoryName(Application.ExecutablePath); var cp = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = false, OutputAssembly = Path.Combine(outDir, Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".xmls.dll") }; cp.ReferencedAssemblies.Add(Application.ExecutablePath); if (File.Exists(cp.OutputAssembly)) { Console.WriteLine("Deleting file {0}", cp.OutputAssembly); File.Delete(cp.OutputAssembly); } Console.WriteLine("Generating assembly {0}...", cp.OutputAssembly); XmlSerializer.GenerateSerializer(types, xms, cp); }
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) { } }
static void Main () { XmlReflectionImporter importer = new XmlReflectionImporter (); XmlTypeMapping map = importer.ImportTypeMapping (typeof (MyList)); XmlSerializer xs = new XmlSerializer (map); xs.Serialize (Console.Out, new MyList (null)); }
/// <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 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); }
/// <summary> /// This method is used to serialize the sub response to a specified sub response instance. /// </summary> /// <param name="subResponseDocument">Specify the sub response XML document.</param> /// <param name="site">An object provides logging, assertions, and SUT adapters for test code onto its execution context.</param> /// <returns>Return the object represents the specified kind of sub response.</returns> private object SerializeSubResponse(XmlDocument subResponseDocument, ITestSite site) { Assembly assembly = Assembly.LoadFrom("Common.dll"); if (assembly == null) { site.Assert.Fail("Cannot load the common object assembly."); } Type subResponseType = assembly.GetType("Microsoft.Protocols.TestSuites.Common." + this.SubResponseTypeName); if (subResponseType == null) { site.Assert.Fail(string.Format("Cannot load the type {0} from the assembly CommonProject.dll", this.SubResponseTypeName)); } XmlAttributes xmlAttrs = new XmlAttributes(); xmlAttrs.XmlType = new XmlTypeAttribute(this.SubResponseElementName); XmlAttributeOverrides xmlOverrides = new XmlAttributeOverrides(); xmlOverrides.Add(subResponseType, xmlAttrs); XmlReflectionImporter importer = new XmlReflectionImporter(xmlOverrides, "http://schemas.microsoft.com/sharepoint/soap/"); XmlSerializer serializer = new XmlSerializer(importer.ImportTypeMapping(subResponseType)); using (MemoryStream ms = new MemoryStream()) { byte[] subResponseBytes = System.Text.Encoding.UTF8.GetBytes(subResponseDocument.OuterXml); ms.Write(subResponseBytes, 0, subResponseBytes.Length); ms.Position = 0; return(serializer.Deserialize(ms)); } }
/// <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); } }
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(); }
static string GetHeaderElementName(Type headerType) { XmlReflectionImporter importer = SoapReflector.CreateXmlImporter(null, false); XmlTypeMapping mapping = importer.ImportTypeMapping(headerType); return(mapping.ElementName); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException(nameof(type)); } DefaultNamespace = defaultNamespace; rootType = type; _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !uapaot _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } else if (ReflectionMethodEnabled) { var importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } } #endif }
// 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); } }
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]); } } }
static int Main () { XmlReflectionImporter importer = new XmlReflectionImporter (); try { importer.ImportTypeMapping (typeof (SimpleClass)); return 1; } catch (InvalidOperationException) { return 0; } }
public static XmlSerializer GetSerializer(Type type) { return(TypeSerializers.GetOrAdd(type, t => { var importer = new XmlReflectionImporter(); var mapping = importer.ImportTypeMapping(t, null, null); return new XmlSerializer(mapping); })); }
XmlTypeMapping GetLiteralTypeMapping() { XmlRootAttribute root = new XmlRootAttribute("rootroot"); Type[] types = new Type[] { typeof(UknTestPart), typeof(AnotherTestPart), typeof(DblStringContainer) }; XmlReflectionImporter ri = new XmlReflectionImporter(); foreach (Type t in types) { ri.IncludeType(t); } return(ri.ImportTypeMapping(typeof(Test), root)); }
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()); }
public static void Xml_FromMappings() { var types = new[] { typeof(Guid), typeof(List<string>) }; XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } var serializers = XmlSerializer.FromMappings(mappings, typeof(object)); Xml_GuidAsRoot(serializers[0]); Xml_ListGenericRoot(serializers[1]); }
private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) { importer.IncludeType(extraTypes[i]); } } return(importer.ImportTypeMapping(type, root, defaultNamespace)); }
public override object GetInitializer(LogicalMethodInfo methodInfo) { LogicalTypeInfo sti = TypeStubManager.GetLogicalTypeInfo(methodInfo.DeclaringType); object[] ats = methodInfo.ReturnTypeCustomAttributeProvider.GetCustomAttributes(typeof(XmlRootAttribute), true); XmlRootAttribute root = ats.Length > 0 ? ats[0] as XmlRootAttribute : null; XmlReflectionImporter importer = new XmlReflectionImporter(); importer.IncludeTypes(methodInfo.CustomAttributeProvider); XmlTypeMapping map = importer.ImportTypeMapping(methodInfo.ReturnType, root, sti.GetWebServiceLiteralNamespace(sti.WebServiceNamespace)); return(new XmlSerializer(map)); }
public static XmlSerializer CreateDefaultXmlSerializer(Type type) { XmlSerializer serializer; if (XmlSerializerCache.TryGetValue(type, out serializer)) { return(serializer); } var importer = new XmlReflectionImporter(); var mapping = importer.ImportTypeMapping(type, null, null); serializer = new XmlSerializer(mapping); return(XmlSerializerCache[type] = serializer); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) { return(new XmlSerializer[0]); } XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return(FromMappings(mappings)); }
private XmlStrippedSerializer GetSerializerInternal(Type type, string typeName) { XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(); XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type); //Create the new serializer XmlStrippedSerializer strippedSerializer = new XmlStrippedSerializer(new XmlSerializer(type), xmlTypeMapping.XsdElementName, xmlTypeMapping.Namespace, type); lock (cache) { cache[typeName] = strippedSerializer; } return(strippedSerializer); }
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(); }
public static void Xml_FromMappings() { var types = new[] { typeof(Guid), typeof(List <string>) }; XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } var serializers = XmlSerializer.FromMappings(mappings, typeof(object)); Xml_GuidAsRoot(serializers[0]); Xml_ListGenericRoot(serializers[1]); }
/// <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]); }
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)); }
public int Run (string[] args) { ParseArgs (args); if (!nologo) { Console.WriteLine ("Mono Xml Serializer Generator Tool"); Console.WriteLine ("Mono version " + Environment.Version); Console.WriteLine (); } if (unknownArg != null) { Console.WriteLine ("Unknown option: " + unknownArg); Console.WriteLine (); return 1; } if (help) { Console.WriteLine ("Usage: sgen [options]"); Console.WriteLine (); return 0; } if (assembly == null) { Console.WriteLine ("Assembly name not provided"); Console.WriteLine (); return 1; } Assembly asm = null; try { asm = Assembly.Load (assembly); } catch {} if (asm == null) { try { asm = Assembly.LoadFrom (assembly); } catch { Console.WriteLine ("Specified assembly cannot be loaded."); Console.WriteLine (); return 1; } } ArrayList userTypes = new ArrayList (); ArrayList maps = new ArrayList (); XmlReflectionImporter imp = new XmlReflectionImporter (); if (verbose) Console.WriteLine ("Generating serializer for the following types:"); if (types == null) { foreach (Type t in asm.GetTypes ()) { try { maps.Add (imp.ImportTypeMapping (t)); userTypes.Add (t); if (verbose) Console.WriteLine( " - " + t ); } catch (InvalidOperationException ex) { if (verbose) Console.WriteLine (" - Warning: " + ex.Message); } catch (NotImplementedException ex) { if (verbose) { Console.WriteLine (" - Warning: ignoring '" + t + "'"); Console.WriteLine (" " + ex.Message); } } catch (NotSupportedException ex) { if (verbose) Console.WriteLine (" - Warning: " + ex.Message); } } } else { foreach (string type in types) { try { Type t = asm.GetType (type); maps.Add (imp.ImportTypeMapping (t)); userTypes.Add (t); if (verbose) Console.WriteLine (" - " + t); } catch (InvalidOperationException ex) { if (verbose) Console.WriteLine (" - Warning: " + ex.Message); } catch (NotImplementedException ex) { if (verbose) { Console.WriteLine (" - Warning: ignoring '" + type + "'"); Console.WriteLine (" " + ex.Message); } } catch (NotSupportedException ex) { if (verbose) Console.WriteLine (" - Warning: " + ex.Message); } } } if (verbose) Console.WriteLine (); CompilerParameters parameters = new CompilerParameters (); parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = debug; parameters.ReferencedAssemblies.AddRange ((string[])references.ToArray(typeof(string))); parameters.TempFiles = new TempFileCollection (Environment.CurrentDirectory, keep); parameters.CompilerOptions = compilerOptions; string file = Path.GetFileNameWithoutExtension (asm.Location) + ".XmlSerializers.dll"; if (outDir == null) outDir = Path.GetDirectoryName (asm.Location); parameters.OutputAssembly = Path.Combine (outDir, file); if (File.Exists (parameters.OutputAssembly) && !force) { Console.WriteLine ("Cannot generate assembly '" + parameters.OutputAssembly + "' because it already exist. Use /force option to overwrite the existing assembly"); Console.WriteLine (); return 1; } XmlSerializer.GenerateSerializer ( (Type[]) userTypes.ToArray (typeof(Type)), (XmlTypeMapping[]) maps.ToArray (typeof(XmlTypeMapping)), parameters); if (!silent) { Console.WriteLine ("Generated assembly: " + file); Console.WriteLine (); } return 0; }
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; }