コード例 #1
0
        public static Assembly GenerateSerializer(Type[] types, XmlMapping[] mappings, CompilerParameters parameters)
        {
            if ((types == null) || (types.Length == 0))
            {
                return(null);
            }
            if (mappings == null)
            {
                throw new ArgumentNullException("mappings");
            }
            if (XmlMapping.IsShallow(mappings))
            {
                throw new InvalidOperationException(Res.GetString("XmlMelformMapping"));
            }
            Assembly assembly = null;

            for (int i = 0; i < types.Length; i++)
            {
                Type type = types[i];
                if (DynamicAssemblies.IsTypeDynamic(type))
                {
                    throw new InvalidOperationException(Res.GetString("XmlPregenTypeDynamic", new object[] { type.FullName }));
                }
                if (assembly == null)
                {
                    assembly = type.Assembly;
                }
                else if (type.Assembly != assembly)
                {
                    throw new ArgumentException(Res.GetString("XmlPregenOrphanType", new object[] { type.FullName, assembly.Location }), "types");
                }
            }
            return(TempAssembly.GenerateAssembly(mappings, types, null, null, XmlSerializerCompilerParameters.Create(parameters, true), assembly, new Hashtable()));
        }
コード例 #2
0
 internal void AddImport(Type type, Hashtable types)
 {
     if (((type != null) && !TypeScope.IsKnownType(type)) && (types[type] == null))
     {
         types[type] = type;
         Type baseType = type.BaseType;
         if (baseType != null)
         {
             this.AddImport(baseType, types);
         }
         Type declaringType = type.DeclaringType;
         if (declaringType != null)
         {
             this.AddImport(declaringType, types);
         }
         foreach (Type type4 in type.GetInterfaces())
         {
             this.AddImport(type4, types);
         }
         ConstructorInfo[] constructors = type.GetConstructors();
         for (int i = 0; i < constructors.Length; i++)
         {
             ParameterInfo[] parameters = constructors[i].GetParameters();
             for (int j = 0; j < parameters.Length; j++)
             {
                 this.AddImport(parameters[j].ParameterType, types);
             }
         }
         if (type.IsGenericType)
         {
             Type[] genericArguments = type.GetGenericArguments();
             for (int k = 0; k < genericArguments.Length; k++)
             {
                 this.AddImport(genericArguments[k], types);
             }
         }
         TempAssembly.FileIOPermission.Assert();
         Assembly a = type.Module.Assembly;
         if (DynamicAssemblies.IsTypeDynamic(type))
         {
             DynamicAssemblies.Add(a);
         }
         else
         {
             object[] customAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
             if (customAttributes.Length > 0)
             {
                 TypeForwardedFromAttribute attribute = customAttributes[0] as TypeForwardedFromAttribute;
                 Assembly assembly2 = Assembly.Load(attribute.AssemblyFullName);
                 this.imports[assembly2] = assembly2.Location;
             }
             this.imports[a] = a.Location;
         }
     }
 }
コード例 #3
0
        private string WriteAssemblyInfo(Type type)
        {
            string fullName = type.Assembly.FullName;
            string str2     = (string)this.reflectionVariables[fullName];

            if (str2 == null)
            {
                int    index = fullName.IndexOf(',');
                string str3  = (index > -1) ? fullName.Substring(0, index) : fullName;
                str2 = this.GenerateVariableName("assembly", str3);
                this.writer.Write("static " + typeof(Assembly).FullName + " " + str2 + " = ResolveDynamicAssembly(");
                this.WriteQuotedCSharpString(DynamicAssemblies.GetName(type.Assembly));
                this.writer.WriteLine(");");
                this.reflectionVariables.Add(fullName, str2);
            }
            return(str2);
        }
コード例 #4
0
        internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream)
        {
            if (types == null || types.Length == 0)
            {
                return(false);
            }

            if (mappings == null)
            {
                throw new ArgumentNullException(nameof(mappings));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (XmlMapping.IsShallow(mappings))
            {
                throw new InvalidOperationException(SR.XmlMelformMapping);
            }

            Assembly assembly = null;

            for (int i = 0; i < types.Length; i++)
            {
                Type type = types[i];
                if (DynamicAssemblies.IsTypeDynamic(type))
                {
                    throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, type.FullName));
                }

                if (assembly == null)
                {
                    assembly = type.Assembly;
                }
                else if (type.Assembly != assembly)
                {
                    throw new ArgumentException(SR.Format(SR.XmlPregenOrphanType, type.FullName, assembly.Location), nameof(types));
                }
            }

            return(TempAssembly.GenerateSerializerToStream(mappings, types, null, assembly, new Hashtable(), stream));
        }
