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;
                        }

                        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(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();
            }
        }
        internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, CompilerParameters parameters, Assembly assembly, Hashtable assemblies)
        {
            FileIOPermission.Assert();
            for (int i = 0; i < xmlMappings.Length; i++)
            {
                xmlMappings[i].CheckShallow();
            }
            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("#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();
            }
        }
Esempio n. 3
0
        ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns)
        {
            if (!(type.DerivedFrom.Name == Soap.Array && type.DerivedFrom.Namespace == Soap.Encoding))
            {
                return(null);
            }

            // the type should be a XmlSchemaComplexType
            XmlSchemaContentModel model = ((XmlSchemaComplexType)type).ContentModel;

            // the Content  should be an restriction
            if (!(model.Content is XmlSchemaComplexContentRestriction))
            {
                return(null);
            }

            ArrayMapping arrayMapping = new ArrayMapping();

            XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)model.Content;

            for (int i = 0; i < restriction.Attributes.Count; i++)
            {
                XmlSchemaAttribute attribute = restriction.Attributes[i] as XmlSchemaAttribute;
                if (attribute != null && attribute.RefName.Name == Soap.ArrayType && attribute.RefName.Namespace == Soap.Encoding)
                {
                    // read the value of the wsdl:arrayType attribute
                    string arrayType = null;

                    if (attribute.UnhandledAttributes != null)
                    {
                        foreach (XmlAttribute a in attribute.UnhandledAttributes)
                        {
                            if (a.LocalName == Wsdl.ArrayType && a.NamespaceURI == Wsdl.Namespace)
                            {
                                arrayType = a.Value;
                                break;
                            }
                        }
                    }
                    if (arrayType != null)
                    {
                        string           dims;
                        XmlQualifiedName typeName = TypeScope.ParseWsdlArrayType(arrayType, out dims, attribute);

                        TypeMapping mapping;
                        TypeDesc    td = scope.GetTypeDesc(typeName);
                        if (td != null && td.IsPrimitive)
                        {
                            mapping          = new PrimitiveMapping();
                            mapping.TypeDesc = td;
                            mapping.TypeName = td.DataType.Name;
                        }
                        else
                        {
                            mapping = ImportType(typeName, false);
                        }
                        ElementAccessor itemAccessor = new ElementAccessor();
                        itemAccessor.IsSoap     = true;
                        itemAccessor.Name       = typeName.Name;
                        itemAccessor.Namespace  = ns;
                        itemAccessor.Mapping    = mapping;
                        itemAccessor.IsNullable = true;
                        itemAccessor.Form       = XmlSchemaForm.None;

                        arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                        arrayMapping.TypeDesc = itemAccessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                        arrayMapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeName);

                        return(arrayMapping);
                    }
                }
            }

            XmlSchemaParticle particle = restriction.Particle;

            if (particle is XmlSchemaAll || particle is XmlSchemaSequence)
            {
                XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle;
                if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaElement))
                {
                    return(null);
                }
                XmlSchemaElement itemElement = (XmlSchemaElement)group.Items[0];
                if (!itemElement.IsMultipleOccurrence)
                {
                    return(null);
                }
                ElementAccessor itemAccessor = ImportElement(itemElement, ns);
                arrayMapping.Elements = new ElementAccessor[] { itemAccessor };
                arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc();
            }
            else
            {
                return(null);
            }
            return(arrayMapping);
        }
Esempio n. 4
0
 internal static string MakeFieldName(string name)
 {
     return(CodeIdentifier.MakeCamel(name) + "Field");
 }
Esempio n. 5
0
 internal string GenerateUniqueTypeName(string typeName)
 {
     typeName = CodeIdentifier.MakeValid(typeName);
     return(TypeIdentifiers.AddUnique(typeName, typeName));
 }
 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;
 }
        internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
        {
            string name = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));

            name = classes.AddUnique(name + "Serializer", mapping);
            this.writer.WriteLine();
            this.writer.Write("public sealed class ");
            this.writer.Write(CodeIdentifier.GetCSharpName(name));
            this.writer.Write(" : ");
            this.writer.Write(baseSerializer);
            this.writer.WriteLine(" {");
            this.writer.Indent++;
            this.writer.WriteLine();
            this.writer.Write("public override ");
            this.writer.Write(typeof(bool).FullName);
            this.writer.Write(" CanDeserialize(");
            this.writer.Write(typeof(XmlReader).FullName);
            this.writer.WriteLine(" xmlReader) {");
            this.writer.Indent++;
            if (mapping.Accessor.Any)
            {
                this.writer.WriteLine("return true;");
            }
            else
            {
                this.writer.Write("return xmlReader.IsStartElement(");
                this.WriteQuotedCSharpString(mapping.Accessor.Name);
                this.writer.Write(", ");
                this.WriteQuotedCSharpString(mapping.Accessor.Namespace);
                this.writer.WriteLine(");");
            }
            this.writer.Indent--;
            this.writer.WriteLine("}");
            if (writeMethod != null)
            {
                this.writer.WriteLine();
                this.writer.Write("protected override void Serialize(object objectToSerialize, ");
                this.writer.Write(typeof(XmlSerializationWriter).FullName);
                this.writer.WriteLine(" writer) {");
                this.writer.Indent++;
                this.writer.Write("((");
                this.writer.Write(writerClass);
                this.writer.Write(")writer).");
                this.writer.Write(writeMethod);
                this.writer.Write("(");
                if (mapping is XmlMembersMapping)
                {
                    this.writer.Write("(object[])");
                }
                this.writer.WriteLine("objectToSerialize);");
                this.writer.Indent--;
                this.writer.WriteLine("}");
            }
            if (readMethod != null)
            {
                this.writer.WriteLine();
                this.writer.Write("protected override object Deserialize(");
                this.writer.Write(typeof(XmlSerializationReader).FullName);
                this.writer.WriteLine(" reader) {");
                this.writer.Indent++;
                this.writer.Write("return ((");
                this.writer.Write(readerClass);
                this.writer.Write(")reader).");
                this.writer.Write(readMethod);
                this.writer.WriteLine("();");
                this.writer.Indent--;
                this.writer.WriteLine("}");
            }
            this.writer.Indent--;
            this.writer.WriteLine("}");
            return(name);
        }
