ImportTypeMapping() приватный Метод

private ImportTypeMapping ( TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, RecursionLimiter limiter ) : TypeMapping
model TypeModel
ns string
context ImportContext
dataType string
a XmlAttributes
limiter RecursionLimiter
Результат TypeMapping
Пример #1
0
 /// <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;
		}
        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;
        }
Пример #4
0
        /// <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 !NET_NATIVE
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location);
#endif
        }
Пример #5
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence)
        {
#if NET_NATIVE
            throw new PlatformNotSupportedException();
#else
            if (type == null)
            {
                throw new ArgumentNullException(nameof(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 || evidence != null)
            {
                DemandForUserLocationOrEvidence();
            }
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location, evidence);
#endif
        }
		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;
		}
Пример #8
0
		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);
		}
Пример #9
0
        /// <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 !NET_NATIVE
            _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
        }
Пример #10
0
        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;
            }
            _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)
                            {
                                if (Mode == SerializationMode.PreGenOnly)
                                {
                                    AssemblyName name           = type.Assembly.GetName();
                                    var          serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                                    throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
                                }

                                // 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);
            }
        }
Пример #11
0
		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;
		}
Пример #12
0
        /// <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("type");
            }

#if NET_NATIVE
            // The ctor is not supported, but we cannot throw PNSE unconditionally
            // because the ctor is used by ctor(Type) which passes in a null defaultNamespace.
            if (!string.IsNullOrEmpty(defaultNamespace))
            {
                throw new PlatformNotSupportedException();
            }

            rootType = type;
#endif
            _mapping = GetKnownMapping(type, defaultNamespace);
            if (_mapping != null)
            {
                _primitiveType = type;
                return;
            }
#if !NET_NATIVE
            _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);
            }
#endif
        }
Пример #13
0
        /// <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;
        }
Пример #14
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static XmlSerializer[] FromTypes(Type[] types)
        {
            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));
        }
		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);
		}
Пример #16
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();
        }
Пример #17
0
        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 XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);

            for (int i = 0; i < extraTypes.Length; i++)
            {
                importer.IncludeType(extraTypes[i]);
            }
            this.mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
            tempAssembly = GenerateTempAssembly(this.mapping, type, defaultNamespace, location, evidence);
        }
        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 XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);

            for (int i = 0; i < extraTypes.Length; i++)
            {
                importer.IncludeType(extraTypes[i]);
            }
            XmlTypeMapping xmlMapping = importer.ImportTypeMapping(type, root, defaultNamespace);

            return((XmlSerializer)XmlSerializer.GenerateTempAssembly(xmlMapping, type, defaultNamespace, location, evidence).Contract.TypedSerializers[xmlMapping.Key]);
        }
Пример #21
0
        /// <summary>Initializes a new instance of the <see cref="T:System.Xml.Serialization.XmlSerializer" /> class that can serialize objects of type <see cref="T:System.Object" /> into XML document instances, and deserialize XML document instances into objects of type <see cref="T:System.Object" />. Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.</summary>
        /// <param name="type">The type of the object that this <see cref="T:System.Xml.Serialization.XmlSerializer" /> can serialize. </param>
        /// <param name="overrides">An <see cref="T:System.Xml.Serialization.XmlAttributeOverrides" /> that extends or overrides the behavior of the class specified in the <paramref name="type" /> parameter. </param>
        /// <param name="extraTypes">A <see cref="T:System.Type" /> array of additional object types to serialize. </param>
        /// <param name="root">An <see cref="T:System.Xml.Serialization.XmlRootAttribute" /> that defines the XML root element properties. </param>
        /// <param name="defaultNamespace">The default namespace of all XML elements in the XML document. </param>
        public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(overrides, defaultNamespace);

            if (extraTypes != null)
            {
                foreach (Type type2 in extraTypes)
                {
                    xmlReflectionImporter.IncludeType(type2);
                }
            }
            this.typeMapping = xmlReflectionImporter.ImportTypeMapping(type, root, defaultNamespace);
        }