コード例 #5
0
        internal void GenerateSupportedTypes(Type[] types)
        {
            _writer.Write("public override ");
            _writer.Write(typeof(bool).FullName);
            _writer.Write(" CanSerialize(");
            _writer.Write(typeof(Type).FullName);
            _writer.WriteLine(" type) {");
            _writer.Indent++;
            Hashtable uniqueTypes = new Hashtable();

            for (int i = 0; i < types.Length; i++)
            {
                Type type = types[i];

                if (type == null)
                {
                    continue;
                }
                if (!type.IsPublic && !type.IsNestedPublic)
                {
                    continue;
                }
                if (uniqueTypes[type] != null)
                {
                    continue;
                }
                if (DynamicAssemblies.IsTypeDynamic(type))
                {
                    continue;
                }
                if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
                {
                    continue;
                }
                uniqueTypes[type] = type;
                _writer.Write("if (type == typeof(");
                _writer.Write(CodeIdentifier.GetCSharpName(type));
                _writer.WriteLine(")) return true;");
            }
            _writer.WriteLine("return false;");
            _writer.Indent--;
            _writer.WriteLine("}");
        }
コード例 #6
0
        //GenerateGetSerializer(serializers, xmlMappings);
        private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings)
        {
            _writer.Write("public override ");
            _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName);
            _writer.Write(" GetSerializer(");
            _writer.Write(typeof(Type).FullName);
            _writer.WriteLine(" type) {");
            _writer.Indent++;

            for (int i = 0; i < xmlMappings.Length; i++)
            {
                if (xmlMappings[i] is XmlTypeMapping)
                {
                    Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
                    if (type == null)
                    {
                        continue;
                    }
                    if (!type.IsPublic && !type.IsNestedPublic)
                    {
                        continue;
                    }
                    if (DynamicAssemblies.IsTypeDynamic(type))
                    {
                        continue;
                    }
                    if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))
                    {
                        continue;
                    }
                    _writer.Write("if (type == typeof(");
                    _writer.Write(CodeIdentifier.GetCSharpName(type));
                    _writer.Write(")) return new ");
                    _writer.Write((string)serializers[xmlMappings[i].Key]);
                    _writer.WriteLine("();");
                }
            }
            _writer.WriteLine("return null;");
            _writer.Indent--;
            _writer.WriteLine("}");
        }