Esempio n. 8
0
        public static TypeData GetTypeData(Type runtimeType, string xmlDataType)
        {
            Type type             = runtimeType;
            bool nullableOverride = false;

#if NET_2_0
            // Nullable<T> is serialized as T
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                nullableOverride = true;
                type             = type.GetGenericArguments() [0];

                TypeData pt = GetTypeData(type);                  // beware this recursive call btw ...
                if (pt != null)
                {
                    TypeData tt = (TypeData)nullableTypes [pt.XmlType];
#if TARGET_JVM
                    if (tt == null)
                    {
                        tt = (TypeData)AppDomain_nullableTypes [pt.XmlType];
                    }
#endif
                    if (tt == null)
                    {
                        tt            = new TypeData(type, pt.XmlType, false);
                        tt.IsNullable = true;
#if TARGET_JVM
                        AppDomain_nullableTypes [pt.XmlType] = tt;
#else
                        nullableTypes [pt.XmlType] = tt;
#endif
                    }
                    return(tt);
                }
            }
#endif

            if ((xmlDataType != null) && (xmlDataType.Length != 0))
            {
                // If the type is an array, xmlDataType specifies the type for the array elements,
                // not for the whole array. The exception is base64Binary, since it is a byte[],
                // that's why the following check is needed.
                TypeData at = GetPrimitiveTypeData(xmlDataType);
                if (type.IsArray && type != at.Type)
                {
                    TypeData tt = (TypeData)primitiveArrayTypes [xmlDataType];
                    if (tt != null)
                    {
                        return(tt);
                    }
                    if (at.Type == type.GetElementType())
                    {
                        tt = new TypeData(type, GetArrayName(at.XmlType), false);
                        primitiveArrayTypes [xmlDataType] = tt;
                        return(tt);
                    }
                    else
                    {
                        throw new InvalidOperationException("Cannot convert values of type '" + type.GetElementType() + "' to '" + xmlDataType + "'");
                    }
                }
                return(at);
            }

            TypeData typeData = nameCache[runtimeType] as TypeData;
            if (typeData != null)
            {
                return(typeData);
            }

#if TARGET_JVM
            Hashtable dynamicCache = AppDomain_nameCache;
            typeData = dynamicCache[runtimeType] as TypeData;
            if (typeData != null)
            {
                return(typeData);
            }
#endif

            string name;
            if (type.IsArray)
            {
                string sufix = GetTypeData(type.GetElementType()).XmlType;
                name = GetArrayName(sufix);
            }
#if NET_2_0
            else if (type.IsGenericType && !type.IsGenericTypeDefinition)
            {
                name = XmlConvert.EncodeLocalName(type.Name.Substring(0, type.Name.IndexOf('`'))) + "Of";
                foreach (Type garg in type.GetGenericArguments())
                {
                    name += garg.IsArray || garg.IsGenericType ?
                            GetTypeData(garg).XmlType :
                            CodeIdentifier.MakePascal(XmlConvert.EncodeLocalName(garg.Name));
                }
            }
#endif
            else
            {
                name = XmlConvert.EncodeLocalName(type.Name);
            }

            typeData = new TypeData(type, name, false);
            if (nullableOverride)
            {
                typeData.IsNullable = true;
            }
#if TARGET_JVM
            dynamicCache[runtimeType] = typeData;
#else
            nameCache[runtimeType] = typeData;
#endif
            return(typeData);
        }