Пример #22
0
 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlSerializer(Type type)
 {
     this.events.sender = this;
     tempAssembly       = cache[type];
     if (tempAssembly == null)
     {
         lock (cache) {
             tempAssembly = cache[type];
             if (tempAssembly == null)
             {
                 XmlReflectionImporter importer = new XmlReflectionImporter();
                 tempAssembly = GenerateTempAssembly(importer.ImportTypeMapping(type));
                 cache.Add(type, tempAssembly);
             }
         }
     }
 }
 /// <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("type");
     }
     this.mapping = GetKnownMapping(type, defaultNamespace);
     if (this.mapping != null)
     {
         this.primitiveType = type;
         return;
     }
     tempAssembly = cache[defaultNamespace, type];
     if (tempAssembly == null)
     {
         lock (cache) {
             tempAssembly = cache[defaultNamespace, type];
             if (tempAssembly == null)
             {
                 XmlSerializerImplementation contract;
                 Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract);
                 if (assembly == null)
                 {
                     // need to reflect and generate new serialization assembly
                     XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
                     this.mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
                     tempAssembly = GenerateTempAssembly(this.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
                     this.mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
                     tempAssembly = new TempAssembly(new XmlMapping[] { this.mapping }, assembly, contract);
                 }
             }
             cache.Add(defaultNamespace, type, tempAssembly);
         }
     }
     if (mapping == null)
     {
         mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
     }
 }
		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);
		}
Пример #25
0
        /// <include file='doc\XmlSerializerFactory.uex' path='docs/doc[@for="XmlSerializerFactory.CreateSerializer1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSerializer CreateSerializer(Type type, string defaultNamespace)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            TempAssembly   tempAssembly = s_cache[defaultNamespace, type];
            XmlTypeMapping mapping      = null;

            if (tempAssembly == null)
            {
                lock (s_cache)
                {
                    tempAssembly = s_cache[defaultNamespace, type];
                    if (tempAssembly == null)
                    {
                        XmlSerializerImplementation contract;
                        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 = XmlSerializer.GenerateTempAssembly(mapping, type, defaultNamespace);
                        }
                        else
                        {
                            tempAssembly = new TempAssembly(contract);
                        }
                        s_cache.Add(defaultNamespace, type, tempAssembly);
                    }
                }
            }
            if (mapping == null)
            {
                mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
            }
            return((XmlSerializer)tempAssembly.Contract.GetSerializer(type));
        }
Пример #26
0
        public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (location != null)
            {
                DemandForUserLocationOrEvidence();
            }

            XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);

            for (int i = 0; i < extraTypes.Length; i++)
            {
                importer.IncludeType(extraTypes[i]);
            }
            XmlTypeMapping mapping      = importer.ImportTypeMapping(type, root, defaultNamespace);
            TempAssembly   tempAssembly = XmlSerializer.GenerateTempAssembly(mapping, type, defaultNamespace, location);

            return((XmlSerializer)tempAssembly.Contract.TypedSerializers[mapping.Key]);
        }
Пример #27
0
 /// <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);
     }
 }
Пример #28
0
        /// <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("type");
            }

            _mapping = GetKnownMapping(type, defaultNamespace);
            if (_mapping != null)
            {
                _primitiveType = type;
                return;
            }
            _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);
            }
        }
Пример #29
0
        private void Init(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
        {
            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 !NET_NATIVE
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
        }
Пример #30
0
        /// <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);
        }
Пример #31
0
        /// <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);
        }
Пример #32
0
		public void GenerateSerializerGenerics ()
		{
			XmlReflectionImporter imp = new XmlReflectionImporter ();
			Type type = typeof (List<int>);
			XmlSerializer.GenerateSerializer (
				new Type [] {type},
				new XmlTypeMapping [] {imp.ImportTypeMapping (type)});
		}
Пример #33
0
		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 ();
					}
				}
			}
		}
Пример #34
0
		static void RegisterExtensionType (Type type)
		{
			ExtensionInfo ext = new ExtensionInfo();
			ext.Type = type;
			
			object[] ats = type.GetCustomAttributes (typeof(XmlFormatExtensionPrefixAttribute), true);
			
			foreach (XmlFormatExtensionPrefixAttribute at in ats)
				ext.NamespaceDeclarations.Add (new XmlQualifiedName (at.Prefix, at.Namespace));
			
			ats = type.GetCustomAttributes (typeof(XmlFormatExtensionAttribute), true);
			if (ats.Length > 0)
			{
				XmlFormatExtensionAttribute at = (XmlFormatExtensionAttribute)ats[0];
				ext.ElementName = at.ElementName;
				if (at.Namespace != null) ext.Namespace = at.Namespace;
			}

			XmlRootAttribute root = new XmlRootAttribute ();
			root.ElementName = ext.ElementName;
			if (ext.Namespace != null) root.Namespace = ext.Namespace;

			XmlReflectionImporter ri = new XmlReflectionImporter ();
			XmlTypeMapping map = ri.ImportTypeMapping (type, root);
			
			if (ext.ElementName == null) throw new InvalidOperationException ("XmlFormatExtensionAttribute must be applied to type " + type);
			extensionsByName.Add (ext.Namespace + " " + ext.ElementName, ext);
			extensionsByType.Add (type, ext);
			
			maps.Add (map);
			extensions.Add (ext);
		}