コード例 #7
0
        internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
        {
            FileIOPermission.Assert();
            Compiler compiler = new Compiler();

            try {
                Hashtable scopeTable = new Hashtable();
                foreach (XmlMapping mapping in xmlMappings)
                {
                    scopeTable[mapping.Scope] = mapping;
                }
                TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count];
                scopeTable.Keys.CopyTo(scopes, 0);

                assemblies.Clear();
                Hashtable importedTypes = new Hashtable();
                foreach (TypeScope scope in scopes)
                {
                    foreach (Type t in scope.Types)
                    {
                        compiler.AddImport(t, importedTypes);
                        Assembly a    = t.Assembly;
                        string   name = a.FullName;
                        if (assemblies[name] != null)
                        {
                            continue;
                        }
                        if (!a.GlobalAssemblyCache)
                        {
                            assemblies[name] = a;
                        }
                    }
                }
                for (int i = 0; i < types.Length; i++)
                {
                    compiler.AddImport(types[i], importedTypes);
                }
                compiler.AddImport(typeof(object).Assembly);
                compiler.AddImport(typeof(XmlSerializer).Assembly);

                IndentedWriter writer = new IndentedWriter(compiler.Source, false);

                writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION");
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
                writer.WriteLine("[assembly:System.Security.SecurityTransparent()]");
                writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]");
                writer.WriteLine("#endif");
                // Add AssemblyVersion attribute to match parent accembly version
                if (types != null && types.Length > 0 && types[0] != null)
                {
                    writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]");
                }
                if (assembly != null && types.Length > 0)
                {
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type type = types[i];
                        if (type == null)
                        {
                            continue;
                        }
                        if (DynamicAssemblies.IsTypeDynamic(type))
                        {
                            throw new InvalidOperationException(Res.GetString(Res.XmlPregenTypeDynamic, types[i].FullName));
                        }
                    }
                    writer.Write("[assembly:");
                    writer.Write(typeof(XmlSerializerVersionAttribute).FullName);
                    writer.Write("(");
                    writer.Write("ParentAssemblyId=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]));
                    writer.Write(", Version=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version);
                    if (defaultNamespace != null)
                    {
                        writer.Write(", Namespace=");
                        ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace);
                    }
                    writer.WriteLine(")]");
                }
                CodeIdentifiers classes = new CodeIdentifiers();
                classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter");
                classes.AddUnique("XmlSerializationReader", "XmlSerializationReader");
                string suffix = null;
                if (types != null && types.Length == 1 && types[0] != null)
                {
                    suffix = CodeIdentifier.MakeValid(types[0].Name);
                    if (types[0].IsArray)
                    {
                        suffix += "Array";
                    }
                }

                writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {");
                writer.Indent++;

                writer.WriteLine();

                string writerClass = "XmlSerializationWriter" + suffix;
                writerClass = classes.AddUnique(writerClass, writerClass);
                XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass);

                writerCodeGen.GenerateBegin();
                string[] writeMethodNames = new string[xmlMappings.Length];

                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]);
                }
                writerCodeGen.GenerateEnd();

                writer.WriteLine();

                string readerClass = "XmlSerializationReader" + suffix;
                readerClass = classes.AddUnique(readerClass, readerClass);
                XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass);

                readerCodeGen.GenerateBegin();
                string[] readMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]);
                }
                readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types);

                string    baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes);
                Hashtable serializers    = new Hashtable();
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    if (serializers[xmlMappings[i].Key] == null)
                    {
                        serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass);
                    }
                }
                readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers);
                writer.Indent--;
                writer.WriteLine("}");

                return(compiler.Compile(assembly, defaultNamespace, parameters, evidence));
            }
            finally {
                compiler.Close();
            }
        }
コード例 #8
0
        // 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 void AddImport(Type type, Hashtable types)
        {
            if (type == null)
            {
                return;
            }
            if (TypeScope.IsKnownType(type))
            {
                return;
            }
            if (types[type] != null)
            {
                return;
            }
            types[type] = type;
            Type baseType = type.GetTypeInfo().BaseType;

            if (baseType != null)
            {
                AddImport(baseType, types);
            }

            Type declaringType = type.DeclaringType;

            if (declaringType != null)
            {
                AddImport(declaringType, types);
            }

            foreach (Type intf in type.GetInterfaces())
            {
                AddImport(intf, types);
            }

            ConstructorInfo[] ctors = type.GetConstructors();
            for (int i = 0; i < ctors.Length; i++)
            {
                ParameterInfo[] parms = ctors[i].GetParameters();
                for (int j = 0; j < parms.Length; j++)
                {
                    AddImport(parms[j].ParameterType, types);
                }
            }

            if (type.GetTypeInfo().IsGenericType)
            {
                Type[] arguments = type.GetGenericArguments();
                for (int i = 0; i < arguments.Length; i++)
                {
                    AddImport(arguments[i], types);
                }
            }

            Module   module   = type.GetTypeInfo().Module;
            Assembly assembly = module.Assembly;

            if (DynamicAssemblies.IsTypeDynamic(type))
            {
                DynamicAssemblies.Add(assembly);
                return;
            }

            object[] typeForwardedFromAttribute = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
            if (typeForwardedFromAttribute.Length > 0)
            {
                TypeForwardedFromAttribute originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute;
                Assembly originalAssembly = Assembly.Load(new AssemblyName(originalAssemblyInfo.AssemblyFullName));
                //_imports[originalAssembly] = originalAssembly.Location;
            }
            //_imports[assembly] = assembly.Location;
        }