Esempio n. 9
0
        void AddDefaultValueAttribute(CodeMemberField field, CodeAttributeDeclarationCollection metadata, object value, TypeMapping mapping)
        {
            #if DEBUG
            // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
            if (!(mapping is PrimitiveMapping))
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value is invalid for " + mapping.GetType().Name));
            }
            else if (mapping.IsList)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value is invalid for " + mapping.GetType().Name));
            }
            #endif

            if (value == null)
            {
                return;
            }

            CodeExpression          valueExpression = null;
            CodeExpression          initExpression  = null;
            CodeExpression          typeofValue     = null;
            string                  typeName        = mapping.TypeDesc.FullName;
            Type                    type            = value.GetType();
            CodeAttributeArgument[] arguments       = null;

            if (mapping is EnumMapping)
            {
                #if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (value.GetType() != typeof(string))
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Invalid enumeration type " + value.GetType().Name));
                }
                #endif

                if (((EnumMapping)mapping).IsFlags)
                {
                    string[] values = ((string)value).Split(null);
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i].Length == 0)
                        {
                            continue;
                        }
                        CodeExpression enumRef = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeName), values[i]);
                        if (valueExpression != null)
                        {
                            valueExpression = new CodeBinaryOperatorExpression(valueExpression, CodeBinaryOperatorType.BitwiseOr, enumRef);
                        }
                        else
                        {
                            valueExpression = enumRef;
                        }
                    }
                }
                else
                {
                    valueExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeName), (string)value);
                }
                initExpression = valueExpression;
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(bool) ||
                     type == typeof(Int32) ||
                     type == typeof(string) ||
                     type == typeof(double))
            {
                initExpression = valueExpression = new CodePrimitiveExpression(value);
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(Int16) ||
                     type == typeof(Int64) ||
                     type == typeof(float) ||
                     type == typeof(byte) ||
                     type == typeof(decimal))
            {
                valueExpression = new CodePrimitiveExpression(value.ToString());
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(sbyte) ||
                     type == typeof(UInt16) ||
                     type == typeof(UInt32) ||
                     type == typeof(UInt64))
            {
                // need to promote the non-CLS complient types

                value = PromoteType(type, value);

                valueExpression = new CodePrimitiveExpression(value.ToString());
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(DateTime))
            {
                DateTime dt = (DateTime)value;
                string   dtString;
                long     ticks;
                if (mapping.TypeDesc.FormatterName == "Date")
                {
                    dtString = XmlCustomFormatter.FromDate(dt);
                    ticks    = (new DateTime(dt.Year, dt.Month, dt.Day)).Ticks;
                }
                else if (mapping.TypeDesc.FormatterName == "Time")
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                else
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                valueExpression = new CodePrimitiveExpression(dtString);
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] { new CodePrimitiveExpression(ticks) });
            }
            if (arguments != null)
            {
                if (field != null)
                {
                    field.InitExpression = initExpression;
                }
                AddCustomAttribute(metadata, typeof(DefaultValueAttribute), arguments);
            }
        }
Esempio n. 10
0
        private void InternalLoad(Type elementType, bool asAddress = false)
        {
            Match match = s_regex.Match(Arg);

            if (match.Success)
            {
                object varA    = ILG.GetVariable(match.Groups["a"].Value);
                Type   varType = ILG.GetVariableType(varA);
                object varIA   = ILG.GetVariable(match.Groups["ia"].Value);
                if (varType.IsArray)
                {
                    ILG.Load(varA);
                    ILG.Load(varIA);
                    Type eType = varType.GetElementType();
                    if (CodeGenerator.IsNullableGenericType(eType))
                    {
                        ILG.Ldelema(eType);
                        ConvertNullableValue(eType, elementType);
                    }
                    else
                    {
                        if (eType.GetTypeInfo().IsValueType)
                        {
                            ILG.Ldelema(eType);
                            if (!asAddress)
                            {
                                ILG.Ldobj(eType);
                            }
                        }
                        else
                        {
                            ILG.Ldelem(eType);
                        }
                        if (elementType != null)
                        {
                            ILG.ConvertValue(eType, elementType);
                        }
                    }
                }
                else
                {
                    ILG.Load(varA);
                    ILG.Load(varIA);
                    MethodInfo get_Item = varType.GetMethod(
                        "get_Item",
                        CodeGenerator.InstanceBindingFlags,
                        new Type[] { typeof(Int32) }
                        );
                    Debug.Assert(get_Item != null);
                    ILG.Call(get_Item);
                    Type eType = get_Item.ReturnType;
                    if (CodeGenerator.IsNullableGenericType(eType))
                    {
                        LocalBuilder localTmp = ILG.GetTempLocal(eType);
                        ILG.Stloc(localTmp);
                        ILG.Ldloca(localTmp);
                        ConvertNullableValue(eType, elementType);
                    }
                    else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType)))
                    {
                        throw new InvalidOperationException(SR.Format(SR.IsNotAssignableFrom, eType.GetTypeInfo().AssemblyQualifiedName, elementType.GetTypeInfo().AssemblyQualifiedName));
                    }
                    else
                    {
                        Convert(eType, elementType, asAddress);
                    }
                }
            }
            else if (Source == "null")
            {
                ILG.Load(null);
            }
            else
            {
                object var;
                Type   varType;
                if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null)
                {
                    var     = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg);
                    varType = ILG.GetVariableType(var);
                    if (varType.GetTypeInfo().IsValueType)
                    {
                        ILG.LoadAddress(var);
                    }
                    else
                    {
                        ILG.Load(var);
                    }
                }
                else
                {
                    var     = ILG.GetVariable(Arg);
                    varType = ILG.GetVariableType(var);

                    if (CodeGenerator.IsNullableGenericType(varType) &&
                        varType.GetGenericArguments()[0] == elementType)
                    {
                        ILG.LoadAddress(var);
                        ConvertNullableValue(varType, elementType);
                    }
                    else
                    {
                        if (asAddress)
                        {
                            ILG.LoadAddress(var);
                        }
                        else
                        {
                            ILG.Load(var);
                        }
                    }
                }

                if (MemberInfo != null)
                {
                    Type memberType = (MemberInfo is FieldInfo) ?
                                      ((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType;
                    if (CodeGenerator.IsNullableGenericType(memberType))
                    {
                        ILG.LoadMemberAddress(MemberInfo);
                        ConvertNullableValue(memberType, elementType);
                    }
                    else
                    {
                        ILG.LoadMember(MemberInfo);
                        Convert(memberType, elementType, asAddress);
                    }
                }
                else
                {
                    match = s_regex2.Match(Source);
                    if (match.Success)
                    {
                        Debug.Assert(match.Groups["arg"].Value == Arg);
                        Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type));
                        if (asAddress)
                        {
                            ILG.ConvertAddress(varType, Type);
                        }
                        else
                        {
                            ILG.ConvertValue(varType, Type);
                        }
                        varType = Type;
                    }
                    Convert(varType, elementType, asAddress);
                }
            }
        }
