internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract)
 {
     this.assembly = assembly;
     InitAssemblyMethods(xmlMappings);
     this.contract       = contract;
     pregeneratedAssmbly = true;
 }
 internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract)
 {
     this.assemblies = new Hashtable();
     this.assembly = assembly;
     this.InitAssemblyMethods(xmlMappings);
     this.contract = contract;
     this.pregeneratedAssmbly = true;
 }
        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);
            }
        }
예제 #4
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
        }
예제 #5
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
        }
예제 #6
0
        private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
        {
            XmlSerializer[] serializers = new XmlSerializer[mappings.Length];

            InternalHashtable typedMappingTable = null;

            lock (s_xmlSerializerTable)
            {
                typedMappingTable = s_xmlSerializerTable[type] as InternalHashtable;
                if (typedMappingTable == null)
                {
                    typedMappingTable          = new InternalHashtable();
                    s_xmlSerializerTable[type] = typedMappingTable;
                }
            }

            lock (typedMappingTable)
            {
                InternalHashtable pendingKeys = new InternalHashtable();
                for (int i = 0; i < mappings.Length; i++)
                {
                    XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
                    serializers[i] = typedMappingTable[mappingKey] as XmlSerializer;
                    if (serializers[i] == null)
                    {
                        pendingKeys.Add(mappingKey, i);
                    }
                }

                if (pendingKeys.Count > 0)
                {
                    XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
                    int          index           = 0;
                    foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
                    {
                        pendingMappings[index++] = mappingKey.Mapping;
                    }

                    TempAssembly tempAssembly            = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null);
                    XmlSerializerImplementation contract = tempAssembly.Contract;

                    foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
                    {
                        index = (int)pendingKeys[mappingKey];
                        serializers[index] = (XmlSerializer)contract.XmlTypedSerializers[mappingKey.Mapping.Key];
                        serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);

                        typedMappingTable[mappingKey] = serializers[index];
                    }
                }
            }

            return(serializers);
        }
        private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
        {
            XmlSerializer[] serializers = new XmlSerializer[mappings.Length];

            Dictionary <XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null;

            lock (s_xmlSerializerTable)
            {
                if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable))
                {
                    typedMappingTable          = new Dictionary <XmlSerializerMappingKey, XmlSerializer>();
                    s_xmlSerializerTable[type] = typedMappingTable;
                }
            }

            lock (typedMappingTable)
            {
                var pendingKeys = new Dictionary <XmlSerializerMappingKey, int>();
                for (int i = 0; i < mappings.Length; i++)
                {
                    XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
                    if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i]))
                    {
                        pendingKeys.Add(mappingKey, i);
                    }
                }

                if (pendingKeys.Count > 0)
                {
                    XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
                    int          index           = 0;
                    foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
                    {
                        pendingMappings[index++] = mappingKey.Mapping;
                    }

                    TempAssembly tempAssembly            = new TempAssembly(pendingMappings, new Type[] { type }, null, null);
                    XmlSerializerImplementation contract = tempAssembly.Contract;

                    foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
                    {
                        index = pendingKeys[mappingKey];
                        serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
                        serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);

                        typedMappingTable[mappingKey] = serializers[index];
                    }
                }
            }

            return(serializers);
        }
        public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
        {
            if (mappings == null || mappings.Length == 0)
            {
                return(new XmlSerializer[0]);
            }
            XmlSerializerImplementation contract = null;
            Assembly     assembly     = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract);
            TempAssembly tempAssembly = null;

            if (assembly == null)
            {
                if (XmlMapping.IsShallow(mappings))
                {
                    return(new XmlSerializer[0]);
                }
                else
                {
                    if (type == null)
                    {
                        tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
                        XmlSerializer[] serializers = new XmlSerializer[mappings.Length];

                        contract = tempAssembly.Contract;

                        for (int i = 0; i < serializers.Length; i++)
                        {
                            serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
                            serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
                        }

                        return(serializers);
                    }
                    else
                    {
                        // Use XmlSerializer cache when the type is not null.
                        return(GetSerializersFromCache(mappings, type));
                    }
                }
            }
            else
            {
                XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
                for (int i = 0; i < serializers.Length; i++)
                {
                    serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
                }
                return(serializers);
            }
        }
        private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
        {
            XmlSerializer[] serializerArray = new XmlSerializer[mappings.Length];
            Hashtable       hashtable       = null;

            lock (xmlSerializerTable)
            {
                hashtable = xmlSerializerTable[type] as Hashtable;
                if (hashtable == null)
                {
                    hashtable = new Hashtable();
                    xmlSerializerTable[type] = hashtable;
                }
            }
            lock (hashtable)
            {
                Hashtable hashtable2 = new Hashtable();
                for (int i = 0; i < mappings.Length; i++)
                {
                    XmlSerializerMappingKey key = new XmlSerializerMappingKey(mappings[i]);
                    serializerArray[i] = hashtable[key] as XmlSerializer;
                    if (serializerArray[i] == null)
                    {
                        hashtable2.Add(key, i);
                    }
                }
                if (hashtable2.Count <= 0)
                {
                    return(serializerArray);
                }
                XmlMapping[] xmlMappings = new XmlMapping[hashtable2.Count];
                int          index       = 0;
                foreach (XmlSerializerMappingKey key2 in hashtable2.Keys)
                {
                    xmlMappings[index++] = key2.Mapping;
                }
                TempAssembly tempAssembly            = new TempAssembly(xmlMappings, new Type[] { type }, null, null, null);
                XmlSerializerImplementation contract = tempAssembly.Contract;
                foreach (XmlSerializerMappingKey key3 in hashtable2.Keys)
                {
                    index = (int)hashtable2[key3];
                    serializerArray[index] = (XmlSerializer)contract.TypedSerializers[key3.Mapping.Key];
                    serializerArray[index].SetTempAssembly(tempAssembly, key3.Mapping);
                    hashtable[key3] = serializerArray[index];
                }
            }
            return(serializerArray);
        }
        public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Evidence evidence)
        {
            if (mappings == null || mappings.Length == 0)
            {
                return(new XmlSerializer[0]);
            }
            if (XmlMapping.IsShallow(mappings))
            {
                return(new XmlSerializer[0]);
            }
            TempAssembly tempAssembly            = new TempAssembly(mappings, new Type[0], null, null, evidence);
            XmlSerializerImplementation contract = tempAssembly.Contract;

            XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
            for (int i = 0; i < serializers.Length; i++)
            {
                serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
            }
            return(serializers);
        }
        public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
        {
            if ((mappings == null) || (mappings.Length == 0))
            {
                return(new XmlSerializer[0]);
            }
            XmlSerializerImplementation contract = null;
            Assembly     assembly     = (type == null) ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract);
            TempAssembly tempAssembly = null;

            if (assembly == null)
            {
                if (XmlMapping.IsShallow(mappings))
                {
                    return(new XmlSerializer[0]);
                }
                if (type != null)
                {
                    return(GetSerializersFromCache(mappings, type));
                }
                tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null);
                XmlSerializer[] serializerArray = new XmlSerializer[mappings.Length];
                contract = tempAssembly.Contract;
                for (int j = 0; j < serializerArray.Length; j++)
                {
                    serializerArray[j] = (XmlSerializer)contract.TypedSerializers[mappings[j].Key];
                    serializerArray[j].SetTempAssembly(tempAssembly, mappings[j]);
                }
                return(serializerArray);
            }
            XmlSerializer[] serializerArray2 = new XmlSerializer[mappings.Length];
            for (int i = 0; i < serializerArray2.Length; i++)
            {
                serializerArray2[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
            }
            return(serializerArray2);
        }
 internal TempAssembly(XmlSerializerImplementation contract)
 {
     this.contract       = contract;
     pregeneratedAssmbly = true;
 }