コード例 #9
0
ファイル: Compilation.cs プロジェクト: zouql/runtime
        internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream)
        {
            var compiler = new Compiler();

            try
            {
                var scopeTable = new Hashtable();
                foreach (XmlMapping mapping in xmlMappings)
                {
                    scopeTable[mapping.Scope] = mapping;
                }

                var scopes = new TypeScope[scopeTable.Keys.Count];
                scopeTable.Keys.CopyTo(scopes, 0);
                assemblies.Clear();
                var importedTypes = new Hashtable();

                foreach (TypeScope scope in scopes)
                {
                    foreach (Type t in scope.Types)
                    {
                        compiler.AddImport(t, importedTypes);
                        Assembly a    = t.Assembly;
                        string   name = a.FullName;
                        if (assemblies[name] != null)
                        {
                            continue;
                        }

                        assemblies[name] = a;
                    }
                }

                for (int i = 0; i < types.Length; i++)
                {
                    compiler.AddImport(types[i], importedTypes);
                }

                compiler.AddImport(typeof(object).Assembly);
                compiler.AddImport(typeof(System.Xml.Serialization.XmlSerializer).Assembly);
                var writer = new IndentedWriter(compiler.Source, false);
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
                writer.WriteLine("[assembly:System.Security.SecurityTransparent()]");
                writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]");

                if (assembly != null && types.Length > 0)
                {
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type type = types[i];
                        if (type == null)
                        {
                            continue;
                        }

                        if (DynamicAssemblies.IsTypeDynamic(type))
                        {
                            throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName));
                        }
                    }

                    writer.Write("[assembly:");
                    writer.Write(typeof(XmlSerializerVersionAttribute).FullName);
                    writer.Write("(");
                    writer.Write("ParentAssemblyId=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]));
                    writer.Write(", Version=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version);
                    if (defaultNamespace != null)
                    {
                        writer.Write(", Namespace=");
                        ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace);
                    }

                    writer.WriteLine(")]");
                }

                var classes = new CodeIdentifiers();
                classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter");
                classes.AddUnique("XmlSerializationReader", "XmlSerializationReader");
                string suffix = null;

                if (types != null && types.Length == 1 && types[0] != null)
                {
                    suffix = CodeIdentifier.MakeValid(types[0].Name);
                    if (types[0].IsArray)
                    {
                        suffix += "Array";
                    }
                }

                writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {");
                writer.Indent++;
                writer.WriteLine();

                string writerClass = "XmlSerializationWriter" + suffix;
                writerClass = classes.AddUnique(writerClass, writerClass);
                var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass);
                writerCodeGen.GenerateBegin();
                string[] writeMethodNames = new string[xmlMappings.Length];

                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]);
                }

                writerCodeGen.GenerateEnd();
                writer.WriteLine();

                string readerClass = "XmlSerializationReader" + suffix;
                readerClass = classes.AddUnique(readerClass, readerClass);
                var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass);
                readerCodeGen.GenerateBegin();
                string[] readMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]);
                }

                readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types);

                string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes);
                var    serializers    = new Hashtable();
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    if (serializers[xmlMappings[i].Key] == null)
                    {
                        serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass);
                    }
                }

                readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers);
                writer.Indent--;
                writer.WriteLine("}");

                string codecontent = compiler.Source.ToString();
                byte[] info        = new UTF8Encoding(true).GetBytes(codecontent);
                stream.Write(info, 0, info.Length);
                stream.Flush();
                return(true);
            }
            finally
            {
                compiler.Close();
            }
        }
コード例 #10
0
        internal void GenerateSupportedTypes(Type[] types)
        {
            this.writer.Write("public override ");
            this.writer.Write(typeof(bool).FullName);
            this.writer.Write(" CanSerialize(");
            this.writer.Write(typeof(Type).FullName);
            this.writer.WriteLine(" type) {");
            this.writer.Indent++;
            Hashtable hashtable = new Hashtable();

            for (int i = 0; i < types.Length; i++)
            {
                Type type = types[i];
                if (((type != null) && (type.IsPublic || type.IsNestedPublic)) && ((((hashtable[type] == null) && !DynamicAssemblies.IsTypeDynamic(type)) && !type.IsGenericType) && (!type.ContainsGenericParameters || !DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments()))))
                {
                    hashtable[type] = type;
                    this.writer.Write("if (type == typeof(");
                    this.writer.Write(CodeIdentifier.GetCSharpName(type));
                    this.writer.WriteLine(")) return true;");
                }
            }
            this.writer.WriteLine("return false;");
            this.writer.Indent--;
            this.writer.WriteLine("}");
        }