Esempio n. 11
0
        private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
        {
            TypeDesc  typeDesc = null;
            TypeKind  kind;
            Type      arrayElementType = null;
            Type      baseType         = null;
            TypeFlags flags            = 0;
            Exception exception        = null;

            if (!type.GetTypeInfo().IsVisible)
            {
                flags    |= TypeFlags.Unsupported;
                exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName));
            }
            else if (directReference && (type.GetTypeInfo().IsAbstract&& type.GetTypeInfo().IsSealed))
            {
                flags    |= TypeFlags.Unsupported;
                exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName));
            }

            if (!type.GetTypeInfo().IsValueType)
            {
                flags |= TypeFlags.Reference;
            }

            if (type == typeof(object))
            {
                kind   = TypeKind.Root;
                flags |= TypeFlags.HasDefaultConstructor;
            }
            else if (type == typeof(ValueType))
            {
                kind   = TypeKind.Enum;
                flags |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
                }
            }
            else if (type == typeof(void))
            {
                kind = TypeKind.Void;
            }
            else if (typeof(IXmlSerializable).IsAssignableFrom(type))
            {
                kind   = TypeKind.Serializable;
                flags |= TypeFlags.Special | TypeFlags.CanBeElementValue;
                flags |= GetConstructorFlags(type, ref exception);
            }
            else if (type.IsArray)
            {
                kind = TypeKind.Array;
                if (type.GetArrayRank() > 1)
                {
                    flags |= TypeFlags.Unsupported;
                    if (exception == null)
                    {
                        exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
                    }
                }
                arrayElementType = type.GetElementType();
                flags           |= TypeFlags.HasDefaultConstructor;
            }
            else if (typeof(ICollection).IsAssignableFrom(type))
            {
                kind             = TypeKind.Collection;
                arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name);
                flags           |= GetConstructorFlags(type, ref exception);
            }
            else if (type == typeof(XmlQualifiedName))
            {
                kind = TypeKind.Primitive;
            }
            else if (type.GetTypeInfo().IsPrimitive)
            {
                kind   = TypeKind.Primitive;
                flags |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
                }
            }
            else if (type.GetTypeInfo().IsEnum)
            {
                kind = TypeKind.Enum;
            }
            else if (type.GetTypeInfo().IsValueType)
            {
                kind = TypeKind.Struct;
                if (IsOptionalValue(type))
                {
                    baseType = type.GetGenericArguments()[0];
                    flags   |= TypeFlags.OptionalValue;
                }
                else
                {
                    baseType = type.GetTypeInfo().BaseType;
                }
                if (type.GetTypeInfo().IsAbstract)
                {
                    flags |= TypeFlags.Abstract;
                }
            }
            else if (type.GetTypeInfo().IsClass)
            {
                {
                    kind     = TypeKind.Class;
                    baseType = type.GetTypeInfo().BaseType;
                    if (type.GetTypeInfo().IsAbstract)
                    {
                        flags |= TypeFlags.Abstract;
                    }
                }
            }
            else if (type.GetTypeInfo().IsInterface)
            {
                kind   = TypeKind.Void;
                flags |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    if (memberInfo == null)
                    {
                        exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName));
                    }
                    else
                    {
                        exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName));
                    }
                }
            }
            else
            {
                kind   = TypeKind.Void;
                flags |= TypeFlags.Unsupported;
                if (exception == null)
                {
                    exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
                }
            }

            // check to see if the type has public default constructor for classes
            if (kind == TypeKind.Class && !type.GetTypeInfo().IsAbstract)
            {
                flags |= GetConstructorFlags(type, ref exception);
            }
            // check if a struct-like type is enumerable
            if (kind == TypeKind.Struct || kind == TypeKind.Class)
            {
                if (typeof(IEnumerable).IsAssignableFrom(type))
                {
                    arrayElementType = GetEnumeratorElementType(type, ref flags);
                    kind             = TypeKind.Enumerable;

                    // GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property,
                    // we need to check the MoveNext() and ctor methods for the security attribues
                    flags |= GetConstructorFlags(type, ref exception);
                }
            }
            typeDesc           = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null);
            typeDesc.Exception = exception;

            if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable))
            {
                typeDesc.CheckNeedConstructor();
            }

            if (typeDesc.IsUnsupported)
            {
                // return right away, do not check anything else
                return(typeDesc);
            }
            _typeDescs.Add(type, typeDesc);

            if (arrayElementType != null)
            {
                TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false);
                // explicitly disallow read-only elements, even if they are collections
                if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive)
                {
                    td.CheckNeedConstructor();
                }
                typeDesc.ArrayElementTypeDesc = td;
            }
            if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType))
            {
                typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false);
            }
            return(typeDesc);
        }
        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);
        }
        /// <summary>Produces a Pascal-case string from an input string. </summary>
        /// <returns>A Pascal-case version of the parameter string.</returns>
        /// <param name="identifier">The name of a code entity, such as a method parameter, typically taken from an XML element or attribute name.</param>
        public static string MakePascal(string identifier)
        {
            string text = CodeIdentifier.MakeValid(identifier);

            return(char.ToUpper(text[0], CultureInfo.InvariantCulture) + text.Substring(1));
        }
