private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) { this.InitTheFirstTime(); string cSharpName = typeDesc.CSharpName; string str2 = (string)this.reflectionVariables[cSharpName]; if (str2 == null) { if (type.IsArray) { str2 = this.GenerateVariableName("array", typeDesc.CSharpName); TypeDesc arrayElementTypeDesc = typeDesc.ArrayElementTypeDesc; if (arrayElementTypeDesc.UseReflection) { string str3 = this.WriteTypeInfo(scope, arrayElementTypeDesc, scope.GetTypeFromTypeDesc(arrayElementTypeDesc)); this.writer.WriteLine("static " + typeof(Type).FullName + " " + str2 + " = " + str3 + ".MakeArrayType();"); } else { string str4 = this.WriteAssemblyInfo(type); this.writer.Write("static " + typeof(Type).FullName + " " + str2 + " = " + str4 + ".GetType("); this.WriteQuotedCSharpString(type.FullName); this.writer.WriteLine(");"); } } else { str2 = this.GenerateVariableName("type", typeDesc.CSharpName); Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType != null) { string str5 = this.WriteTypeInfo(scope, scope.GetTypeDesc(underlyingType), underlyingType); this.writer.WriteLine("static " + typeof(Type).FullName + " " + str2 + " = typeof(System.Nullable<>).MakeGenericType(new " + typeof(Type).FullName + "[] {" + str5 + "});"); } else { string str6 = this.WriteAssemblyInfo(type); this.writer.Write("static " + typeof(Type).FullName + " " + str2 + " = " + str6 + ".GetType("); this.WriteQuotedCSharpString(type.FullName); this.writer.WriteLine(");"); } } this.reflectionVariables.Add(cSharpName, str2); TypeMapping typeMappingFromTypeDesc = scope.GetTypeMappingFromTypeDesc(typeDesc); if (typeMappingFromTypeDesc != null) { this.WriteMappingInfo(typeMappingFromTypeDesc, str2, type); } if (typeDesc.IsCollection || typeDesc.IsEnumerable) { TypeDesc desc2 = typeDesc.ArrayElementTypeDesc; if (desc2.UseReflection) { this.WriteTypeInfo(scope, desc2, scope.GetTypeFromTypeDesc(desc2)); } this.WriteCollectionInfo(str2, typeDesc, type); } } return(str2); }
internal XmlMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) { _scope = scope; _accessor = accessor; _access = access; _shallow = scope == null; }
protected void WriteXmlAttribute(XmlNode node, object container) { XmlAttribute attr = node as XmlAttribute; if (attr == null) { throw new InvalidOperationException(SR.XmlNeedAttributeHere); } if (attr.Value != null) { if (attr.NamespaceURI == Wsdl.Namespace && attr.LocalName == Wsdl.ArrayType) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null); string value = FromXmlQualifiedName(qname, true) + dims; //<xsd:attribute xmlns:q3="s0" wsdl:arrayType="q3:FoosBase[]" xmlns:q4="http://schemas.xmlsoap.org/soap/encoding/" ref="q4:arrayType" /> WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value); } else { WriteAttribute(attr.Name, attr.NamespaceURI, attr.Value); } } }
internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) : base(scope, accessor, access) { MembersMapping mapping = (MembersMapping)accessor.Mapping !; StringBuilder key = new StringBuilder(); key.Append(':'); _mappings = new XmlMemberMapping[mapping.Members !.Length];
internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor) : base(scope) { this.accessor = accessor; MembersMapping mapping = (MembersMapping)accessor.Mapping; mappings = new XmlMemberMapping[mapping.Members.Length]; for (int i = 0; i < mappings.Length; i++) mappings[i] = new XmlMemberMapping(scope, mapping.Members[i]); }
public SoapReflectionImporter(SoapAttributeOverrides?attributeOverrides, string?defaultNamespace) { _defaultNs = defaultNamespace ?? string.Empty; _attributeOverrides = attributeOverrides ?? new SoapAttributeOverrides(); _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); }
internal XmlMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) { this.scope = scope; this.accessor = accessor; this.access = access; this.shallow = scope == null; }
void CheckScope(TypeScope scope) { if (this.scope == null) { this.scope = scope; } else if (this.scope != scope) { throw new InvalidOperationException(Res.GetString(Res.XmlMappingsScopeMismatch)); } }
/// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) { if (defaultNamespace == null) defaultNamespace = String.Empty; if (attributeOverrides == null) attributeOverrides = new SoapAttributeOverrides(); this.attributeOverrides = attributeOverrides; this.defaultNs = defaultNamespace; this.typeScope = new TypeScope(); this.modelScope = new ModelScope(this.typeScope); }
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; } } }
private void CheckScope(TypeScope scope) { if (_scope == null) { _scope = scope; } else if (_scope != scope) { throw new InvalidOperationException(SR.XmlMappingsScopeMismatch); } }
internal void WriteReflectionInit(TypeScope scope) { foreach (Type type in scope.Types) { TypeDesc typeDesc = scope.GetTypeDesc(type); if (typeDesc.UseReflection) { this.WriteTypeInfo(scope, typeDesc, type); } } }
internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor) : base(scope) { this.accessor = accessor; MembersMapping mapping = (MembersMapping)accessor.Mapping; mappings = new XmlMemberMapping[mapping.Members.Length]; for (int i = 0; i < mappings.Length; i++) { mappings[i] = new XmlMemberMapping(scope, mapping.Members[i]); } }
internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { this.writer = writer; this.scopes = scopes; if (scopes.Length > 0) { stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } this.raCodeGen = new ReflectionAwareCodeGen(writer); this.className = className; this.access = access; }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides, string defaultNamespace) { if (defaultNamespace == null) defaultNamespace = String.Empty; if (attributeOverrides == null) attributeOverrides = new XmlAttributeOverrides(); _attributeOverrides = attributeOverrides; _defaultNs = defaultNamespace; _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); }
internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { this.scopes = scopes; if (scopes.Length > 0) { stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } this.raCodeGen = new ReflectionAwareILGen(); this.className = className; System.Diagnostics.Debug.Assert(access == "public"); this.typeAttributes = TypeAttributes.Public; }
internal void CheckScope(TypeScope scope) { if (_scope == null) { _scope = scope; } else if (_scope != scope) { throw new InvalidOperationException(SR.XmlMappingsScopeMismatch); } }
/// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException1"]/*' /> protected Exception CreateUnknownTypeException(Type type) { if (typeof(IXmlSerializable).IsAssignableFrom(type)) { return(new InvalidOperationException(SR.Format(SR.XmlInvalidSerializable, type.FullName))); } TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); if (!typeDesc.IsStructLike) { return(new InvalidOperationException(SR.Format(SR.XmlInvalidUseOfType, type.FullName))); } return(new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, type.FullName))); }
internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) : base(scope, accessor, access) { MembersMapping mapping = (MembersMapping)accessor.Mapping; StringBuilder key = new StringBuilder(); key.Append(":"); mappings = new XmlMemberMapping[mapping.Members.Length]; for (int i = 0; i < mappings.Length; i++) { if (mapping.Members[i].TypeDesc.Type != null) { key.Append(GenerateKey(mapping.Members[i].TypeDesc.Type, null, null)); key.Append(":"); } mappings[i] = new XmlMemberMapping(mapping.Members[i]); } SetKeyInternal(key.ToString()); }
/// <include file='doc\SoapReflectionImporter.uex' path='docs/doc[@for="SoapReflectionImporter.SoapReflectionImporter3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) { if (defaultNamespace == null) { defaultNamespace = String.Empty; } if (attributeOverrides == null) { attributeOverrides = new SoapAttributeOverrides(); } _attributeOverrides = attributeOverrides; _defaultNs = defaultNamespace; _typeScope = new TypeScope(); _modelScope = new ModelScope(_typeScope); }
public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) { this.types = new System.Xml.Serialization.NameTable(); this.nullables = new System.Xml.Serialization.NameTable(); if (defaultNamespace == null) { defaultNamespace = string.Empty; } if (attributeOverrides == null) { attributeOverrides = new SoapAttributeOverrides(); } this.attributeOverrides = attributeOverrides; this.defaultNs = defaultNamespace; this.typeScope = new TypeScope(); this.modelScope = new ModelScope(this.typeScope); }
void ExportRootIfNecessary(TypeScope typeScope) { if (!needToExportRoot) { return; } foreach (TypeMapping mapping in typeScope.TypeMappings) { if (mapping is StructMapping && mapping.TypeDesc.IsRoot) { ExportDerivedMappings((StructMapping)mapping); } else if (mapping is ArrayMapping) { ExportArrayMapping((ArrayMapping)mapping, mapping.Namespace); } } }
internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) : base(scope, accessor, access) { MembersMapping mapping = (MembersMapping)accessor.Mapping; StringBuilder builder = new StringBuilder(); builder.Append(":"); this.mappings = new XmlMemberMapping[mapping.Members.Length]; for (int i = 0; i < this.mappings.Length; i++) { if (mapping.Members[i].TypeDesc.Type != null) { builder.Append(XmlMapping.GenerateKey(mapping.Members[i].TypeDesc.Type, null, null)); builder.Append(":"); } this.mappings[i] = new XmlMemberMapping(mapping.Members[i]); } base.SetKeyInternal(builder.ToString()); }
protected override void InitCallbacks() { TypeScope scope = _mapping.Scope; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping) && !mapping.TypeDesc.IsRoot) { AddWriteCallback( mapping.TypeDesc.Type, mapping.TypeName, mapping.Namespace, CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable) ); } } }
private string WriteDefaultIndexerInit(Type type, string escapedName, bool collectionUseReflection, bool elementUseReflection) { string s = this.GenerateVariableName("item", escapedName); PropertyInfo defaultIndexer = TypeScope.GetDefaultIndexer(type, null); this.writer.Write("static XSArrayInfo "); this.writer.Write(s); this.writer.Write("= new XSArrayInfo("); this.writer.Write(this.GetStringForTypeof(CodeIdentifier.GetCSharpName(type), collectionUseReflection)); this.writer.Write(".GetProperty("); this.WriteQuotedCSharpString(defaultIndexer.Name); this.writer.Write(","); this.writer.Write(this.GetStringForTypeof(CodeIdentifier.GetCSharpName(defaultIndexer.PropertyType), elementUseReflection)); this.writer.Write(",new "); this.writer.Write(typeof(Type[]).FullName); this.writer.WriteLine("{typeof(int)}));"); this.reflectionVariables.Add("0:" + escapedName, s); return(s); }
public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides, string defaultNamespace) { this.defaultAttributes = new XmlAttributes(); this.types = new System.Xml.Serialization.NameTable(); this.nullables = new System.Xml.Serialization.NameTable(); this.elements = new System.Xml.Serialization.NameTable(); this.anonymous = new Hashtable(); this.choiceNum = 1; if (defaultNamespace == null) { defaultNamespace = string.Empty; } if (attributeOverrides == null) { attributeOverrides = new XmlAttributeOverrides(); } this.attributeOverrides = attributeOverrides; this.defaultNs = defaultNamespace; this.typeScope = new TypeScope(); this.modelScope = new ModelScope(this.typeScope); }
// 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; }
internal XmlMemberMapping(TypeScope scope, MemberMapping mapping) { this.scope = scope; this.mapping = mapping; }
internal void WriteReflectionInit(TypeScope scope) { foreach (Type type in scope.Types) { TypeDesc typeDesc = scope.GetTypeDesc(type); } }
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].GetTypeInfo().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.GetTypeInfo().Assembly); }
public XmlSerializationReaderCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) : this(writer, scopes){ this.className = className; this.access = access; }
internal XmlTypeMapping(TypeScope scope, ElementAccessor accessor) : base(scope, accessor) { }
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(); } }
internal XmlTypeMapping(TypeScope scope, ElementAccessor accessor) : base(scope) { this.accessor = accessor; }
internal void WriteReflectionInit(TypeScope scope){ foreach (Type type in scope.Types) { TypeDesc typeDesc = scope.GetTypeDesc(type); if (typeDesc.UseReflection) WriteTypeInfo(scope, typeDesc, type); } }
private void ExportRootIfNecessary(TypeScope typeScope) { if (this.needToExportRoot) { foreach (TypeMapping mapping in typeScope.TypeMappings) { if ((mapping is StructMapping) && mapping.TypeDesc.IsRoot) { this.ExportDerivedMappings((StructMapping) mapping); } else if (mapping is ArrayMapping) { this.ExportArrayMapping((ArrayMapping) mapping, mapping.Namespace, null); } else if (mapping is SerializableMapping) { this.ExportSpecialMapping((SerializableMapping) mapping, mapping.Namespace, false, null); } } } }
private object WriteLiteralStructMethod(StructMapping structMapping, bool isNullable, bool checkType, string defaultNamespace) { XmlQualifiedName xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) { isNull = ReadNull(); } if (checkType) { if (structMapping.TypeDesc.IsRoot && isNull) { if (xsiType != null) { return(ReadTypedNull(xsiType)); } else { if (structMapping.TypeDesc.IsValueType) { return(ReflectionCreateObject(structMapping.TypeDesc.Type)); } else { return(null); } } } object o = null; if (xsiType == null || (!structMapping.TypeDesc.IsRoot && QNameEqual(xsiType, structMapping.TypeName, structMapping.Namespace, defaultNamespace))) { if (structMapping.TypeDesc.IsRoot) { return(ReadTypedPrimitive(new XmlQualifiedName(Soap.UrType, XmlSchemaConstants.Namespace))); } } else if (WriteDerivedTypes(out o, structMapping, xsiType, defaultNamespace, checkType, isNullable)) { return(o); } else if (structMapping.TypeDesc.IsRoot && WriteEnumAndArrayTypes(out o, structMapping, xsiType, defaultNamespace)) { return(o); } else { if (structMapping.TypeDesc.IsRoot) { return(ReadTypedPrimitive(xsiType)); } else { throw CreateUnknownTypeException(xsiType); } } } if (structMapping.TypeDesc.IsNullable && isNull) { return(null); } else if (structMapping.TypeDesc.IsAbstract) { throw CreateAbstractTypeException(structMapping.TypeName, structMapping.Namespace); } else { if (structMapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(structMapping.TypeDesc.Type)) { // #10589: To Support Serializing XmlSchemaObject throw new NotImplementedException("typeof(XmlSchemaObject)"); } object o = ReflectionCreateObject(structMapping.TypeDesc.Type); MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); MemberMapping anyText = null; MemberMapping anyElement = null; MemberMapping anyAttribute = null; Member anyElementMember = null; Member anyTextMember = null; bool isSequence = structMapping.HasExplicitSequence(); if (isSequence) { // #10586: Currently the reflection based method treat this kind of type as normal types. // But potentially we can do some optimization for types that have ordered properties. } var allMembersList = new List <Member>(mappings.Length); var allMemberMappingList = new List <MemberMapping>(mappings.Length); for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; if (mapping.Text != null) { anyText = mapping; } if (mapping.Attribute != null && mapping.Attribute.Any) { anyAttribute = mapping; } if (!isSequence) { // find anyElement if present. for (int j = 0; j < mapping.Elements.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { anyElement = mapping; break; } } } else if (mapping.IsParticle && !mapping.IsSequence) { StructMapping declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); } var member = new Member(mapping); if (mapping.TypeDesc.IsArrayLike) { if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.Collection = new CollectionMember(); } else if (!mapping.TypeDesc.IsArray) { } } allMemberMappingList.Add(mapping); allMembersList.Add(member); if (mapping == anyElement) { anyElementMember = member; } else if (mapping == anyText) { anyTextMember = member; } } var allMembers = allMembersList.ToArray(); var allMemberMappings = allMemberMappingList.ToArray(); Action <object> unknownNodeAction = (n) => UnknownNode(n); WriteAttributes(allMemberMappings, anyAttribute, unknownNodeAction, ref o); Reader.MoveToElement(); if (Reader.IsEmptyElement) { Reader.Skip(); return(o); } Reader.ReadStartElement(); bool IsSequenceAllMembers = IsSequence(allMembers); if (IsSequenceAllMembers) { // #10586: Currently the reflection based method treat this kind of type as normal types. // But potentially we can do some optimization for types that have ordered properties. } UnknownNodeAction unknownNode = UnknownNodeAction.ReadUnknownNode; WriteMembers(ref o, allMembers, unknownNode, unknownNode, anyElementMember, anyTextMember); ReadEndElement(); return(o); } }
internal void Depends(XmlSchemaObject item, ArrayList refs) { if (item == null || scope[item] != null) { return; } Type t = item.GetType(); if (typeof(XmlSchemaType).IsAssignableFrom(t)) { XmlQualifiedName baseName = XmlQualifiedName.Empty; XmlSchemaType baseType = null; XmlSchemaParticle particle = null; XmlSchemaObjectCollection attributes = null; if (item is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)item; if (ct.ContentModel != null) { XmlSchemaContent content = ct.ContentModel.Content; if (content is XmlSchemaComplexContentRestriction) { baseName = ((XmlSchemaComplexContentRestriction)content).BaseTypeName; attributes = ((XmlSchemaComplexContentRestriction)content).Attributes; } else if (content is XmlSchemaSimpleContentRestriction) { XmlSchemaSimpleContentRestriction restriction = (XmlSchemaSimpleContentRestriction)content; if (restriction.BaseType != null) { baseType = restriction.BaseType; } else { baseName = restriction.BaseTypeName; } attributes = restriction.Attributes; } else if (content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; attributes = extension.Attributes; particle = extension.Particle; baseName = extension.BaseTypeName; } else if (content is XmlSchemaSimpleContentExtension) { XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content; attributes = extension.Attributes; baseName = extension.BaseTypeName; } } else { attributes = ct.Attributes; particle = ct.Particle; } if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; particle = ((XmlSchemaGroup)schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)).Particle; } else if (particle is XmlSchemaGroupBase) { particle = (XmlSchemaGroupBase)particle; } } else if (item is XmlSchemaSimpleType) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)item; XmlSchemaSimpleTypeContent content = simpleType.Content; if (content is XmlSchemaSimpleTypeRestriction) { baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType; baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; } else if (content is XmlSchemaSimpleTypeList) { XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)content; if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty) { baseName = list.ItemTypeName; } if (list.ItemType != null) { baseType = list.ItemType; } } else if (content is XmlSchemaSimpleTypeRestriction) { baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { XmlQualifiedName[] memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes; if (memberTypes != null) { for (int i = 0; i < memberTypes.Length; i++) { XmlSchemaType type = (XmlSchemaType)schemas.Find(memberTypes[i], typeof(XmlSchemaType), false); AddRef(refs, type); } } } } if (baseType == null && !baseName.IsEmpty && baseName.Namespace != XmlSchema.Namespace) { baseType = (XmlSchemaType)schemas.Find(baseName, typeof(XmlSchemaType), false); } if (baseType != null) { AddRef(refs, baseType); } if (particle != null) { Depends(particle, refs); } if (attributes != null) { for (int i = 0; i < attributes.Count; i++) { Depends(attributes[i], refs); } } } else if (t == typeof(XmlSchemaElement)) { XmlSchemaElement el = (XmlSchemaElement)item; if (!el.SubstitutionGroup.IsEmpty) { if (el.SubstitutionGroup.Namespace != XmlSchema.Namespace) { XmlSchemaElement head = (XmlSchemaElement)schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false); AddRef(refs, head); } } if (!el.RefName.IsEmpty) { el = (XmlSchemaElement)schemas.Find(el.RefName, typeof(XmlSchemaElement), false); AddRef(refs, el); } else if (!el.SchemaTypeName.IsEmpty) { XmlSchemaType type = (XmlSchemaType)schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else { Depends(el.SchemaType, refs); } } else if (t == typeof(XmlSchemaGroup)) { Depends(((XmlSchemaGroup)item).Particle); } else if (t == typeof(XmlSchemaGroupRef)) { XmlSchemaGroup group = (XmlSchemaGroup)schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false); AddRef(refs, group); } else if (typeof(XmlSchemaGroupBase).IsAssignableFrom(t)) { foreach (XmlSchemaObject o in ((XmlSchemaGroupBase)item).Items) { Depends(o, refs); } } else if (t == typeof(XmlSchemaAttributeGroupRef)) { XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false); AddRef(refs, group); } else if (t == typeof(XmlSchemaAttributeGroup)) { foreach (XmlSchemaObject o in ((XmlSchemaAttributeGroup)item).Attributes) { Depends(o, refs); } } else if (t == typeof(XmlSchemaAttribute)) { XmlSchemaAttribute at = (XmlSchemaAttribute)item; if (!at.RefName.IsEmpty) { at = (XmlSchemaAttribute)schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false); AddRef(refs, at); } else if (!at.SchemaTypeName.IsEmpty) { XmlSchemaType type = (XmlSchemaType)schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else { Depends(at.SchemaType, refs); } } if (typeof(XmlSchemaAnnotated).IsAssignableFrom(t)) { XmlAttribute[] attrs = (XmlAttribute[])((XmlSchemaAnnotated)item).UnhandledAttributes; if (attrs != null) { for (int i = 0; i < attrs.Length; i++) { XmlAttribute attribute = attrs[i]; if (attribute.LocalName == Wsdl.ArrayType && attribute.NamespaceURI == Wsdl.Namespace) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out dims, item); XmlSchemaType type = (XmlSchemaType)schemas.Find(qname, typeof(XmlSchemaType), false); AddRef(refs, type); } } } } }
public ModelScope(TypeScope typeScope) { this.typeScope = typeScope; }
internal ModelScope(TypeScope typeScope) { _typeScope = typeScope; }
internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNamespace) { XmlAttributes attributes = new XmlAttributes(type); TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); ElementAccessor accessor = new ElementAccessor(); if (typeDesc.Kind == TypeKind.Node) { accessor.Any = true; } else { string str = (attributes.XmlRoot == null) ? defaultNamespace : attributes.XmlRoot.Namespace; string name = string.Empty; if (attributes.XmlType != null) { name = attributes.XmlType.TypeName; } if (name.Length == 0) { name = type.Name; } accessor.Name = XmlConvert.EncodeLocalName(name); accessor.Namespace = str; } XmlTypeMapping mapping = new XmlTypeMapping(null, accessor); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, attributes.XmlRoot, defaultNamespace)); return mapping; }
/// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException1"]/*' /> protected Exception CreateUnknownTypeException(Type type) { if (typeof(IXmlSerializable).IsAssignableFrom(type)) return new InvalidOperationException(Res.GetString(Res.XmlInvalidSerializable, type.FullName)); TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); if (!typeDesc.IsStructLike) return new InvalidOperationException(Res.GetString(Res.XmlInvalidUseOfType, type.FullName)); return new InvalidOperationException(Res.GetString(Res.XmlUnxpectedType, type.FullName)); }
// will create a shallow type mapping for a top-level type internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNamespace) { XmlAttributes a = new XmlAttributes(type); TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); ElementAccessor element = new ElementAccessor(); if (typeDesc.Kind == TypeKind.Node) { element.Any = true; } else { string ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace; string typeName = string.Empty; if (a.XmlType != null) typeName = a.XmlType.TypeName; if (typeName.Length == 0) typeName = type.Name; element.Name = XmlConvert.EncodeLocalName(typeName); element.Namespace = ns; } XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, a.XmlRoot, defaultNamespace)); return mapping; }
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; }
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); }
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(); } }
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(assemblyName); ConstructorInfo SecurityTransparentAttribute_ctor = typeof(SecurityTransparentAttribute).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty <Type>() ); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityTransparentAttribute_ctor, Array.Empty <Object>())); 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); return(writerType.GetTypeInfo().Assembly); }
public XmlSerializationReaderCodeGen(IndentedWriter writer, TypeScope[] scopes) { this.writer = writer; this.scopes = scopes; stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); }
internal XmlSerializationWriterCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) : base(writer, scopes, access, className){ }
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(); } }
string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type){ InitTheFirstTime(); string typeFullName = typeDesc.CSharpName; string typeVariable = (string)reflectionVariables[typeFullName]; if (typeVariable != null) return typeVariable; if (type.IsArray) { typeVariable = GenerateVariableName("array", typeDesc.CSharpName); TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; if (elementTypeDesc.UseReflection) { string elementTypeVariable = WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); writer.WriteLine("static "+typeof(Type).FullName+" "+typeVariable +" = " + elementTypeVariable + ".MakeArrayType();"); } else { string assemblyVariable = WriteAssemblyInfo(type); writer.Write("static "+typeof(Type).FullName+" "+typeVariable +" = "+assemblyVariable+".GetType("); WriteQuotedCSharpString(type.FullName); writer.WriteLine(");"); } } else { typeVariable = GenerateVariableName("type", typeDesc.CSharpName); Type parameterType = Nullable.GetUnderlyingType(type); if (parameterType != null) { string parameterTypeVariable = WriteTypeInfo(scope, scope.GetTypeDesc(parameterType), parameterType); writer.WriteLine("static "+typeof(Type).FullName+" "+typeVariable +" = typeof(System.Nullable<>).MakeGenericType(new " + typeof(Type).FullName + "[] {"+parameterTypeVariable+"});"); } else { string assemblyVariable = WriteAssemblyInfo(type); writer.Write("static "+typeof(Type).FullName+" "+typeVariable +" = "+assemblyVariable+".GetType("); WriteQuotedCSharpString(type.FullName); writer.WriteLine(");"); } } reflectionVariables.Add(typeFullName, typeVariable); TypeMapping mapping = scope.GetTypeMappingFromTypeDesc(typeDesc); if (mapping != null) WriteMappingInfo(mapping, typeVariable, type); if (typeDesc.IsCollection || typeDesc.IsEnumerable){// Arrays use the generic item_Array TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; if (elementTypeDesc.UseReflection) WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); WriteCollectionInfo(typeVariable, typeDesc, type); } return typeVariable; }
private ArrayMapping ImportArrayMapping(XmlSchemaType type, string ns) { ArrayMapping arrayMapping; if (type.Name == Soap.Array && ns == Soap.Encoding) { arrayMapping = new ArrayMapping(); TypeMapping mapping = GetRootMapping(); ElementAccessor itemAccessor = new ElementAccessor(); itemAccessor.IsSoap = true; itemAccessor.Name = Soap.UrType; 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); } 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 = 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.Name, typeName.Namespace); 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); }
internal XmlMapping(TypeScope scope, ElementAccessor accessor) : this(scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write){ }
internal XmlSerializationReaderILGen(TypeScope[] scopes, string access, string className) : base(scopes, access, className) { }