예제 #13
0
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        // SxS: This method does not take any resource name and does not expose any resources to the caller.
        // It's OK to suppress the SxS warning.
        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = type.Assembly.GetName();
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name        = serializerName;
                name.CodeBase    = null;
                name.CultureInfo = CultureInfo.InvariantCulture;

                string serializerPath = null;

                try
                {
                    if (!string.IsNullOrEmpty(type.Assembly.Location))
                    {
                        serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location), serializerName + ".dll");
                    }

                    if ((string.IsNullOrEmpty(serializerPath) || !File.Exists(serializerPath)) && !string.IsNullOrEmpty(Assembly.GetEntryAssembly().Location))
                    {
                        serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), serializerName + ".dll");
                    }

                    if (!string.IsNullOrEmpty(serializerPath))
                    {
                        serializer = Assembly.LoadFile(serializerPath);
                    }
                }
                catch (Exception e)
                {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                    {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
                }

                if (serializer == null)
                {
                    if (XmlSerializer.Mode == SerializationMode.PreGenOnly)
                    {
                        throw new Exception(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
                    }

                    return(null);
                }

                if (!IsSerializerVersionMatch(serializer, type, defaultNamespace))
                {
                    XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName);
                    return(null);
                }
            }
            else
            {
                System.Xml.Serialization.XmlSerializerAssemblyAttribute assemblyAttribute = (System.Xml.Serialization.XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer     = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.Assembly.FullName;
                    serializer     = type.Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

            return(null);
        }
예제 #14
0
 public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
 {
     xmlSerializerContract = xmlSerializerImplementation;
 }
예제 #15
0
 internal TempAssembly(XmlSerializerImplementation contract) {
     this.contract = contract;
     pregeneratedAssmbly = true;
 }
 internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
 {
     Assembly serializer = null;
     contract = null;
     string partialName = null;
     bool enabled = DiagnosticsSwitches.PregenEventLog.Enabled;
     object[] customAttributes = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
     if (customAttributes.Length == 0)
     {
         AssemblyName parent = GetName(type.Assembly, true);
         partialName = Compiler.GetTempAssemblyName(parent, defaultNamespace);
         parent.Name = partialName;
         parent.CodeBase = null;
         parent.CultureInfo = CultureInfo.InvariantCulture;
         try
         {
             serializer = Assembly.Load(parent);
         }
         catch (Exception exception)
         {
             if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
             {
                 throw;
             }
             if (enabled)
             {
                 Log(exception.Message, EventLogEntryType.Information);
             }
             byte[] publicKeyToken = parent.GetPublicKeyToken();
             if ((publicKeyToken != null) && (publicKeyToken.Length > 0))
             {
                 return null;
             }
             serializer = Assembly.LoadWithPartialName(partialName, null);
         }
         if (serializer == null)
         {
             if (enabled)
             {
                 Log(Res.GetString("XmlPregenCannotLoad", new object[] { partialName }), EventLogEntryType.Information);
             }
             return null;
         }
         if (!IsSerializerVersionMatch(serializer, type, defaultNamespace, null))
         {
             if (enabled)
             {
                 Log(Res.GetString("XmlSerializerExpiredDetails", new object[] { partialName, type.FullName }), EventLogEntryType.Error);
             }
             return null;
         }
     }
     else
     {
         XmlSerializerAssemblyAttribute attribute = (XmlSerializerAssemblyAttribute) customAttributes[0];
         if ((attribute.AssemblyName != null) && (attribute.CodeBase != null))
         {
             throw new InvalidOperationException(Res.GetString("XmlPregenInvalidXmlSerializerAssemblyAttribute", new object[] { "AssemblyName", "CodeBase" }));
         }
         if (attribute.AssemblyName != null)
         {
             partialName = attribute.AssemblyName;
             serializer = Assembly.LoadWithPartialName(partialName, null);
         }
         else if ((attribute.CodeBase != null) && (attribute.CodeBase.Length > 0))
         {
             partialName = attribute.CodeBase;
             serializer = Assembly.LoadFrom(partialName);
         }
         else
         {
             partialName = type.Assembly.FullName;
             serializer = type.Assembly;
         }
         if (serializer == null)
         {
             throw new FileNotFoundException(null, partialName);
         }
     }
     Type typeFromAssembly = GetTypeFromAssembly(serializer, "XmlSerializerContract");
     contract = (XmlSerializerImplementation) Activator.CreateInstance(typeFromAssembly);
     if (contract.CanSerialize(type))
     {
         return serializer;
     }
     if (enabled)
     {
         Log(Res.GetString("XmlSerializerExpiredDetails", new object[] { partialName, type.FullName }), EventLogEntryType.Error);
     }
     return null;
 }
예제 #17
0
파일: Compilation.cs 프로젝트: x11us/corefx
 internal TempAssembly(XmlSerializerImplementation contract)
 {
     _contract = contract;
 }
        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            // Packaged apps do not support loading generated serializers.
            if (Microsoft.Win32.UnsafeNativeMethods.IsPackagedProcess.Value)
            {
                return(null);
            }

            bool logEnabled = DiagnosticsSwitches.PregenEventLog.Enabled;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = GetName(type.Assembly, true);
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name        = serializerName;
                name.CodeBase    = null;
                name.CultureInfo = CultureInfo.InvariantCulture;
                try {
                    serializer = Assembly.Load(name);
                }
                catch (Exception e) {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                    {
                        throw;
                    }
                    if (logEnabled)
                    {
                        Log(e.Message, EventLogEntryType.Information);
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618
                }
                if (serializer == null)
                {
#if !FEATURE_PAL // EventLog
                    if (logEnabled)
                    {
                        Log(Res.GetString(Res.XmlPregenCannotLoad, serializerName), EventLogEntryType.Information);
                    }
#endif //!FEATURE_PAL // EventLog
                    return(null);
                }
                if (!IsSerializerVersionMatch(serializer, type, defaultNamespace, null))
                {
#if !FEATURE_PAL // EventLog
                    if (logEnabled)
                    {
                        Log(Res.GetString(Res.XmlSerializerExpiredDetails, serializerName, type.FullName), EventLogEntryType.Error);
                    }
#endif //!FEATURE_PAL // EventLog
                    return(null);
                }
            }
            else
            {
                XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer     = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.Assembly.FullName;
                    serializer     = type.Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

#if !FEATURE_PAL // EventLog
            if (logEnabled)
            {
                Log(Res.GetString(Res.XmlSerializerExpiredDetails, serializerName, type.FullName), EventLogEntryType.Error);
            }
#endif //!FEATURE_PAL // EventLog
            return(null);
        }
        public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
        {
            if (mappings == null || mappings.Length == 0)
            {
                return(Array.Empty <XmlSerializer>());
            }
            bool anySoapMapping = false;

            foreach (var mapping in mappings)
            {
                if (mapping.IsSoap)
                {
                    anySoapMapping = true;
                }
            }

            if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly)
            {
                XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type);
                return(serializers);
            }

            XmlSerializerImplementation contract = null;
            Assembly     assembly     = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract);
            TempAssembly tempAssembly = null;

            if (assembly == null)
            {
                if (Mode == SerializationMode.PreGenOnly)
                {
                    AssemblyName name           = type.Assembly.GetName();
                    string       serializerName = Compiler.GetTempAssemblyName(name, null);
                    throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName));
                }

                if (XmlMapping.IsShallow(mappings))
                {
                    return(Array.Empty <XmlSerializer>());
                }
                else
                {
                    if (type == null)
                    {
                        tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null);
                        XmlSerializer[] serializers = new XmlSerializer[mappings.Length];

                        contract = tempAssembly.Contract;

                        for (int i = 0; i < serializers.Length; i++)
                        {
                            serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
                            serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
                        }

                        return(serializers);
                    }
                    else
                    {
                        // Use XmlSerializer cache when the type is not null.
                        return(GetSerializersFromCache(mappings, type));
                    }
                }
            }
            else
            {
                XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
                for (int i = 0; i < serializers.Length; i++)
                {
                    serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
                }
                return(serializers);
            }
        }