Esempio n. 14
0
        private ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns)
        {
            ArrayMapping mapping;

            if ((type.Name == "Array") && (ns == "http://schemas.xmlsoap.org/soap/encoding/"))
            {
                mapping = new ArrayMapping();
                TypeMapping     rootMapping = base.GetRootMapping();
                ElementAccessor accessor    = new ElementAccessor {
                    IsSoap     = true,
                    Name       = "anyType",
                    Namespace  = ns,
                    Mapping    = rootMapping,
                    IsNullable = true,
                    Form       = XmlSchemaForm.None
                };
                mapping.Elements = new ElementAccessor[] { accessor };
                mapping.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc();
                mapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(accessor.Mapping.TypeName);
                return(mapping);
            }
            if ((type.DerivedFrom.Name != "Array") || (type.DerivedFrom.Namespace != "http://schemas.xmlsoap.org/soap/encoding/"))
            {
                return(null);
            }
            XmlSchemaContentModel contentModel = ((XmlSchemaComplexType)type).ContentModel;

            if (!(contentModel.Content is XmlSchemaComplexContentRestriction))
            {
                return(null);
            }
            mapping = new ArrayMapping();
            XmlSchemaComplexContentRestriction content = (XmlSchemaComplexContentRestriction)contentModel.Content;

            for (int i = 0; i < content.Attributes.Count; i++)
            {
                XmlSchemaAttribute parent = content.Attributes[i] as XmlSchemaAttribute;
                if (((parent != null) && (parent.RefName.Name == "arrayType")) && (parent.RefName.Namespace == "http://schemas.xmlsoap.org/soap/encoding/"))
                {
                    string str = null;
                    if (parent.UnhandledAttributes != null)
                    {
                        foreach (XmlAttribute attribute2 in parent.UnhandledAttributes)
                        {
                            if ((attribute2.LocalName == "arrayType") && (attribute2.NamespaceURI == "http://schemas.xmlsoap.org/wsdl/"))
                            {
                                str = attribute2.Value;
                                break;
                            }
                        }
                    }
                    if (str != null)
                    {
                        string           str2;
                        TypeMapping      mapping3;
                        XmlQualifiedName name     = TypeScope.ParseWsdlArrayType(str, out str2, parent);
                        TypeDesc         typeDesc = base.Scope.GetTypeDesc(name.Name, name.Namespace);
                        if ((typeDesc != null) && typeDesc.IsPrimitive)
                        {
                            mapping3 = new PrimitiveMapping {
                                TypeDesc = typeDesc,
                                TypeName = typeDesc.DataType.Name
                            };
                        }
                        else
                        {
                            mapping3 = this.ImportType(name, false);
                        }
                        ElementAccessor accessor2 = new ElementAccessor {
                            IsSoap     = true,
                            Name       = name.Name,
                            Namespace  = ns,
                            Mapping    = mapping3,
                            IsNullable = true,
                            Form       = XmlSchemaForm.None
                        };
                        mapping.Elements = new ElementAccessor[] { accessor2 };
                        mapping.TypeDesc = accessor2.Mapping.TypeDesc.CreateArrayTypeDesc();
                        mapping.TypeName = "ArrayOf" + CodeIdentifier.MakePascal(accessor2.Mapping.TypeName);
                        return(mapping);
                    }
                }
            }
            XmlSchemaParticle particle = content.Particle;

            if (!(particle is XmlSchemaAll) && !(particle is XmlSchemaSequence))
            {
                return(null);
            }
            XmlSchemaGroupBase base2 = (XmlSchemaGroupBase)particle;

            if ((base2.Items.Count != 1) || !(base2.Items[0] is XmlSchemaElement))
            {
                return(null);
            }
            XmlSchemaElement element = (XmlSchemaElement)base2.Items[0];

            if (!element.IsMultipleOccurrence)
            {
                return(null);
            }
            ElementAccessor accessor3 = this.ImportElement(element, ns);

            mapping.Elements = new ElementAccessor[] { accessor3 };
            mapping.TypeDesc = accessor3.Mapping.TypeDesc.CreateArrayTypeDesc();
            return(mapping);
        }
        TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList)
        {
            TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];

            if (mapping != null)
            {
                return(mapping);
            }

            XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
            TypeDesc            sourceTypeDesc = Scope.GetTypeDesc(sourceDataType);

            if (sourceTypeDesc != null && sourceTypeDesc != Scope.GetTypeDesc(typeof(string)))
            {
                return(ImportPrimitiveDataType(dataType));
            }
            identifier = Accessor.UnescapeName(identifier);
            string      typeName    = GenerateUniqueTypeName(identifier);
            EnumMapping enumMapping = new EnumMapping();

            enumMapping.IsReference = Schemas.IsReference(dataType);
            enumMapping.TypeDesc    = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName    = identifier;
            enumMapping.Namespace   = typeNs;
            enumMapping.IsFlags     = isList;
            CodeIdentifiers constants = new CodeIdentifiers();

            if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));
            }

            XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;

            for (int i = 0; i < restriction.Facets.Count; i++)
            {
                object facet = restriction.Facets[i];
                if (!(facet is XmlSchemaEnumerationFacet))
                {
                    continue;
                }
                XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                ConstantMapping           constant    = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                constant.Name    = constants.AddUnique(constantName, constant);
                constant.XmlName = enumeration.Value;
                constant.Value   = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            if (isList && enumMapping.Constants.Length > 63)
            {
                // if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
                mapping          = new PrimitiveMapping();
                mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
                mapping.TypeName = mapping.TypeDesc.DataType.Name;
                ImportedMappings.Add(dataType, mapping);
                return(mapping);
            }
            ImportedMappings.Add(dataType, enumMapping);
            Scope.AddTypeMapping(enumMapping);
            return(enumMapping);
        }