Пример #35
0
		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);
		}
Пример #36
0
        internal XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location, Evidence evidence)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (location != null || evidence != null)
            {
                DemandForUserLocationOrEvidence();
            }

            XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
            for (int i = 0; i < extraTypes.Length; i++)
                importer.IncludeType(extraTypes[i]);
            XmlTypeMapping mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
            TempAssembly tempAssembly = XmlSerializer.GenerateTempAssembly(mapping, type, defaultNamespace, location, evidence);
            return (XmlSerializer)tempAssembly.Contract.TypedSerializers[mapping.Key];
        }
Пример #37
0
        // 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);
            }
        }
Пример #38
0
        internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
        {
            try
            {
                if (_primitiveType != null)
                {
                    return DeserializePrimitive(xmlReader, events);
                }
#if !NET_NATIVE
                else if (Mode == SerializationMode.ReflectionOnly)
                {
                    XmlMapping mapping;
                    if (_mapping.GenerateSerializer)
                    {
                        mapping = _mapping;
                    }
                    else
                    {
                        XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                        mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                    }

                    var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle);
                    return reader.ReadObject();
                }
                else if (_tempAssembly == null || _typedSerializer)
                {
                    XmlSerializationReader reader = CreateReader();
                    reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
                    try
                    {
                        return Deserialize(reader);
                    }
                    finally
                    {
                        reader.Dispose();
                    }
                }
                else
                {
                    return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
                }
#else
                else
                {
                    if (this.innerSerializer != null)
                    {
                        if (!string.IsNullOrEmpty(this.DefaultNamespace))
                        {
                            this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
                        }

                        XmlSerializationReader reader = this.innerSerializer.CreateReader();
                        reader.Init(xmlReader, encodingStyle);
                        try
                        {
                            return this.innerSerializer.Deserialize(reader);
                        }
                        finally
                        {
                            reader.Dispose();
                        }
                    }
                    else if (ReflectionMethodEnabled)
                    {
                        XmlMapping mapping;
                        if (_mapping != null && _mapping.GenerateSerializer)
                        {
                            mapping = _mapping;
                        }
                        else
                        {
                            XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                            mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                        }

                        var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle);
                        return reader.ReadObject();
                    }
                    else
                    {

                        throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
                    }
                }
#endif
            }
            catch (Exception e)
            {
                if (e is TargetInvocationException)
                    e = e.InnerException;

                if (xmlReader is IXmlLineInfo)
                {
                    IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
                    throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
                }
                else
                {
                    throw new InvalidOperationException(SR.XmlSerializeError, e);
                }
            }
        }
Пример #39
0
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static XmlSerializer[] FromTypes(Type[] types)
        {
            if (types == null)
                return Array.Empty<XmlSerializer>();

#if NET_NATIVE
            var serializers = new XmlSerializer[types.Length];
            for (int i = 0; i < types.Length; i++)
            {
                serializers[i] = new XmlSerializer(types[i]);
            }

            return serializers;
#else
            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);
#endif
        }
Пример #40
0
        internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            try
            {
                if (_primitiveType != null)
                {
                    SerializePrimitive(xmlWriter, o, namespaces);
                }
#if !NET_NATIVE
                else if (Mode == SerializationMode.ReflectionOnly)
                {
                    XmlMapping mapping;
                    if (_mapping.GenerateSerializer)
                    {
                        mapping = _mapping;
                    }
                    else
                    {
                        XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                        mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                    }

                    var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                    writer.WriteObject(o);
                }
                else if (_tempAssembly == null || _typedSerializer)
                {
                    // The contion for the block is never true, thus the block is never hit.
                    XmlSerializationWriter writer = CreateWriter();
                    writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
                    try
                    {
                        Serialize(o, writer);
                    }
                    finally
                    {
                        writer.Dispose();
                    }
                }
                else
                    _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
                else
                {
                    if (this.innerSerializer != null)
                    {
                        if (!string.IsNullOrEmpty(this.DefaultNamespace))
                        {
                            this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
                        }

                        XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
                        writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        try
                        {
                            this.innerSerializer.Serialize(o, writer);
                        }
                        finally
                        {
                            writer.Dispose();
                        }
                    }
                    else if (ReflectionMethodEnabled)
                    {
                        XmlMapping mapping;
                        if (_mapping != null && _mapping.GenerateSerializer)
                        {
                            mapping = _mapping;
                        }
                        else
                        {
                            XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                            mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                        }

                        var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        writer.WriteObject(o);
                    }
                    else
                    {
                        throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
                    }
                }
#endif
            }
            catch (Exception e)
            {
                if (e is TargetInvocationException)
                    e = e.InnerException;
                throw new InvalidOperationException(SR.XmlGenError, e);
            }
            xmlWriter.Flush();
        }