コード例 #11
0
        internal void AddImport(Type type, Hashtable types)
        {
            if (type == null)
            {
                return;
            }
            if (TypeScope.IsKnownType(type))
            {
                return;
            }
            if (types[type] != null)
            {
                return;
            }
            types[type] = type;
            Type baseType = type.BaseType;

            if (baseType != null)
            {
                AddImport(baseType, types);
            }

            Type declaringType = type.DeclaringType;

            if (declaringType != null)
            {
                AddImport(declaringType, types);
            }

            foreach (Type intf in type.GetInterfaces())
            {
                AddImport(intf, types);
            }

            ConstructorInfo[] ctors = type.GetConstructors();
            for (int i = 0; i < ctors.Length; i++)
            {
                ParameterInfo[] parms = ctors[i].GetParameters();
                for (int j = 0; j < parms.Length; j++)
                {
                    AddImport(parms[j].ParameterType, types);
                }
            }

            if (type.IsGenericType)
            {
                Type[] arguments = type.GetGenericArguments();
                for (int i = 0; i < arguments.Length; i++)
                {
                    AddImport(arguments[i], types);
                }
            }

            TempAssembly.FileIOPermission.Assert();
            Module   module   = type.Module;
            Assembly assembly = module.Assembly;

            if (DynamicAssemblies.IsTypeDynamic(type))
            {
                DynamicAssemblies.Add(assembly);
                return;
            }
            imports[assembly] = assembly.Location;
        }