Esempio n. 16
0
        internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
        {
            string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));

            serializerName = classes.AddUnique(serializerName + "Serializer", mapping);

            TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
                _moduleBuilder,
                CodeIdentifier.GetCSharpName(serializerName),
                TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                CreatedTypes[baseSerializer],
                Array.Empty <Type>()
                );

            ilg = new CodeGenerator(typedSerializerTypeBuilder);
            ilg.BeginMethod(
                typeof(Boolean),
                "CanDeserialize",
                new Type[] { typeof(XmlReader) },
                new string[] { "xmlReader" },
                CodeGenerator.PublicOverrideMethodAttributes
                );

            if (mapping.Accessor.Any)
            {
                ilg.Ldc(true);
                ilg.Stloc(ilg.ReturnLocal);
                ilg.Br(ilg.ReturnLabel);
            }
            else
            {
                MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod(
                    "IsStartElement",
                    CodeGenerator.InstanceBindingFlags,
                    new Type[] { typeof(String), typeof(String) }
                    );
                ilg.Ldarg(ilg.GetArg("xmlReader"));
                ilg.Ldstr(GetCSharpString(mapping.Accessor.Name));
                ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace));
                ilg.Call(XmlReader_IsStartElement);
                ilg.Stloc(ilg.ReturnLocal);
                ilg.Br(ilg.ReturnLabel);
            }
            ilg.MarkLabel(ilg.ReturnLabel);
            ilg.Ldloc(ilg.ReturnLocal);
            ilg.EndMethod();

            if (writeMethod != null)
            {
                ilg = new CodeGenerator(typedSerializerTypeBuilder);
                ilg.BeginMethod(
                    typeof(void),
                    "Serialize",
                    new Type[] { typeof(object), typeof(XmlSerializationWriter) },
                    new string[] { "objectToSerialize", "writer" },
                    CodeGenerator.ProtectedOverrideMethodAttributes);
                MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod(
                    writeMethod,
                    CodeGenerator.InstanceBindingFlags,
                    new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) }
                    );
                ilg.Ldarg("writer");
                ilg.Castclass(CreatedTypes[writerClass]);
                ilg.Ldarg("objectToSerialize");
                if (mapping is XmlMembersMapping)
                {
                    ilg.ConvertValue(typeof(object), typeof(object[]));
                }
                ilg.Call(writerType_writeMethod);
                ilg.EndMethod();
            }
            if (readMethod != null)
            {
                ilg = new CodeGenerator(typedSerializerTypeBuilder);
                ilg.BeginMethod(
                    typeof(object),
                    "Deserialize",
                    new Type[] { typeof(XmlSerializationReader) },
                    new string[] { "reader" },
                    CodeGenerator.ProtectedOverrideMethodAttributes);
                MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod(
                    readMethod,
                    CodeGenerator.InstanceBindingFlags,
                    Array.Empty <Type>()
                    );
                ilg.Ldarg("reader");
                ilg.Castclass(CreatedTypes[readerClass]);
                ilg.Call(readerType_readMethod);
                ilg.EndMethod();
            }
            typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes);
            Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType();

            CreatedTypes.Add(typedSerializerType.Name, typedSerializerType);

            return(typedSerializerType.Name);
        }
