private void Initialize(Type type, string rootName, string rootNamespace, XmlSerializer xmlSerializer) { if (type == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("type"); } _rootType = type; _rootName = rootName; _rootNamespace = rootNamespace == null ? string.Empty : rootNamespace; _serializer = xmlSerializer; if (_serializer == null) { if (_rootName == null) _serializer = new XmlSerializer(type); else { XmlRootAttribute xmlRoot = new XmlRootAttribute(); xmlRoot.ElementName = _rootName; xmlRoot.Namespace = _rootNamespace; _serializer = new XmlSerializer(type, xmlRoot); } } else _isSerializerSetExplicit = true; //try to get rootName and rootNamespace from type since root name not set explicitly if (_rootName == null) { XmlTypeMapping mapping = new XmlReflectionImporter(null).ImportTypeMapping(_rootType); _rootName = mapping.ElementName; _rootNamespace = mapping.Namespace; } }
public OldContract.XmlStrippedSerializer GetSerializer(Type type) { OldContract.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 OldContract.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 OldContract.XmlStrippedSerializer(new XmlSerializer(type), xmlTypeMapping.XsdElementName, type); lock (_syncLock) { if (cache.ContainsKey(type)) { strippedSerializer = cache[type] as OldContract.XmlStrippedSerializer; } else { //Add it to the cache cache.Add(type, strippedSerializer); } } } return strippedSerializer; }
public XmlSerializer CreateSerializer(Type type, string defaultNamespace) { if (type == null) { throw new ArgumentNullException("type"); } TempAssembly assembly = cache[defaultNamespace, type]; XmlTypeMapping xmlMapping = null; if (assembly == null) { lock (cache) { assembly = cache[defaultNamespace, type]; if (assembly == null) { XmlSerializerImplementation implementation; if (TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out implementation) == null) { xmlMapping = new XmlReflectionImporter(defaultNamespace).ImportTypeMapping(type, null, defaultNamespace); assembly = XmlSerializer.GenerateTempAssembly(xmlMapping, type, defaultNamespace); } else { assembly = new TempAssembly(implementation); } cache.Add(defaultNamespace, type, assembly); } } } if (xmlMapping == null) { xmlMapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } return assembly.Contract.GetSerializer(type); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); for (int i = 0; i < extraTypes.Length; i++) importer.IncludeType(extraTypes[i]); tempAssembly = GenerateTempAssembly(importer.ImportTypeMapping(type, root)); this.events.sender = this; }
private XmlTypeMapping Map(Type t, XmlRootAttribute root) { XmlReflectionImporter ri = new XmlReflectionImporter(); XmlTypeMapping tm = ri.ImportTypeMapping(t, root); return tm; }
private XmlTypeMapping Map(Type t, XmlAttributeOverrides overrides) { XmlReflectionImporter ri = new XmlReflectionImporter(overrides); XmlTypeMapping tm = ri.ImportTypeMapping(t); //Debug.Print(tm); return tm; }
private XmlTypeMapping Map(Type t, string ns) { XmlReflectionImporter ri = new XmlReflectionImporter(ns); XmlTypeMapping tm = ri.ImportTypeMapping(t); //Debug.Print(tm); return tm; }
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 UnwrappedTypesXmlSerializerManager() { this.allTypes = new Dictionary<Type, XmlTypeMapping>(); this.serializersMap = new Dictionary<Type, XmlSerializer>(); this.operationTypes = new Dictionary<Object, IList<Type>>(); importer = new XmlReflectionImporter(); this.thisLock = new Object(); }
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 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 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(); }
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 override object[] GetInitializers (LogicalMethodInfo[] methodInfos) { XmlReflectionImporter importer = new XmlReflectionImporter (); XmlMapping[] sers = new XmlMapping [methodInfos.Length]; for (int n=0; n<sers.Length; n++) { LogicalMethodInfo metinfo = methodInfos[n]; if (metinfo.IsVoid) sers[n] = null; else { LogicalTypeInfo sti = TypeStubManager.GetLogicalTypeInfo (metinfo.DeclaringType); object[] ats = methodInfos[n].ReturnTypeCustomAttributeProvider.GetCustomAttributes (typeof(XmlRootAttribute), true); XmlRootAttribute root = ats.Length > 0 ? ats[0] as XmlRootAttribute : null; sers[n] = importer.ImportTypeMapping (methodInfos[n].ReturnType, root, sti.GetWebServiceLiteralNamespace (sti.WebServiceNamespace)); } } return XmlSerializer.FromMappings (sers); }
public void ExportXmlSerializable_NestedClassMapping () { XmlSchemas schemas = new XmlSchemas (); XmlReflectionMember xmlReflectionMember = new XmlReflectionMember (); XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter (schemas); XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter (); //Export mapping for DataSet1 class. xmlReflectionMember.MemberType = typeof (DataSet1); XmlMembersMapping xmlMembersMapping = xmlReflectionImporter.ImportMembersMapping ("DataSet1Response", "ResponseNamespace", new XmlReflectionMember [] { xmlReflectionMember }, true); xmlSchemaExporter.ExportMembersMapping (xmlMembersMapping); //Export mapping for nested of DataSet1 class. xmlReflectionMember.MemberType = typeof (DataSet1.DataTable1DataTable); xmlMembersMapping = xmlReflectionImporter.ImportMembersMapping ("DataTable1DataTableResponse", "ResponseNamespace", new XmlReflectionMember [] { xmlReflectionMember }, true); xmlSchemaExporter.ExportMembersMapping (xmlMembersMapping); }
/// <summary> /// Imports the XML types. /// </summary> /// <param name="type">The type.</param> /// <param name="mappings">The mappings.</param> /// <param name="importedTypes">The imported types.</param> /// <param name="importer">The importer.</param> private static void ImportXmlTypes(Type type, List<XmlMapping> mappings, List<Type> importedTypes, XmlReflectionImporter importer) { XmlTypeMapping mapping = null; var importer2 = new XmlReflectionImporter(); try { mapping = importer2.ImportTypeMapping(type); } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } return; } if (mapping != null) { mapping = importer.ImportTypeMapping(type); mappings.Add(mapping); importedTypes.Add(type); } }
private void Initialize(Type type, string rootName, string rootNamespace, XmlSerializer xmlSerializer) { if (type == null) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("type"); } this.rootType = type; this.rootName = rootName; this.rootNamespace = (rootNamespace == null) ? string.Empty : rootNamespace; this.serializer = xmlSerializer; if (this.serializer == null) { if (this.rootName == null) { this.serializer = new XmlSerializer(type); } else { XmlRootAttribute root = new XmlRootAttribute { ElementName = this.rootName, Namespace = this.rootNamespace }; this.serializer = new XmlSerializer(type, root); } } else { this.isSerializerSetExplicit = true; } if (this.rootName == null) { XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(this.rootType); this.rootName = mapping.ElementName; this.rootNamespace = mapping.Namespace; } }
[Test] // bug #76049 public void TestIncludeType () { XmlReflectionImporter imp = new XmlReflectionImporter (); XmlTypeMapping map = imp.ImportTypeMapping (typeof (object)); imp.IncludeType (typeof (TestSpace)); XmlSerializer ser = new XmlSerializer (map); ser.Serialize (new StringWriter (), new TestSpace ()); }
/// <summary> /// Generates XmlSerializers assembly for this assembly, allowing faster startup with xml serialization. /// </summary> public static void SGenThisAssembly() { var xmlRootTypes = new List<Type>(); var assembly = typeof(Utilities).Assembly; var mappings = new List<XmlMapping>(); var allXmlTypeToSerialize = new List<Type>(); var importer = new XmlReflectionImporter(); foreach (var type in assembly.GetTypes()) { if (type.GetCustomAttributes(typeof(XmlRootAttribute), true).Length > 0) { xmlRootTypes.Add(type); ImportXmlTypes(type, mappings, allXmlTypeToSerialize, importer); } } if (allXmlTypeToSerialize.Count == 0) return; string assemblySerializer = XmlSerializer.GetXmlSerializerAssemblyName(allXmlTypeToSerialize[0], null) + ".dll"; var assemblySerializerTime = File.GetLastWriteTime(assemblySerializer); if (!File.Exists(assemblySerializer) || File.GetLastWriteTime(typeof(Utilities).Assembly.Location) > assemblySerializerTime) { // Delete previous assembly File.Delete(assemblySerializer); // Regenerate assembly var parameters = new CompilerParameters(); string codePath = Path.GetDirectoryName(assembly.Location); var files = new TempFileCollection(codePath, false); parameters.TempFiles = files; parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.GenerateInMemory = false; XmlSerializer.GenerateSerializer(allXmlTypeToSerialize.ToArray(), mappings.ToArray(), parameters); files.Delete(); } else { Assembly.LoadFrom(assemblySerializer); } }
XmlTypeMapping ReflectType (TypeData typeData, string ns) { if (!encodedFormat) { if (auxXmlRefImporter == null) auxXmlRefImporter = new XmlReflectionImporter (); return auxXmlRefImporter.ImportTypeMapping (typeData, ns); } else { if (auxSoapRefImporter == null) auxSoapRefImporter = new SoapReflectionImporter (); return auxSoapRefImporter.ImportTypeMapping (typeData, ns); } }
protected override void BeginNamespace () { xmlImporter = new XmlSchemaImporter (LiteralSchemas, ClassNames); soapImporter = new SoapSchemaImporter (EncodedSchemas, ClassNames); xmlExporter = new XmlCodeExporter (CodeNamespace, null); xmlReflectionImporter = new XmlReflectionImporter (); }
private void ReflectInternal(ProtocolReflector[] reflectors) { this.description = new System.Web.Services.Description.ServiceDescription(); this.description.TargetNamespace = this.serviceAttr.Namespace; this.ServiceDescriptions.Add(this.description); this.service = new System.Web.Services.Description.Service(); string name = this.serviceAttr.Name; if ((name == null) || (name.Length == 0)) { name = this.serviceType.Name; } this.service.Name = XmlConvert.EncodeLocalName(name); if ((this.serviceAttr.Description != null) && (this.serviceAttr.Description.Length > 0)) { this.service.Documentation = this.serviceAttr.Description; } this.description.Services.Add(this.service); this.reflectionContext = new Hashtable(); this.exporter = new XmlSchemaExporter(this.description.Types.Schemas); this.importer = SoapReflector.CreateXmlImporter(this.serviceAttr.Namespace, SoapReflector.ServiceDefaultIsEncoded(this.serviceType)); WebMethodReflector.IncludeTypes(this.methods, this.importer); for (int i = 0; i < reflectors.Length; i++) { reflectors[i].Reflect(); } }
CodeNamespace ExportCode (Type type) { XmlReflectionImporter imp = new XmlReflectionImporter (); XmlTypeMapping map = imp.ImportTypeMapping (type); CodeNamespace codeNamespace = new CodeNamespace (); XmlCodeExporter exp = new XmlCodeExporter (codeNamespace); exp.ExportTypeMapping (map); return codeNamespace; }
/// <summary> /// Generate a set of schemas from the given types /// </summary> /// <param name="types">Array of types to generate schemas from</param> /// <returns>An array of schemas</returns> public IList<XmlSchema> GenerateSchemas(Type[] types) { Trace.Assert(types != null); if (types.Length == 0) return null; #region generate the schema from the type XmlReflectionImporter reflectionImporter = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); foreach (Type type in types) { // we can provide the default namespace as a parameter here XmlTypeMapping map = reflectionImporter.ImportTypeMapping(type); exporter.ExportTypeMapping(map); } #endregion // compile the schemas to make sure they were generated correctly schemas.Compile(null, true); ResolveImportedSchemas(schemas, types[0].Name); // convert the generated schemas to an array of schemas return XmlSchemasToArray(schemas); }
/// <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); }
public SoapTypeStubInfo (LogicalTypeInfo logicalTypeInfo) : base (logicalTypeInfo) { xmlImporter = new XmlReflectionImporter (); soapImporter = new SoapReflectionImporter (); if (typeof (SoapHttpClientProtocol).IsAssignableFrom (Type)) { if (Bindings.Count == 0 || ((BindingInfo)Bindings[0]).WebServiceBindingAttribute == null) throw new InvalidOperationException ("WebServiceBindingAttribute is required on proxy class '" + Type + "'."); if (Bindings.Count > 1) throw new InvalidOperationException ("Only one WebServiceBinding attribute may be specified on type '" + Type + "'."); } object [] o = Type.GetCustomAttributes (typeof (SoapDocumentServiceAttribute), false); if (o.Length == 1){ SoapDocumentServiceAttribute a = (SoapDocumentServiceAttribute) o [0]; ParameterStyle = a.ParameterStyle; SoapBindingStyle = SoapBindingStyle.Document; } else { o = Type.GetCustomAttributes (typeof (SoapRpcServiceAttribute), false); if (o.Length == 1){ ParameterStyle = SoapParameterStyle.Wrapped; SoapBindingStyle = SoapBindingStyle.Rpc; } else { ParameterStyle = SoapParameterStyle.Wrapped; SoapBindingStyle = SoapBindingStyle.Document; } } if (ParameterStyle == SoapParameterStyle.Default) ParameterStyle = SoapParameterStyle.Wrapped; xmlImporter.IncludeTypes (Type); soapImporter.IncludeTypes (Type); #if MOBILE || XAMMAC_4_5 SoapExtensions = new SoapExtensionRuntimeConfig [2][]; #else SoapExtensions = SoapExtension.GetTypeExtensions (Type); #endif }
// // Constructor // public SoapMethodStubInfo (TypeStubInfo typeStub, LogicalMethodInfo source, object kind, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter) : base (typeStub, source) { SoapTypeStubInfo parent = (SoapTypeStubInfo) typeStub; XmlElementAttribute optional_ns = null; if (kind == null) { Use = parent.LogicalType.BindingUse; RequestName = ""; RequestNamespace = ""; ResponseName = ""; ResponseNamespace = ""; ParameterStyle = parent.ParameterStyle; SoapBindingStyle = parent.SoapBindingStyle; OneWay = false; // disabled (see bug #332150) //#if NET_2_0 // if (parent.Type != source.DeclaringType) // Binding = source.DeclaringType.Name + parent.ProtocolName; //#endif } else if (kind is SoapDocumentMethodAttribute){ SoapDocumentMethodAttribute dma = (SoapDocumentMethodAttribute) kind; Use = dma.Use; if (Use == SoapBindingUse.Default) { if (parent.SoapBindingStyle == SoapBindingStyle.Document) Use = parent.LogicalType.BindingUse; else Use = SoapBindingUse.Literal; } Action = dma.Action; Binding = dma.Binding; RequestName = dma.RequestElementName; RequestNamespace = dma.RequestNamespace; ResponseName = dma.ResponseElementName; ResponseNamespace = dma.ResponseNamespace; ParameterStyle = dma.ParameterStyle; if (ParameterStyle == SoapParameterStyle.Default) ParameterStyle = parent.ParameterStyle; OneWay = dma.OneWay; SoapBindingStyle = SoapBindingStyle.Document; } else { SoapRpcMethodAttribute rma = (SoapRpcMethodAttribute) kind; Use = SoapBindingUse.Encoded; // RPC always use encoded Action = rma.Action; if (Action != null && Action.Length == 0) Action = null; Binding = rma.Binding; // When using RPC, MS.NET seems to ignore RequestElementName and // MessageName, and it always uses the method name RequestName = source.Name; ResponseName = source.Name + "Response"; // RequestName = rma.RequestElementName; // ResponseName = rma.ResponseElementName; RequestNamespace = rma.RequestNamespace; ResponseNamespace = rma.ResponseNamespace; ParameterStyle = SoapParameterStyle.Wrapped; OneWay = rma.OneWay; SoapBindingStyle = SoapBindingStyle.Rpc; // For RPC calls, make all arguments be part of the empty namespace optional_ns = new XmlElementAttribute (); optional_ns.Namespace = ""; } if (OneWay){ if (source.ReturnType != typeof (void)) throw new Exception ("OneWay methods should not have a return value."); if (source.OutParameters.Length != 0) throw new Exception ("OneWay methods should not have out/ref parameters."); } BindingInfo binfo = parent.GetBinding (Binding); if (binfo == null) throw new InvalidOperationException ("Type '" + parent.Type + "' is missing WebServiceBinding attribute that defines a binding named '" + Binding + "'."); string serviceNamespace = binfo.Namespace; if (RequestNamespace == "") RequestNamespace = parent.LogicalType.GetWebServiceNamespace (serviceNamespace, Use); if (ResponseNamespace == "") ResponseNamespace = parent.LogicalType.GetWebServiceNamespace (serviceNamespace, Use); if (RequestName == "") RequestName = Name; if (ResponseName == "") ResponseName = Name + "Response"; if (Action == null) Action = serviceNamespace.EndsWith("/") ? (serviceNamespace + Name) : (serviceNamespace + "/" + Name); bool hasWrappingElem = (ParameterStyle == SoapParameterStyle.Wrapped); bool writeAccessors = (SoapBindingStyle == SoapBindingStyle.Rpc); XmlReflectionMember [] in_members = BuildRequestReflectionMembers (optional_ns); XmlReflectionMember [] out_members = BuildResponseReflectionMembers (optional_ns); if (Use == SoapBindingUse.Literal) { xmlImporter.IncludeTypes (source.CustomAttributeProvider); InputMembersMapping = xmlImporter.ImportMembersMapping (RequestName, RequestNamespace, in_members, hasWrappingElem); OutputMembersMapping = xmlImporter.ImportMembersMapping (ResponseName, ResponseNamespace, out_members, hasWrappingElem); } else { soapImporter.IncludeTypes (source.CustomAttributeProvider); InputMembersMapping = soapImporter.ImportMembersMapping (RequestName, RequestNamespace, in_members, hasWrappingElem, writeAccessors); OutputMembersMapping = soapImporter.ImportMembersMapping (ResponseName, ResponseNamespace, out_members, hasWrappingElem, writeAccessors); } InputMembersMapping.SetKey(RequestName); OutputMembersMapping.SetKey(ResponseName); requestSerializerId = parent.RegisterSerializer (InputMembersMapping); responseSerializerId = parent.RegisterSerializer (OutputMembersMapping); object[] o = source.GetCustomAttributes (typeof (SoapHeaderAttribute)); ArrayList allHeaderList = new ArrayList (o.Length); ArrayList inHeaderList = new ArrayList (o.Length); ArrayList outHeaderList = new ArrayList (o.Length); ArrayList faultHeaderList = new ArrayList (); SoapHeaderDirection unknownHeaderDirections = (SoapHeaderDirection)0; for (int i = 0; i < o.Length; i++) { SoapHeaderAttribute att = (SoapHeaderAttribute) o[i]; MemberInfo[] mems = source.DeclaringType.GetMember (att.MemberName); if (mems.Length == 0) throw new InvalidOperationException ("Member " + att.MemberName + " not found in class " + source.DeclaringType.FullName + "."); HeaderInfo header = new HeaderInfo (mems[0], att); allHeaderList.Add (header); if (!header.Custom) { if ((header.Direction & SoapHeaderDirection.In) != 0) inHeaderList.Add (header); if ((header.Direction & SoapHeaderDirection.Out) != 0) outHeaderList.Add (header); if ((header.Direction & SoapHeaderDirection.Fault) != 0) faultHeaderList.Add (header); } else unknownHeaderDirections |= header.Direction; } Headers = (HeaderInfo[]) allHeaderList.ToArray (typeof(HeaderInfo)); if (inHeaderList.Count > 0 || (unknownHeaderDirections & SoapHeaderDirection.In) != 0) { InHeaders = (HeaderInfo[]) inHeaderList.ToArray (typeof(HeaderInfo)); XmlReflectionMember[] members = BuildHeadersReflectionMembers (InHeaders); if (Use == SoapBindingUse.Literal) InputHeaderMembersMapping = xmlImporter.ImportMembersMapping ("", RequestNamespace, members, false); else InputHeaderMembersMapping = soapImporter.ImportMembersMapping ("", RequestNamespace, members, false, false); InputHeaderMembersMapping.SetKey(RequestName + ":InHeaders"); requestHeadersSerializerId = parent.RegisterSerializer (InputHeaderMembersMapping); } if (outHeaderList.Count > 0 || (unknownHeaderDirections & SoapHeaderDirection.Out) != 0) { OutHeaders = (HeaderInfo[]) outHeaderList.ToArray (typeof(HeaderInfo)); XmlReflectionMember[] members = BuildHeadersReflectionMembers (OutHeaders); if (Use == SoapBindingUse.Literal) OutputHeaderMembersMapping = xmlImporter.ImportMembersMapping ("", RequestNamespace, members, false); else OutputHeaderMembersMapping = soapImporter.ImportMembersMapping ("", RequestNamespace, members, false, false); OutputHeaderMembersMapping.SetKey(ResponseName + ":OutHeaders"); responseHeadersSerializerId = parent.RegisterSerializer (OutputHeaderMembersMapping); } if (faultHeaderList.Count > 0 || (unknownHeaderDirections & SoapHeaderDirection.Fault) != 0) { FaultHeaders = (HeaderInfo[]) faultHeaderList.ToArray (typeof(HeaderInfo)); XmlReflectionMember[] members = BuildHeadersReflectionMembers (FaultHeaders); if (Use == SoapBindingUse.Literal) FaultHeaderMembersMapping = xmlImporter.ImportMembersMapping ("", RequestNamespace, members, false); else FaultHeaderMembersMapping = soapImporter.ImportMembersMapping ("", RequestNamespace, members, false, false); faultHeadersSerializerId = parent.RegisterSerializer (FaultHeaderMembersMapping); } SoapExtensions = SoapExtension.GetMethodExtensions (source); }
public static void Generate (string configFileName, string outputPath) { SerializationCodeGeneratorConfiguration cnf = null; StreamReader sr = new StreamReader (configFileName); try { XmlReflectionImporter ri = new XmlReflectionImporter (); ri.AllowPrivateTypes = true; XmlSerializer ser = new XmlSerializer (ri.ImportTypeMapping (typeof (SerializationCodeGeneratorConfiguration))); cnf = (SerializationCodeGeneratorConfiguration) ser.Deserialize (sr); } finally { sr.Close (); } if (outputPath == null) outputPath = ""; CodeIdentifiers ids = new CodeIdentifiers (); if (cnf.Serializers != null) { foreach (SerializerInfo info in cnf.Serializers) { Type type; if (info.Assembly != null) { Assembly asm; try { asm = Assembly.Load (info.Assembly); } catch { asm = Assembly.LoadFrom (info.Assembly); } type = asm.GetType (info.ClassName, true); } else type = Type.GetType (info.ClassName); if (type == null) throw new InvalidOperationException ("Type " + info.ClassName + " not found"); string file = info.OutFileName; if (file == null || file.Length == 0) { int i = info.ClassName.LastIndexOf ("."); if (i != -1) file = info.ClassName.Substring (i+1); else file = info.ClassName; file = ids.AddUnique (file, type) + "Serializer.cs"; } StreamWriter writer = new StreamWriter (Path.Combine (outputPath, file)); try { XmlTypeMapping map; if (info.SerializationFormat == SerializationFormat.Literal) { XmlReflectionImporter ri = new XmlReflectionImporter (); map = ri.ImportTypeMapping (type); } else { SoapReflectionImporter ri = new SoapReflectionImporter (); map = ri.ImportTypeMapping (type); } SerializationCodeGenerator gen = new SerializationCodeGenerator (map, info); gen.GenerateSerializers (writer); } finally { writer.Close (); } } } }
public void GenerateSerializerGenerics () { XmlReflectionImporter imp = new XmlReflectionImporter (); Type type = typeof (List<int>); XmlSerializer.GenerateSerializer ( new Type [] {type}, new XmlTypeMapping [] {imp.ImportTypeMapping (type)}); }
public void TestSchemaForm () { TestSchemaForm1 t1 = new TestSchemaForm1 (); t1.p1 = new PrintTypeResponse (); t1.p1.Init (); t1.p2 = new PrintTypeResponse (); t1.p2.Init (); TestSchemaForm2 t2 = new TestSchemaForm2 (); t2.p1 = new PrintTypeResponse (); t2.p1.Init (); t2.p2 = new PrintTypeResponse (); t2.p2.Init (); Serialize (t1); string res = ""; res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"; res += " <p1>"; res += " <result>"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p1>"; res += " <p2 xmlns=\"urn:oo\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p2>"; res += "</TestSchemaForm1>"; Assert.AreEqual (Infoset (res), WriterText); Serialize (t2); res = ""; res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"; res += " <p1 xmlns=\"urn:testForm\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p1>"; res += " <p2 xmlns=\"urn:oo\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p2>"; res += "</TestSchemaForm2>"; Assert.AreEqual (Infoset (res), WriterText); XmlReflectionImporter imp = new XmlReflectionImporter (); XmlTypeMapping map = imp.ImportTypeMapping (typeof (TestSchemaForm1), "urn:extra"); Serialize (t1, map); res = ""; res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; res += "<TestSchemaForm1 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">"; res += " <p1>"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p1>"; res += " <p2 xmlns=\"urn:oo\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p2>"; res += "</TestSchemaForm1>"; Assert.AreEqual (Infoset (res), WriterText); imp = new XmlReflectionImporter (); map = imp.ImportTypeMapping (typeof (TestSchemaForm2), "urn:extra"); Serialize (t2, map); res = ""; res += "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; res += "<TestSchemaForm2 xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:extra\">"; res += " <p1 xmlns=\"urn:testForm\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p1>"; res += " <p2 xmlns=\"urn:oo\">"; res += " <result xmlns=\"\">"; res += " <data>data1</data>"; res += " </result>"; res += " <intern xmlns=\"urn:responseTypes\">"; res += " <result xmlns=\"\">"; res += " <data>data2</data>"; res += " </result>"; res += " </intern>"; res += " </p2>"; res += "</TestSchemaForm2>"; Assert.AreEqual (Infoset (res), WriterText); }