コード例 #12
0
        private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
        {
            TypeDesc  desc = null;
            TypeKind  root;
            Type      elementType = null;
            Type      baseType    = null;
            TypeFlags none        = TypeFlags.None;
            Exception exception   = null;

            if (!type.IsPublic && !type.IsNestedPublic)
            {
                none     |= TypeFlags.Unsupported;
                exception = new InvalidOperationException(Res.GetString("XmlTypeInaccessible", new object[] { type.FullName }));
            }
            else if (type.IsAbstract && type.IsSealed)
            {
                none     |= TypeFlags.Unsupported;
                exception = new InvalidOperationException(Res.GetString("XmlTypeStatic", new object[] { type.FullName }));
            }
            if (DynamicAssemblies.IsTypeDynamic(type))
            {
                none |= TypeFlags.UseReflection;
            }
            if (!type.IsValueType)
            {
                none |= TypeFlags.Reference;
            }
            if (type == typeof(object))
            {
                root  = TypeKind.Root;
                none |= TypeFlags.HasDefaultConstructor;
            }
            else if (type == typeof(ValueType))
            {
                root  = TypeKind.Enum;
                none |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(Res.GetString("XmlSerializerUnsupportedType", new object[] { type.FullName }));
                }
            }
            else if (type == typeof(void))
            {
                root = TypeKind.Void;
            }
            else if (typeof(IXmlSerializable).IsAssignableFrom(type))
            {
                root  = TypeKind.Serializable;
                none |= TypeFlags.CanBeElementValue | TypeFlags.Special;
                none |= GetConstructorFlags(type, ref exception);
            }
            else if (type.IsArray)
            {
                root = TypeKind.Array;
                if (type.GetArrayRank() > 1)
                {
                    none |= TypeFlags.Unsupported;
                    if (exception == null)
                    {
                        exception = new NotSupportedException(Res.GetString("XmlUnsupportedRank", new object[] { type.FullName }));
                    }
                }
                elementType = type.GetElementType();
                none       |= TypeFlags.HasDefaultConstructor;
            }
            else if (typeof(ICollection).IsAssignableFrom(type))
            {
                root        = TypeKind.Collection;
                elementType = GetCollectionElementType(type, (memberInfo == null) ? null : (memberInfo.DeclaringType.FullName + "." + memberInfo.Name));
                none       |= GetConstructorFlags(type, ref exception);
            }
            else if (type == typeof(XmlQualifiedName))
            {
                root = TypeKind.Primitive;
            }
            else if (type.IsPrimitive)
            {
                root  = TypeKind.Primitive;
                none |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(Res.GetString("XmlSerializerUnsupportedType", new object[] { type.FullName }));
                }
            }
            else if (type.IsEnum)
            {
                root = TypeKind.Enum;
            }
            else if (type.IsValueType)
            {
                root = TypeKind.Struct;
                if (IsOptionalValue(type))
                {
                    baseType = type.GetGenericArguments()[0];
                    none    |= TypeFlags.OptionalValue;
                }
                else
                {
                    baseType = type.BaseType;
                }
                if (type.IsAbstract)
                {
                    none |= TypeFlags.Abstract;
                }
            }
            else if (type.IsClass)
            {
                if (type == typeof(XmlAttribute))
                {
                    root  = TypeKind.Attribute;
                    none |= TypeFlags.CanBeAttributeValue | TypeFlags.Special;
                }
                else if (typeof(XmlNode).IsAssignableFrom(type))
                {
                    root     = TypeKind.Node;
                    baseType = type.BaseType;
                    none    |= TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Special;
                    if (typeof(XmlText).IsAssignableFrom(type))
                    {
                        none &= ~TypeFlags.CanBeElementValue;
                    }
                    else if (typeof(XmlElement).IsAssignableFrom(type))
                    {
                        none &= ~TypeFlags.CanBeTextValue;
                    }
                    else if (type.IsAssignableFrom(typeof(XmlAttribute)))
                    {
                        none |= TypeFlags.CanBeAttributeValue;
                    }
                }
                else
                {
                    root     = TypeKind.Class;
                    baseType = type.BaseType;
                    if (type.IsAbstract)
                    {
                        none |= TypeFlags.Abstract;
                    }
                }
            }
            else if (type.IsInterface)
            {
                root  = TypeKind.Void;
                none |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    if (memberInfo == null)
                    {
                        exception = new NotSupportedException(Res.GetString("XmlUnsupportedInterface", new object[] { type.FullName }));
                    }
                    else
                    {
                        exception = new NotSupportedException(Res.GetString("XmlUnsupportedInterfaceDetails", new object[] { memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName }));
                    }
                }
            }
            else
            {
                root  = TypeKind.Void;
                none |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(Res.GetString("XmlSerializerUnsupportedType", new object[] { type.FullName }));
                }
            }
            if ((root == TypeKind.Class) && !type.IsAbstract)
            {
                none |= GetConstructorFlags(type, ref exception);
            }
            if (((root == TypeKind.Struct) || (root == TypeKind.Class)) && typeof(IEnumerable).IsAssignableFrom(type))
            {
                elementType = GetEnumeratorElementType(type, ref none);
                root        = TypeKind.Enumerable;
                none       |= GetConstructorFlags(type, ref exception);
            }
            desc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), root, null, none, null)
            {
                Exception = exception
            };
            if (directReference && (desc.IsClass || (root == TypeKind.Serializable)))
            {
                desc.CheckNeedConstructor();
            }
            if (!desc.IsUnsupported)
            {
                this.typeDescs.Add(type, desc);
                if (elementType != null)
                {
                    TypeDesc desc2 = this.GetTypeDesc(elementType, memberInfo, true, false);
                    if ((directReference && (desc2.IsCollection || desc2.IsEnumerable)) && !desc2.IsPrimitive)
                    {
                        desc2.CheckNeedConstructor();
                    }
                    desc.ArrayElementTypeDesc = desc2;
                }
                if (((baseType != null) && (baseType != typeof(object))) && (baseType != typeof(ValueType)))
                {
                    desc.BaseTypeDesc = this.GetTypeDesc(baseType, memberInfo, false, false);
                }
                if (type.IsNestedPublic)
                {
                    for (Type type4 = type.DeclaringType; (type4 != null) && !type4.ContainsGenericParameters; type4 = type4.DeclaringType)
                    {
                        this.GetTypeDesc(type4, null, false);
                    }
                }
            }
            return(desc);
        }