Esempio n. 17
0
        private void SetArrayMappingType(ArrayMapping mapping)
        {
            string      typeName;
            string      str2;
            TypeMapping mapping2;
            bool        flag = false;

            if (mapping.Elements.Length == 1)
            {
                mapping2 = mapping.Elements[0].Mapping;
            }
            else
            {
                mapping2 = null;
            }
            if (mapping2 is EnumMapping)
            {
                str2     = mapping2.Namespace;
                typeName = mapping2.TypeName;
            }
            else if (mapping2 is PrimitiveMapping)
            {
                str2     = mapping2.TypeDesc.IsXsdType ? "http://www.w3.org/2001/XMLSchema" : "http://microsoft.com/wsdl/types/";
                typeName = mapping2.TypeDesc.DataType.Name;
                flag     = true;
            }
            else if (mapping2 is StructMapping)
            {
                if (mapping2.TypeDesc.IsRoot)
                {
                    str2     = "http://www.w3.org/2001/XMLSchema";
                    typeName = "anyType";
                    flag     = true;
                }
                else
                {
                    str2     = mapping2.Namespace;
                    typeName = mapping2.TypeName;
                }
            }
            else
            {
                if (!(mapping2 is ArrayMapping))
                {
                    throw new InvalidOperationException(Res.GetString("XmlInvalidSoapArray", new object[] { mapping.TypeDesc.FullName }));
                }
                str2     = mapping2.Namespace;
                typeName = mapping2.TypeName;
            }
            typeName = CodeIdentifier.MakePascal(typeName);
            string      str3     = "ArrayOf" + typeName;
            string      str4     = flag ? this.defaultNs : str2;
            int         num      = 1;
            TypeMapping mapping3 = (TypeMapping)this.types[str3, str4];

            while (mapping3 != null)
            {
                if (mapping3 is ArrayMapping)
                {
                    ArrayMapping mapping4 = (ArrayMapping)mapping3;
                    if (AccessorMapping.ElementsMatch(mapping4.Elements, mapping.Elements))
                    {
                        break;
                    }
                }
                str3     = typeName + num.ToString(CultureInfo.InvariantCulture);
                mapping3 = (TypeMapping)this.types[str3, str4];
                num++;
            }
            mapping.Namespace = str4;
            mapping.TypeName  = str3;
        }
Esempio n. 18
0
        internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace)
        {
            var scopeTable = new Dictionary <TypeScope, XmlMapping>();

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

            string          assemblyName    = "Microsoft.GeneratedCode";
            AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(assemblyName);

            // Add AssemblyVersion attribute to match parent accembly version
            if (types != null && types.Length > 0 && types[0] != null)
            {
                ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor(
                    new Type[] { typeof(String) }
                    );
                string assemblyVersion = types[0].Assembly.GetName().Version.ToString();
                assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion }));
            }
            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";
                }
            }

            ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName);

            string writerClass = "XmlSerializationWriter" + suffix;

            writerClass = classes.AddUnique(writerClass, writerClass);
            XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass);

            writerCodeGen.ModuleBuilder = moduleBuilder;

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

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

            string readerClass = "XmlSerializationReader" + suffix;

            readerClass = classes.AddUnique(readerClass, readerClass);
            XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass);

            readerCodeGen.ModuleBuilder = moduleBuilder;
            readerCodeGen.CreatedTypes.Add(writerType.Name, writerType);

            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 Dictionary <string, string>();

            for (int i = 0; i < xmlMappings.Length; i++)
            {
                if (!serializers.ContainsKey(xmlMappings[i].Key))
                {
                    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);

            return(writerType.Assembly);
        }