Пример #41
0
        private void Init(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
        {
            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 !NET_NATIVE
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
        }
Пример #42
0
        private void Init(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 !NET_NATIVE
            _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
        }
		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;
		}
Пример #44
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
        public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
        {
            try
            {
                if (_primitiveType != null)
                {
                    if (encodingStyle != null && encodingStyle.Length > 0)
                    {
                        throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
                    }
                    SerializePrimitive(xmlWriter, o, namespaces);
                }
#if !NET_NATIVE
                else if (Mode == SerializationMode.ReflectionOnly)
                {
                    XmlMapping mapping;
                    if (_mapping != null && _mapping.GenerateSerializer)
                    {
                        mapping = _mapping;
                    }
                    else
                    {
                        XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                        mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                    }

                    var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                    writer.WriteObject(o);
                }
                else if (_tempAssembly == null || _typedSerializer)
                {
                    // The contion for the block is never true, thus the block is never hit.
                    XmlSerializationWriter writer = CreateWriter();
                    writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
                    try
                    {
                        Serialize(o, writer);
                    }
                    finally
                    {
                        writer.Dispose();
                    }
                }
                else
                {
                    _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                }
#else
                else
                {
                    if (this.innerSerializer != null)
                    {
                        if (!string.IsNullOrEmpty(this.DefaultNamespace))
                        {
                            this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
                        }

                        XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
                        writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        try
                        {
                            this.innerSerializer.Serialize(o, writer);
                        }
                        finally
                        {
                            writer.Dispose();
                        }
                    }
                    else if (ReflectionMethodEnabled)
                    {
                        XmlMapping mapping;
                        if (_mapping != null && _mapping.GenerateSerializer)
                        {
                            mapping = _mapping;
                        }
                        else
                        {
                            XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
                            mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
                        }

                        var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
                        writer.WriteObject(o);
                    }
                    else
                    {
                        throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
                    }
                }
#endif
            }
Пример #45
0
        /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
        {
#if NET_NATIVE
            throw new PlatformNotSupportedException();
#else
            if (type == null)
                throw new ArgumentNullException("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);
            _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
#endif
        }
Пример #46
0
		[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 ());
		}
Пример #47
0
 /// <include file='doc\XmlSerializerFactory.uex' path='docs/doc[@for="XmlSerializerFactory.CreateSerializer1"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlSerializer CreateSerializer(Type type, string defaultNamespace)
 {
     if (type == null)
         throw new ArgumentNullException(nameof(type));
     TempAssembly tempAssembly = s_cache[defaultNamespace, type];
     XmlTypeMapping mapping = null;
     if (tempAssembly == null)
     {
         lock (s_cache)
         {
             tempAssembly = s_cache[defaultNamespace, type];
             if (tempAssembly == null)
             {
                 XmlSerializerImplementation contract;
                 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 = XmlSerializer.GenerateTempAssembly(mapping, type, defaultNamespace);
                 }
                 else
                 {
                     tempAssembly = new TempAssembly(contract);
                 }
                 s_cache.Add(defaultNamespace, type, tempAssembly);
             }
         }
     }
     if (mapping == null)
     {
         mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
     }
     return (XmlSerializer)tempAssembly.Contract.GetSerializer(type);
 }
Пример #48
0
		public XmlSerializer (Type type,
			XmlAttributeOverrides overrides,
			Type [] extraTypes,
			XmlRootAttribute root,
			string defaultNamespace)
		{
			if (type == null)
				throw new ArgumentNullException ("type");

			XmlReflectionImporter importer = new XmlReflectionImporter (overrides, defaultNamespace);

			if (extraTypes != null) 
			{
				foreach (Type intype in extraTypes)
					importer.IncludeType (intype);
			}

			typeMapping = importer.ImportTypeMapping (type, root, defaultNamespace);
		}