예제 #20
0
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        // SxS: This method does not take any resource name and does not expose any resources to the caller.
        // It's OK to suppress the SxS warning.
        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = type.GetTypeInfo().Assembly.GetName();
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name        = serializerName;
                name.CodeBase    = null;
                name.CultureInfo = CultureInfo.InvariantCulture;
                try
                {
                    serializer = Assembly.Load(name);
                }
                catch (Exception e)
                {
                    if (e is OutOfMemoryException)
                    {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                if (serializer == null)
                {
                    return(null);
                }
            }
            else
            {
                XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer     = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.GetTypeInfo().Assembly.FullName;
                    serializer     = type.GetTypeInfo().Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

            return(null);
        }
예제 #21
0
파일: Compilation.cs 프로젝트: x11us/corefx
 internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract)
 {
     _assembly = assembly;
     InitAssemblyMethods(xmlMappings);
     _contract = contract;
 }
예제 #22
0
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) {
            Assembly serializer = null;
            contract = null;
            string serializerName = null;
            bool logEnabled = DiagnosticsSwitches.PregenEventLog.Enabled;

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0) {
                // Guess serializer name: if parent assembly signed use strong name 
                AssemblyName name = GetName(type.Assembly, true);
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name 
                name.Name = serializerName;
                name.CodeBase = null;
                name.CultureInfo = CultureInfo.InvariantCulture;
                try {
                    serializer = Assembly.Load(name);
                }
                catch (Exception e) {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0) {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return null;
                    }
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618
                }
                catch {
                    return null;
                }
                if (serializer == null) {
                    return null;
                }
                if (!IsSerializerVersionMatch(serializer, type, defaultNamespace, null)) {
                    return null;
                }
            }
            else {
                XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                    throw new InvalidOperationException(Res.GetString(Res.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase")); 

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null) {
                    serializerName = assemblyAttribute.AssemblyName;
#pragma warning disable 618
                    serializer = Assembly.LoadWithPartialName(serializerName, null);
#pragma warning restore 618
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0) {
                    serializerName = assemblyAttribute.CodeBase;
                    serializer = Assembly.LoadFrom(serializerName);
                }
                else {
                    serializerName = type.Assembly.FullName;
                    serializer = type.Assembly;
                }
                if (serializer == null) {
                    throw new FileNotFoundException(null, serializerName); 
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");
            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
                return serializer;

            return null;
        }
예제 #23
0
파일: Compilation.cs 프로젝트: x11us/corefx
        /// <devdoc>
        ///    <para>
        ///    Attempts to load pre-generated serialization assembly.
        ///    First check for the [XmlSerializerAssembly] attribute
        ///    </para>
        /// </devdoc>
        // SxS: This method does not take any resource name and does not expose any resources to the caller.
        // It's OK to suppress the SxS warning.
        internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract)
        {
            Assembly serializer = null;

            contract = null;
            string serializerName = null;

            //BinCompat TODO: Check if this needs to come back
            // Packaged apps do not support loading generated serializers.

            /*if (Microsoft.Win32.UnsafeNativeMethods.IsPackagedProcess.Value)
             * {
             *  return null;
             * }*/

            // check to see if we loading explicit pre-generated assembly
            object[] attrs = type.GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false);
            if (attrs.Length == 0)
            {
                // Guess serializer name: if parent assembly signed use strong name
                AssemblyName name = type.GetTypeInfo().Assembly.GetName();
                serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace);
                // use strong name
                name.Name = serializerName;
                //BinCompat TODO: Check if this was actually needed
                //name.CodeBase = null;
                //name.CultureInfo = CultureInfo.InvariantCulture;
                try
                {
                    serializer = Assembly.Load(name);
                }
                catch (Exception e)
                {
                    if (e is OutOfMemoryException)
                    {
                        throw;
                    }
                    byte[] token = name.GetPublicKeyToken();
                    if (token != null && token.Length > 0)
                    {
                        // the parent assembly was signed, so do not try to LoadWithPartialName
                        return(null);
                    }
                    //BinCompat TODO: Test this
                    throw new NotImplementedException(string.Format("Could not load assembly ", name));

                    /*#pragma warning disable 618
                    *                   serializer = Assembly.LoadWithPartialName(serializerName, null);
                    #pragma warning restore 618*/
                }
                if (serializer == null)
                {
                    return(null);
                }
            }
            else
            {
                XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs[0];
                if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null)
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase"));
                }

                // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer
                if (assemblyAttribute.AssemblyName != null)
                {
                    serializerName = assemblyAttribute.AssemblyName;
                    //BinCompat TODO: Test this
                    throw new NotImplementedException(string.Format("Could not load assembly ", serializerName));

                    /*#pragma warning disable 618
                    *                   serializer = Assembly.LoadWithPartialName(serializerName, null);
                    #pragma warning restore 618*/
                }
                else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0)
                {
                    serializerName = assemblyAttribute.CodeBase;
                    //BinCompat TODO: Test this
                    throw new NotImplementedException(string.Format("Could not load assembly ", serializerName));
                    //serializer = Assembly.LoadFrom(serializerName);
                }
                else
                {
                    serializerName = type.GetTypeInfo().Assembly.FullName;
                    serializer     = type.GetTypeInfo().Assembly;
                }
                if (serializer == null)
                {
                    throw new FileNotFoundException(null, serializerName);
                }
            }
            Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract");

            contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType);
            if (contract.CanSerialize(type))
            {
                return(serializer);
            }

            return(null);
        }
 internal TempAssembly(XmlSerializerImplementation contract)
 {
     this.assemblies = new Hashtable();
     this.contract = contract;
     this.pregeneratedAssmbly = true;
 }