Esempio n. 19
0
        internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence)
        {
            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);

            string          assemblyName    = "Microsoft.GeneratedCode";
            AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(AppDomain.CurrentDomain, assemblyName);
            ConstructorInfo SecurityTransparentAttribute_ctor = typeof(SecurityTransparentAttribute).GetConstructor(
                CodeGenerator.InstanceBindingFlags,
                null,
                CodeGenerator.EmptyTypeArray,
                null
                );

            assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityTransparentAttribute_ctor, new Object[0]));
            ConstructorInfo AllowPartiallyTrustedCallersAttribute_ctor = typeof(AllowPartiallyTrustedCallersAttribute).GetConstructor(
                CodeGenerator.InstanceBindingFlags,
                null,
                CodeGenerator.EmptyTypeArray,
                null
                );

            assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AllowPartiallyTrustedCallersAttribute_ctor, new Object[0]));
            ConstructorInfo SecurityRulesAttribute_ctor = typeof(SecurityRulesAttribute).GetConstructor(
                CodeGenerator.InstanceBindingFlags,
                null,
                new Type[] { typeof(SecurityRuleSet) },
                null
                );

            assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityRulesAttribute_ctor, new Object[] { SecurityRuleSet.Level1 }));
            // Add AssemblyVersion attribute to match parent accembly version
            if (types != null && types.Length > 0 && types[0] != null)
            {
                ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor(
                    CodeGenerator.InstanceBindingFlags,
                    null,
                    new Type[] { typeof(String) },
                    null
                    );
                FileIOPermission.Assert();
                string assemblyVersion = types[0].Assembly.GetName().Version.ToString();
                FileIOPermission.RevertAssert();
                assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion }));
            }
            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";
                }
            }

            ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName);

            string writerClass = "XmlSerializationWriter" + suffix;

            writerClass = classes.AddUnique(writerClass, writerClass);
            XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass);

            writerCodeGen.ModuleBuilder = moduleBuilder;

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

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

            string readerClass = "XmlSerializationReader" + suffix;

            readerClass = classes.AddUnique(readerClass, readerClass);
            XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass);

            readerCodeGen.ModuleBuilder = moduleBuilder;
            readerCodeGen.CreatedTypes.Add(writerType.Name, writerType);

            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);

            if (DiagnosticsSwitches.KeepTempFiles.Enabled)
            {
                FileIOPermission.Assert();
                assemblyBuilder.Save(assemblyName + ".dll");
            }
            return(writerType.Assembly);
        }
Esempio n. 20
0
        // UNDONE Nullable
        private void SetArrayMappingType(ArrayMapping mapping)
        {
            bool useDefaultNs = false;

            string itemTypeName;
            string itemTypeNamespace;

            TypeMapping itemTypeMapping;

            if (mapping.Elements.Length == 1)
            {
                itemTypeMapping = mapping.Elements[0].Mapping;
            }
            else
            {
                itemTypeMapping = null;
            }

            if (itemTypeMapping is EnumMapping)
            {
                itemTypeNamespace = itemTypeMapping.Namespace;
                itemTypeName      = itemTypeMapping.TypeName;
            }
            else if (itemTypeMapping is PrimitiveMapping)
            {
                itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace;
                itemTypeName      = itemTypeMapping.TypeDesc.DataType.Name;
                useDefaultNs      = true;
            }
            else if (itemTypeMapping is StructMapping)
            {
                if (itemTypeMapping.TypeDesc.IsRoot)
                {
                    itemTypeNamespace = XmlSchema.Namespace;
                    itemTypeName      = Soap.UrType;
                    useDefaultNs      = true;
                }
                else
                {
                    itemTypeNamespace = itemTypeMapping.Namespace;
                    itemTypeName      = itemTypeMapping.TypeName;
                }
            }
            else if (itemTypeMapping is ArrayMapping)
            {
                itemTypeNamespace = itemTypeMapping.Namespace;
                itemTypeName      = itemTypeMapping.TypeName;
            }
            else
            {
                throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName));
            }

            itemTypeName = CodeIdentifier.MakePascal(itemTypeName);
            string      uniqueName      = "ArrayOf" + itemTypeName;
            string      ns              = useDefaultNs ? _defaultNs : itemTypeNamespace;
            int         i               = 1;
            TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns];

            while (existingMapping != null)
            {
                if (existingMapping is ArrayMapping)
                {
                    ArrayMapping arrayMapping = (ArrayMapping)existingMapping;
                    if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements))
                    {
                        break;
                    }
                }
                // need to re-name the mapping
                uniqueName      = itemTypeName + i.ToString(CultureInfo.InvariantCulture);
                existingMapping = (TypeMapping)_types[uniqueName, ns];
                i++;
            }
            mapping.Namespace = ns;
            mapping.TypeName  = uniqueName;
        }
Esempio n. 21
0
 private string GenerateVariableName(string prefix, string fullName)
 {
     this.nextReflectionVariableNumber++;
     return(string.Concat(new object[] { prefix, this.nextReflectionVariableNumber, "_", CodeIdentifier.MakeValidInternal(fullName.Replace('.', '_')) }));
 }