コード例 #13
0
 internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
 {
     Assembly assembly3;
     FileIOPermission.Assert();
     for (int i = 0; i < xmlMappings.Length; i++)
     {
         xmlMappings[i].CheckShallow();
     }
     Compiler compiler = new Compiler();
     try
     {
         Hashtable hashtable = new Hashtable();
         foreach (XmlMapping mapping in xmlMappings)
         {
             hashtable[mapping.Scope] = mapping;
         }
         TypeScope[] array = new TypeScope[hashtable.Keys.Count];
         hashtable.Keys.CopyTo(array, 0);
         assemblies.Clear();
         Hashtable hashtable2 = new Hashtable();
         foreach (TypeScope scope in array)
         {
             foreach (Type type in scope.Types)
             {
                 compiler.AddImport(type, hashtable2);
                 Assembly assembly2 = type.Assembly;
                 string fullName = assembly2.FullName;
                 if ((assemblies[fullName] == null) && !assembly2.GlobalAssemblyCache)
                 {
                     assemblies[fullName] = assembly2;
                 }
             }
         }
         for (int j = 0; j < types.Length; j++)
         {
             compiler.AddImport(types[j], hashtable2);
         }
         compiler.AddImport(typeof(object).Assembly);
         compiler.AddImport(typeof(XmlSerializer).Assembly);
         IndentedWriter writer = new IndentedWriter(compiler.Source, false);
         writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION");
         writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
         writer.WriteLine("[assembly:System.Security.SecurityTransparent()]");
         writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]");
         writer.WriteLine("#endif");
         if (((types != null) && (types.Length > 0)) && (types[0] != null))
         {
             writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]");
         }
         if ((assembly != null) && (types.Length > 0))
         {
             for (int num3 = 0; num3 < types.Length; num3++)
             {
                 Type type2 = types[num3];
                 if ((type2 != null) && DynamicAssemblies.IsTypeDynamic(type2))
                 {
                     throw new InvalidOperationException(Res.GetString("XmlPregenTypeDynamic", new object[] { types[num3].FullName }));
                 }
             }
             writer.Write("[assembly:");
             writer.Write(typeof(XmlSerializerVersionAttribute).FullName);
             writer.Write("(");
             writer.Write("ParentAssemblyId=");
             ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]));
             writer.Write(", Version=");
             ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, "4.0.0.0");
             if (defaultNamespace != null)
             {
                 writer.Write(", Namespace=");
                 ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace);
             }
             writer.WriteLine(")]");
         }
         CodeIdentifiers classes = new CodeIdentifiers();
         classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter");
         classes.AddUnique("XmlSerializationReader", "XmlSerializationReader");
         string str2 = null;
         if (((types != null) && (types.Length == 1)) && (types[0] != null))
         {
             str2 = CodeIdentifier.MakeValid(types[0].Name);
             if (types[0].IsArray)
             {
                 str2 = str2 + "Array";
             }
         }
         writer.WriteLine("namespace Microsoft.Xml.Serialization.GeneratedAssembly {");
         writer.Indent++;
         writer.WriteLine();
         string identifier = "XmlSerializationWriter" + str2;
         identifier = classes.AddUnique(identifier, identifier);
         XmlSerializationWriterCodeGen gen = new XmlSerializationWriterCodeGen(writer, array, "public", identifier);
         gen.GenerateBegin();
         string[] writerMethods = new string[xmlMappings.Length];
         for (int k = 0; k < xmlMappings.Length; k++)
         {
             writerMethods[k] = gen.GenerateElement(xmlMappings[k]);
         }
         gen.GenerateEnd();
         writer.WriteLine();
         string str4 = "XmlSerializationReader" + str2;
         str4 = classes.AddUnique(str4, str4);
         XmlSerializationReaderCodeGen gen2 = new XmlSerializationReaderCodeGen(writer, array, "public", str4);
         gen2.GenerateBegin();
         string[] methods = new string[xmlMappings.Length];
         for (int m = 0; m < xmlMappings.Length; m++)
         {
             methods[m] = gen2.GenerateElement(xmlMappings[m]);
         }
         gen2.GenerateEnd(methods, xmlMappings, types);
         string baseSerializer = gen2.GenerateBaseSerializer("XmlSerializer1", str4, identifier, classes);
         Hashtable serializers = new Hashtable();
         for (int n = 0; n < xmlMappings.Length; n++)
         {
             if (serializers[xmlMappings[n].Key] == null)
             {
                 serializers[xmlMappings[n].Key] = gen2.GenerateTypedSerializer(methods[n], writerMethods[n], xmlMappings[n], classes, baseSerializer, str4, identifier);
             }
         }
         gen2.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, str4, methods, identifier, writerMethods, serializers);
         writer.Indent--;
         writer.WriteLine("}");
         assembly3 = compiler.Compile(assembly, defaultNamespace, parameters, evidence);
     }
     finally
     {
         compiler.Close();
     }
     return assembly3;
 }