internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); this.writer.WriteLine(); this.writer.Write("public abstract class "); this.writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); this.writer.Write(" : "); this.writer.Write(typeof(XmlSerializer).FullName); this.writer.WriteLine(" {"); this.writer.Indent++; this.writer.Write("protected override "); this.writer.Write(typeof(XmlSerializationReader).FullName); this.writer.WriteLine(" CreateReader() {"); this.writer.Indent++; this.writer.Write("return new "); this.writer.Write(readerClass); this.writer.WriteLine("();"); this.writer.Indent--; this.writer.WriteLine("}"); this.writer.Write("protected override "); this.writer.Write(typeof(XmlSerializationWriter).FullName); this.writer.WriteLine(" CreateWriter() {"); this.writer.Indent++; this.writer.Write("return new "); this.writer.Write(writerClass); this.writer.WriteLine("();"); this.writer.Indent--; this.writer.WriteLine("}"); this.writer.Indent--; this.writer.WriteLine("}"); return baseSerializer; }
public void IgnoreCase () { CodeIdentifiers c = new CodeIdentifiers (false); c.Add ("test", "x"); c.Add ("Test", "y"); Assert.IsTrue ("test" != c.AddUnique ("Test", "z"), "#1"); Assert.IsTrue (c.IsInUse ("tEsT"), "#2"); Assert.AreEqual ("camelCase", c.MakeRightCase ("CAMELCASE"), "#3"); }
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; }
CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers) { CodeIdentifiers pids = new CodeIdentifiers (); CodeMemberMethod method = new CodeMemberMethod (); CodeMemberMethod methodBegin = new CodeMemberMethod (); CodeMemberMethod methodEnd = new CodeMemberMethod (); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodEnd.Attributes = MemberAttributes.Public | MemberAttributes.Final; SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style; // Find unique names for temporary variables for (int n=0; n<inputMembers.Count; n++) pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]); if (outputMembers != null) for (int n=0; n<outputMembers.Count; n++) pids.AddUnique (outputMembers[n].MemberName, outputMembers[n]); string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult"); string varResults = pids.AddUnique ("results","results"); string varCallback = pids.AddUnique ("callback","callback"); string varAsyncState = pids.AddUnique ("asyncState","asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method); method.Name = CodeIdentifier.MakeValid(Operation.Name); if (method.Name == ClassName) method.Name += "1"; methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name),method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name),method); method.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0]; for (int n=0; n<inputMembers.Count; n++) { CodeParameterDeclarationExpression param = GenerateParameter (inputMembers[n], FieldDirection.In); method.Parameters.Add (param); GenerateMemberAttributes (inputMembers, inputMembers[n], bodyBinding.Use, param); methodBegin.Parameters.Add (GenerateParameter (inputMembers[n], FieldDirection.In)); paramArray [n] = new CodeVariableReferenceExpression (param.Name); } if (outputMembers != null) { bool hasReturn = false; for (int n=0; n<outputMembers.Count; n++) { CodeParameterDeclarationExpression cpd = GenerateParameter (outputMembers[n], FieldDirection.Out); outParams [n] = cpd; bool found = false; foreach (CodeParameterDeclarationExpression ip in method.Parameters) { if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType) { ip.Direction = FieldDirection.Ref; methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out)); found = true; break; } } if (found) continue; if (!hasReturn) { hasReturn = true; method.ReturnType = cpd.Type; methodEnd.ReturnType = cpd.Type; GenerateReturnAttributes (outputMembers, outputMembers[n], bodyBinding.Use, method); outParams [n] = null; continue; } method.Parameters.Add (cpd); GenerateMemberAttributes (outputMembers, outputMembers[n], bodyBinding.Use, cpd); methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out)); } } methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback)); methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState)); methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) methodParams = new CodeArrayCreateExpression (typeof(object), paramArray); else methodParams = new CodeArrayCreateExpression (typeof(object), 0); // Assignment of output parameters CodeStatementCollection outAssign = new CodeStatementCollection (); CodeVariableReferenceExpression arrVar = new CodeVariableReferenceExpression (varResults); for (int n=0; n<outParams.Length; n++) { CodeExpression index = new CodePrimitiveExpression (n); if (outParams[n] == null) { CodeExpression res = new CodeCastExpression (method.ReturnType, new CodeArrayIndexerExpression (arrVar, index)); outAssign.Add (new CodeMethodReturnStatement (res)); } else { CodeExpression res = new CodeCastExpression (outParams[n].Type, new CodeArrayIndexerExpression (arrVar, index)); CodeExpression var = new CodeVariableReferenceExpression (outParams[n].Name); outAssign.Insert (0, new CodeAssignStatement (var, res)); } } if (Style == ServiceDescriptionImportStyle.Client) { // Invoke call CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName); CodeMethodInvokeExpression inv; CodeVariableDeclarationStatement dec; inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, methodParams); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv); method.Statements.Add (dec); method.Statements.AddRange (outAssign); } else method.Statements.Add (inv); // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState); inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add (new CodeMethodReturnStatement (inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult); inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv); methodEnd.Statements.Add (dec); methodEnd.Statements.AddRange (outAssign); } else methodEnd.Statements.Add (inv); } else { method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract; } // Attributes ImportHeaders (method); CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.WebMethodAttribute"); if (messageName != method.Name) att.Arguments.Add (GetArg ("MessageName",messageName)); AddCustomAttribute (method, att, (Style == ServiceDescriptionImportStyle.Server)); if (style == SoapBindingStyle.Rpc) { att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapRpcMethodAttribute"); att.Arguments.Add (GetArg (soapOper.SoapAction)); if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName)); if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName)); att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace)); if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true)); } else { if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" || inputMembers.ElementName != "" && outputMembers.ElementName == "")) throw new InvalidOperationException ("Parameter style is not the same for the input message and output message"); att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapDocumentMethodAttribute"); att.Arguments.Add (GetArg (soapOper.SoapAction)); if (inputMembers.ElementName != "") { if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName)); if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName)); att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace)); att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped")); } else att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare")); if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true)); att.Arguments.Add (GetEnumArg ("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString())); } AddCustomAttribute (method, att, true); CodeTypeDeclaration.Members.Add (method); if (Style == ServiceDescriptionImportStyle.Client) { CodeTypeDeclaration.Members.Add (methodBegin); CodeTypeDeclaration.Members.Add (methodEnd); } return method; }
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), Array.Empty<Type>()); ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(readerCtor); ilg.EndMethod(); ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(writerCtor); ilg.EndMethod(); baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; }
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(); } }
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); }
void ImportSequenceContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaObjectCollection items, CodeIdentifiers classIds, bool multiValue, ref bool isMixed) { foreach (XmlSchemaObject item in items) { if (item is XmlSchemaElement) { string ns; XmlSchemaElement elem = (XmlSchemaElement) item; XmlTypeMapping emap; TypeData typeData = GetElementTypeData (typeQName, elem, null, out emap); XmlSchemaElement refElem = GetRefElement (typeQName, elem, out ns); if (elem.MaxOccurs == 1 && !multiValue) { XmlTypeMapMemberElement member = null; if (typeData.SchemaType != SchemaTypes.Array) { member = new XmlTypeMapMemberElement (); if (refElem.DefaultValue != null) member.DefaultValue = ImportDefaultValue (typeData, refElem.DefaultValue); } else if (GetTypeMapping (typeData).IsSimpleType) { // It is a simple list (space separated list). // Since this is not supported, map as a single item value member = new XmlTypeMapMemberElement (); #if NET_2_0 // In MS.NET those types are mapped to a string typeData = TypeTranslator.GetTypeData(typeof(string)); #else typeData = typeData.ListItemTypeData; #endif } else member = new XmlTypeMapMemberList (); if (elem.MinOccurs == 0 && typeData.IsValueType) member.IsOptionalValueType = true; member.Name = classIds.AddUnique(CodeIdentifier.MakeValid(refElem.Name), member); member.Documentation = GetDocumentation (elem); member.TypeData = typeData; member.ElementInfo.Add (CreateElementInfo (ns, member, refElem.Name, typeData, refElem.IsNillable, refElem.Form, emap, items.IndexOf (item))); cmap.AddMember (member); } else { XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList (); member.ListMap = new ListMap (); member.Name = classIds.AddUnique(CodeIdentifier.MakeValid(refElem.Name), member); member.Documentation = GetDocumentation (elem); member.TypeData = typeData.ListTypeData; member.ElementInfo.Add (CreateElementInfo (ns, member, refElem.Name, typeData, refElem.IsNillable, refElem.Form, emap, items.IndexOf (item))); member.ListMap.ItemInfo = member.ElementInfo; cmap.AddMember (member); } } else if (item is XmlSchemaAny) { XmlSchemaAny elem = (XmlSchemaAny) item; XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement (); member.Name = classIds.AddUnique ("Any", member); member.Documentation = GetDocumentation (elem); Type ctype; if (elem.MaxOccurs != 1 || multiValue) ctype = isMixed ? typeof(XmlNode[]) : typeof(XmlElement[]); else ctype = isMixed ? typeof(XmlNode) : typeof(XmlElement); member.TypeData = TypeTranslator.GetTypeData (ctype); XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (member, member.TypeData); einfo.IsUnnamedAnyElement = true; member.ElementInfo.Add (einfo); if (isMixed) { einfo = CreateTextElementInfo (typeQName.Namespace, member, member.TypeData); member.ElementInfo.Add (einfo); member.IsXmlTextCollector = true; isMixed = false; //Allow only one XmlTextAttribute } cmap.AddMember (member); } else if (item is XmlSchemaParticle) { ImportParticleContent (typeQName, cmap, (XmlSchemaParticle)item, classIds, multiValue, ref isMixed); } } }
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], CodeGenerator.EmptyTypeArray ); 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, CodeGenerator.EmptyTypeArray ); 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); }
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 assembly 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); }
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(); } }
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); }
void ExportMembersMapCode(CodeTypeDeclaration codeClass, ClassMap map, string defaultNamespace, XmlTypeMapping baseMap) { ICollection attributes = map.AttributeMembers; ICollection members = map.ElementMembers; // collect names if (attributes != null) { foreach (XmlTypeMapMemberAttribute attr in attributes) { identifiers.AddUnique(attr.Name, attr); } } if (members != null) { foreach (XmlTypeMapMemberElement member in members) { identifiers.AddUnique(member.Name, member); } } // Write attributes if (attributes != null) { foreach (XmlTypeMapMemberAttribute attr in attributes) { if (baseMap != null && DefinedInBaseMap(baseMap, attr)) { continue; } AddAttributeFieldMember(codeClass, attr, defaultNamespace); } } members = map.ElementMembers; if (members != null) { foreach (XmlTypeMapMemberElement member in members) { if (baseMap != null && DefinedInBaseMap(baseMap, member)) { continue; } Type memType = member.GetType(); if (memType == typeof(XmlTypeMapMemberList)) { AddArrayElementFieldMember(codeClass, (XmlTypeMapMemberList)member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberFlatList)) { AddElementFieldMember(codeClass, member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberAnyElement)) { AddAnyElementFieldMember(codeClass, member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberElement)) { AddElementFieldMember(codeClass, member, defaultNamespace); } else { throw new InvalidOperationException("Member type " + memType + " not supported"); } } } XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember; if (anyAttrMember != null) { CodeTypeMember codeField = CreateFieldMember(codeClass, anyAttrMember.TypeData, anyAttrMember.Name); AddComments(codeField, anyAttrMember.Documentation); codeField.Attributes = MemberAttributes.Public; GenerateAnyAttribute(codeField); } }
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); }
void ImportSimpleContent (XmlQualifiedName typeQName, XmlTypeMapping map, XmlSchemaSimpleContent content, CodeIdentifiers classIds, bool isMixed) { XmlSchemaSimpleContentExtension ext = content.Content as XmlSchemaSimpleContentExtension; ClassMap cmap = (ClassMap)map.ObjectMap; XmlQualifiedName qname = GetContentBaseType (content.Content); TypeData simpleType = null; if (!IsPrimitiveTypeNamespace (qname.Namespace)) { // Add base map members to this map XmlTypeMapping baseMap = ImportType (qname, null, true); BuildPendingMap (baseMap); if (baseMap.IsSimpleType) { simpleType = baseMap.TypeData; } else { ClassMap baseClassMap = (ClassMap)baseMap.ObjectMap; foreach (XmlTypeMapMember member in baseClassMap.AllMembers) cmap.AddMember (member); map.BaseMap = baseMap; baseMap.DerivedTypes.Add (map); } } else simpleType = FindBuiltInType (qname); if (simpleType != null) { XmlTypeMapMemberElement member = new XmlTypeMapMemberElement (); member.Name = classIds.AddUnique("Value", member); member.TypeData = simpleType; member.ElementInfo.Add (CreateTextElementInfo (typeQName.Namespace, member, member.TypeData)); member.IsXmlTextCollector = true; cmap.AddMember (member); } if (ext != null) ImportAttributes (typeQName, cmap, ext.Attributes, ext.AnyAttribute, classIds); }
void ImportAttributes (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaObjectCollection atts, XmlSchemaAnyAttribute anyat, CodeIdentifiers classIds) { atts = CollectAttributeUsesNonOverlap (atts, cmap); if (anyat != null) { XmlTypeMapMemberAnyAttribute member = new XmlTypeMapMemberAnyAttribute (); member.Name = classIds.AddUnique ("AnyAttribute", member); member.TypeData = TypeTranslator.GetTypeData (typeof(XmlAttribute[])); cmap.AddMember (member); } foreach (XmlSchemaObject at in atts) { if (at is XmlSchemaAttribute) { string ns; XmlSchemaAttribute attr = (XmlSchemaAttribute)at; XmlSchemaAttribute refAttr = GetRefAttribute (typeQName, attr, out ns); XmlTypeMapMemberAttribute member = new XmlTypeMapMemberAttribute (); member.Name = classIds.AddUnique (CodeIdentifier.MakeValid (refAttr.Name), member); member.Documentation = GetDocumentation (attr); member.AttributeName = refAttr.Name; member.Namespace = ns; member.Form = refAttr.Form; member.TypeData = GetAttributeTypeData (typeQName, attr); if (refAttr.DefaultValue != null) member.DefaultValue = ImportDefaultValue (member.TypeData, refAttr.DefaultValue); else if (member.TypeData.IsValueType) member.IsOptionalValueType = (refAttr.ValidatedUse != XmlSchemaUse.Required); if (member.TypeData.IsComplexType) member.MappedType = GetTypeMapping (member.TypeData); cmap.AddMember (member); } else if (at is XmlSchemaAttributeGroupRef) { XmlSchemaAttributeGroupRef gref = (XmlSchemaAttributeGroupRef)at; XmlSchemaAttributeGroup grp = FindRefAttributeGroup (gref.RefName); ImportAttributes (typeQName, cmap, grp.Attributes, grp.AnyAttribute, classIds); } } }
string GenerateUniqueTypeName(string typeName) { typeName = CodeIdentifier.MakeValid(typeName); return(typeIdentifiers.AddUnique(typeName, typeName)); }
void CreateHeaderMessages(string methodName, SoapBindingUse use, XmlMembersMapping inHeaderMappings, XmlMembersMapping outHeaderMappings, SoapReflectedHeader[] headers, bool rpc) { // if (use == SoapBindingUse.Encoded) { SoapExporter.ExportMembersMapping(inHeaderMappings, false); if (outHeaderMappings != null) SoapExporter.ExportMembersMapping(outHeaderMappings, false); } else { SchemaExporter.ExportMembersMapping(inHeaderMappings); if (outHeaderMappings != null) SchemaExporter.ExportMembersMapping(outHeaderMappings); } CodeIdentifiers identifiers = new CodeIdentifiers(); int inCount = 0, outCount = 0; for (int i = 0; i < headers.Length; i++) { SoapReflectedHeader soapHeader = headers[i]; if (!soapHeader.custom) continue; XmlMemberMapping member; if ((soapHeader.direction & SoapHeaderDirection.In) != 0) { member = inHeaderMappings[inCount++]; if (soapHeader.direction != SoapHeaderDirection.In) outCount++; } else { member = outHeaderMappings[outCount++]; } MessagePart part = new MessagePart(); part.Name = member.XsdElementName; if (use == SoapBindingUse.Encoded) part.Type = new XmlQualifiedName(member.TypeName, member.TypeNamespace); else part.Element = new XmlQualifiedName(member.XsdElementName, member.Namespace); Message message = new Message(); message.Name = identifiers.AddUnique(methodName + part.Name, message); message.Parts.Add(part); HeaderMessages.Add(message); ServiceDescriptionFormatExtension soapHeaderBinding = CreateSoapHeaderBinding(new XmlQualifiedName(message.Name, Binding.ServiceDescription.TargetNamespace), part.Name, rpc ? member.Namespace : null, use); if ((soapHeader.direction & SoapHeaderDirection.In) != 0) OperationBinding.Input.Extensions.Add(soapHeaderBinding); if ((soapHeader.direction & SoapHeaderDirection.Out) != 0) OperationBinding.Output.Extensions.Add(soapHeaderBinding); if ((soapHeader.direction & SoapHeaderDirection.Fault) != 0) { if (soapMethod.IsClaimsConformance) { throw new InvalidOperationException(Res.GetString(Res.BPConformanceHeaderFault, soapMethod.methodInfo.ToString(), soapMethod.methodInfo.DeclaringType.FullName, "Direction", typeof(SoapHeaderDirection).Name, SoapHeaderDirection.Fault.ToString())); } OperationBinding.Output.Extensions.Add(soapHeaderBinding); } } }
void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, string ns) { AttributeAccessor accessor = ImportAttribute(attribute, identifier, ns); if (accessor == null) return; MemberMapping member = new MemberMapping(); member.Elements = new ElementAccessor[0]; member.Attribute = accessor; member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = members.AddUnique(member.Name, member); if (member.Name.EndsWith("Specified")) { string name = member.Name; member.Name = members.AddUnique(member.Name, member); members.Remove(name); } member.TypeDesc = accessor.IsList ? accessor.Mapping.TypeDesc.CreateArrayTypeDesc() : accessor.Mapping.TypeDesc; if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = true; } }
void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers members) { SpecialMapping mapping = new SpecialMapping(); mapping.TypeDesc = scope.GetTypeDesc(typeof(XmlAttribute)); mapping.TypeName = mapping.TypeDesc.Name; AttributeAccessor accessor = new AttributeAccessor(); accessor.Any = true; accessor.Mapping = mapping; MemberMapping member = new MemberMapping(); member.Elements = new ElementAccessor[0]; member.Attribute = accessor; member.Name = members.MakeRightCase("AnyAttr"); member.Name = members.AddUnique(member.Name, member); member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc; member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); }
void ImportXmlnsDeclarationsMember(XmlSchemaType type, CodeIdentifiers members) { string xmlnsMemberName; if (!KeepXmlnsDeclarations(type, out xmlnsMemberName)) return; TypeDesc xmlnsTypeDesc = scope.GetTypeDesc(typeof(XmlSerializerNamespaces)); StructMapping xmlnsMapping = new StructMapping(); xmlnsMapping.TypeDesc = xmlnsTypeDesc; xmlnsMapping.TypeName = xmlnsMapping.TypeDesc.Name; xmlnsMapping.Members = new MemberMapping[0]; xmlnsMapping.IncludeInSchema = false; xmlnsMapping.ReferencedByTopLevelElement = true; ElementAccessor xmlns = new ElementAccessor(); xmlns.Mapping = xmlnsMapping; MemberMapping member = new MemberMapping(); member.Elements = new ElementAccessor[] {xmlns}; member.Name = CodeIdentifier.MakeValid(xmlnsMemberName == null ? "Namespaces" : xmlnsMemberName); member.Name = members.AddUnique(member.Name, member); member.TypeDesc = xmlnsTypeDesc; member.Xmlns = new XmlnsAccessor(); member.Ignore = true; }
void ExportProperty(CodeTypeDeclaration codeClass, MemberMapping member, CodeIdentifiers memberScope) { string fieldName = memberScope.AddUnique(CodeExporter.MakeFieldName(member.Name), member); string fieldType = member.GetTypeName(CodeProvider); // need to create a private field CodeMemberField field = new CodeMemberField(fieldType, fieldName); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); CodeMemberProperty prop = CreatePropertyDeclaration(field, member.Name, fieldType); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); AddMemberMetadata(prop.CustomAttributes, member, false); codeClass.Members.Add(prop); if (member.CheckSpecified != SpecifiedAccessor.None) { field = new CodeMemberField(typeof(bool).FullName, fieldName + "Specified"); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); prop = CreatePropertyDeclaration(field, member.Name + "Specified", typeof(bool).FullName); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(SoapIgnoreAttribute).FullName); prop.CustomAttributes.Add(attribute); codeClass.Members.Add(prop); } }
TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier) { EnumMapping enumMapping = (EnumMapping)mappings[dataType]; if (enumMapping != null) return enumMapping; XmlSchemaType sourceType = FindType(dataType.DerivedFrom); if (sourceType is XmlSchemaComplexType) return null; TypeDesc sourceTypeDesc = scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName) return ImportPrimitiveDataType(dataType); string typeName = GenerateUniqueTypeName(identifier); enumMapping = new EnumMapping(); enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0); enumMapping.TypeName = identifier; enumMapping.Namespace = typeNs; enumMapping.IsFlags = false; mappings.Add(dataType, enumMapping); CodeIdentifiers constants = new CodeIdentifiers(); XmlSchemaSimpleTypeContent content = dataType.Content; if (content is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content; for (int i = 0; i < restriction.Facets.Count; i++) { object facet = restriction.Facets[i]; if (!(facet is XmlSchemaEnumerationFacet)) continue; XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet; // validate the enumeration value if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) { XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName); } 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)); scope.AddTypeMapping(enumMapping); return enumMapping; }
public static void Generate (string configFileName, string outputPath) { SerializationCodeGeneratorConfiguration cnf = null; StreamReader sr = new StreamReader (configFileName); try { XmlReflectionImporter ri = new XmlReflectionImporter (); ri.AllowPrivateTypes = true; XmlSerializer ser = new XmlSerializer (ri.ImportTypeMapping (typeof (SerializationCodeGeneratorConfiguration))); cnf = (SerializationCodeGeneratorConfiguration) ser.Deserialize (sr); } finally { sr.Close (); } if (outputPath == null) outputPath = ""; CodeIdentifiers ids = new CodeIdentifiers (); if (cnf.Serializers != null) { foreach (SerializerInfo info in cnf.Serializers) { Type type; if (info.Assembly != null) { Assembly asm; try { asm = Assembly.Load (info.Assembly); } catch { asm = Assembly.LoadFrom (info.Assembly); } type = asm.GetType (info.ClassName, true); } else type = Type.GetType (info.ClassName); if (type == null) throw new InvalidOperationException ("Type " + info.ClassName + " not found"); string file = info.OutFileName; if (file == null || file.Length == 0) { int i = info.ClassName.LastIndexOf ("."); if (i != -1) file = info.ClassName.Substring (i+1); else file = info.ClassName; file = ids.AddUnique (file, type) + "Serializer.cs"; } StreamWriter writer = new StreamWriter (Path.Combine (outputPath, file)); try { XmlTypeMapping map; if (info.SerializationFormat == SerializationFormat.Literal) { XmlReflectionImporter ri = new XmlReflectionImporter (); map = ri.ImportTypeMapping (type); } else { SoapReflectionImporter ri = new SoapReflectionImporter (); map = ri.ImportTypeMapping (type); } SerializationCodeGenerator gen = new SerializationCodeGenerator (map, info); gen.GenerateSerializers (writer); } finally { writer.Close (); } } } }
EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string typeNs, string typeName) { typeName = GenerateUniqueTypeName(typeName, typeNs); EnumMapping enumMapping = new EnumMapping(); enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0); enumMapping.TypeName = typeName; enumMapping.Namespace = typeNs; enumMapping.IsFlags = false; enumMapping.IncludeInSchema = false; CodeIdentifiers constants = new CodeIdentifiers(); for (int i = 0; i < choice.Length; i++) { ElementAccessor element = choice[i]; ConstantMapping constant = new ConstantMapping(); string constantName = CodeIdentifier.MakeValid(element.Name); constant.Name = constants.AddUnique(constantName, constant); constant.XmlName = element.Namespace == typeNs ? element.Name : element.Namespace + ":" + element.Name; constant.Value = i; } enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping)); scope.AddTypeMapping(enumMapping); return enumMapping; }
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; }
/// <include file='doc\XmlSchemaImporter.uex' path='docs/doc[@for="XmlSchemaImporter.ImportMembersMapping2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type baseType, bool baseTypeCanBeIndirect) { CodeIdentifiers memberScope = new CodeIdentifiers(); memberScope.UseCamelCasing = true; MemberMapping[] members = new MemberMapping[names.Length]; for (int i = 0; i < names.Length; i++) { XmlQualifiedName name = EncodeQName(names[i]); ElementAccessor accessor = ImportElement(name, typeof(TypeMapping), baseType); if (baseType != null && accessor.Mapping is StructMapping) MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect); MemberMapping member = new MemberMapping(); member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = memberScope.AddUnique(member.Name, member); member.TypeDesc = accessor.Mapping.TypeDesc; member.Elements = new ElementAccessor[] { accessor }; members[i] = member; } MembersMapping mapping = new MembersMapping(); mapping.HasWrapperElement = false; mapping.TypeDesc = scope.GetTypeDesc(typeof(object[])); mapping.Members = members; ElementAccessor element = new ElementAccessor(); element.Mapping = mapping; return new XmlMembersMapping(scope, element); }
void ImportElementMember(XmlSchemaElement element, CodeIdentifiers members, string ns) { ElementAccessor accessor; if ((accessor = ImportArray(element, ns)) == null) { accessor = ImportElement(element, ns); } MemberMapping member = new MemberMapping(); member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = members.AddUnique(member.Name, member); if (member.Name.EndsWith("Specified", StringComparison.Ordinal)) { string name = member.Name; member.Name = members.AddUnique(member.Name, member); members.Remove(name); } member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc; member.Elements = new ElementAccessor[] { accessor }; if (element.IsMultipleOccurrence) member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = true; } }
MemberMapping ImportChoiceGroup(XmlSchemaChoice group, string identifier, CodeIdentifiers members, string ns, bool groupRepeats) { ArrayList list = new ArrayList(); if (GatherGroupChoices(group, list, identifier, ns)) groupRepeats = true; MemberMapping member = new MemberMapping(); member.Elements = (ElementAccessor[])list.ToArray(typeof(ElementAccessor)); bool duplicateTypes = false; Hashtable uniqueTypeDescs = new Hashtable(list.Count); for (int i = 0; i < list.Count; i++) { TypeDesc td = ((TypeMapping)((ElementAccessor)list[i]).Mapping).TypeDesc; if (uniqueTypeDescs.Contains(td.FullName)) { duplicateTypes = true; } else { uniqueTypeDescs.Add(td.FullName, td); } } TypeDesc[] typeDescs = new TypeDesc[uniqueTypeDescs.Count]; uniqueTypeDescs.Values.CopyTo(typeDescs, 0); member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs); if (member.TypeDesc == null) member.TypeDesc = scope.GetTypeDesc(typeof(object)); if (groupRepeats) member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); if (members != null) { member.Name = members.AddUnique(groupRepeats ? "Items" : "Item", member); } if (duplicateTypes) { member.ChoiceIdentifier = new ChoiceIdentifierAccessor(); member.ChoiceIdentifier.MemberName = member.Name + "ElementName"; // we need to create the EnumMapping to store all of the element names member.ChoiceIdentifier.Mapping = ImportEnumeratedChoice(member.Elements, ns, member.Name + "ChoiceType"); member.ChoiceIdentifier.MemberIds = new string[member.Elements.Length]; ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants; for (int i = 0; i < member.Elements.Length; i++) { member.ChoiceIdentifier.MemberIds[i] = constants[i].Name; } MemberMapping choiceIdentifier = new MemberMapping(); choiceIdentifier.Ignore = true; choiceIdentifier.Name = member.ChoiceIdentifier.MemberName; if (groupRepeats) { choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc.CreateArrayTypeDesc(); } else { choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc; } // create element accessor for the choiceIdentifier ElementAccessor choiceAccessor = new ElementAccessor(); choiceAccessor.Name = choiceIdentifier.Name; choiceAccessor.Namespace = ns; choiceAccessor.Mapping = member.ChoiceIdentifier.Mapping; choiceIdentifier.Elements = new ElementAccessor[] {choiceAccessor}; if (members != null) { choiceAccessor.Name = choiceIdentifier.Name = member.ChoiceIdentifier.MemberName = members.AddUnique(member.ChoiceIdentifier.MemberName, choiceIdentifier); } } return member; }
void ImportChoiceContent (XmlQualifiedName typeQName, ClassMap cmap, XmlSchemaChoice choice, CodeIdentifiers classIds, bool multiValue) { XmlTypeMapElementInfoList choices = new XmlTypeMapElementInfoList (); multiValue = ImportChoices (typeQName, null, choices, choice.Items) || multiValue; if (choices.Count == 0) return; if (choice.MaxOccurs > 1) multiValue = true; XmlTypeMapMemberElement member; if (multiValue) { member = new XmlTypeMapMemberFlatList (); member.Name = classIds.AddUnique ("Items", member); ListMap listMap = new ListMap (); listMap.ItemInfo = choices; ((XmlTypeMapMemberFlatList)member).ListMap = listMap; } else { member = new XmlTypeMapMemberElement (); member.Name = classIds.AddUnique ("Item", member); } // If all choices have the same type, use that type for the member. // If not use System.Object. // If there are at least two choices with the same type, use a choice // identifier attribute TypeData typeData = null; bool twoEqual = false; bool allEqual = true; Hashtable types = new Hashtable (); for (int n = choices.Count - 1; n >= 0; n--) { XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) choices [n]; // In some complex schemas, we may end up with several options // with the same name. It is better to ignore the extra options // than to crash. It's the best we can do, and btw it works // better than in MS.NET. if (cmap.GetElement (einfo.ElementName, einfo.Namespace, einfo.ExplicitOrder) != null || choices.IndexOfElement (einfo.ElementName, einfo.Namespace) != n) { choices.RemoveAt (n); continue; } if (types.ContainsKey (einfo.TypeData)) twoEqual = true; else types.Add (einfo.TypeData, einfo); TypeData choiceType = einfo.TypeData; if (choiceType.SchemaType == SchemaTypes.Class) { // When comparing class types, use the most generic class in the // inheritance hierarchy XmlTypeMapping choiceMap = GetTypeMapping (choiceType); BuildPendingMap (choiceMap); while (choiceMap.BaseMap != null) { choiceMap = choiceMap.BaseMap; BuildPendingMap (choiceMap); choiceType = choiceMap.TypeData; } } if (typeData == null) typeData = choiceType; else if (typeData != choiceType) allEqual = false; } if (!allEqual) typeData = TypeTranslator.GetTypeData (typeof(object)); if (twoEqual) { // Create the choice member XmlTypeMapMemberElement choiceMember = new XmlTypeMapMemberElement (); choiceMember.Ignore = true; choiceMember.Name = classIds.AddUnique (member.Name + "ElementName", choiceMember); member.ChoiceMember = choiceMember.Name; // Create the choice enum XmlTypeMapping enumMap = CreateTypeMapping (new XmlQualifiedName (member.Name + "ChoiceType", typeQName.Namespace), SchemaTypes.Enum, null); enumMap.IncludeInSchema = false; CodeIdentifiers codeIdents = new CodeIdentifiers (); EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember [choices.Count]; for (int n=0; n<choices.Count; n++) { XmlTypeMapElementInfo it =(XmlTypeMapElementInfo) choices[n]; bool extraNs = (it.Namespace != null && it.Namespace != "" && it.Namespace != typeQName.Namespace); string xmlName = extraNs ? it.Namespace + ":" + it.ElementName : it.ElementName; string enumName = codeIdents.AddUnique (CodeIdentifier.MakeValid (it.ElementName), it); members [n] = new EnumMap.EnumMapMember (xmlName, enumName); } enumMap.ObjectMap = new EnumMap (members, false); choiceMember.TypeData = multiValue ? enumMap.TypeData.ListTypeData : enumMap.TypeData; choiceMember.ElementInfo.Add (CreateElementInfo (typeQName.Namespace, choiceMember, choiceMember.Name, choiceMember.TypeData, false, XmlSchemaForm.None, -1)); cmap.AddMember (choiceMember); } if (typeData == null) return; if (multiValue) typeData = typeData.ListTypeData; member.ElementInfo = choices; member.Documentation = GetDocumentation (choice); member.TypeData = typeData; cmap.AddMember (member); }
void ImportTextMember(CodeIdentifiers members, XmlQualifiedName simpleContentType) { TypeMapping mapping; bool isMixed = false; if (simpleContentType != null) { mapping = ImportType(simpleContentType, typeof(TypeMapping), null); if (!(mapping is PrimitiveMapping || mapping.TypeDesc.CanBeTextValue)) { return; } } else { // this is a case of the mixed content type, just generate string typeDesc isMixed = true; mapping = new PrimitiveMapping(); mapping.TypeDesc = scope.GetTypeDesc(typeof(string)); mapping.TypeName = mapping.TypeDesc.DataType.Name; } TextAccessor accessor = new TextAccessor(); accessor.Mapping = mapping; MemberMapping member = new MemberMapping(); member.Elements = new ElementAccessor[0]; member.Text = accessor; if (isMixed) { // just generate code for the standard mixed case (string[] text) member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else { // import mapping for the simpleContent PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping; if (pm.IsList) { member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else { member.TypeDesc = accessor.Mapping.TypeDesc; member.Name = members.MakeRightCase("Value"); } } member.Name = members.AddUnique(member.Name, member); }
XmlTypeMapping ImportClassSimpleType (XmlQualifiedName typeQName, XmlSchemaSimpleType stype, XmlQualifiedName root) { if (CanBeEnum (stype)) { // Create an enum map CodeIdentifiers codeIdents = new CodeIdentifiers (); XmlTypeMapping enumMap = CreateTypeMapping (typeQName, SchemaTypes.Enum, root); enumMap.Documentation = GetDocumentation (stype); bool isFlags = false; if (stype.Content is XmlSchemaSimpleTypeList) { stype = ((XmlSchemaSimpleTypeList)stype.Content).ItemType; isFlags = true; } XmlSchemaSimpleTypeRestriction rest = (XmlSchemaSimpleTypeRestriction)stype.Content; codeIdents.AddReserved (enumMap.TypeData.TypeName); EnumMap.EnumMapMember[] members = new EnumMap.EnumMapMember [rest.Facets.Count]; for (int n=0; n<rest.Facets.Count; n++) { XmlSchemaEnumerationFacet enu = (XmlSchemaEnumerationFacet) rest.Facets[n]; string enumName = codeIdents.AddUnique(CodeIdentifier.MakeValid (enu.Value), enu); members [n] = new EnumMap.EnumMapMember (enu.Value, enumName); members [n].Documentation = GetDocumentation (enu); } enumMap.ObjectMap = new EnumMap (members, isFlags); enumMap.IsSimpleType = true; return enumMap; } if (stype.Content is XmlSchemaSimpleTypeList) { XmlSchemaSimpleTypeList slist = (XmlSchemaSimpleTypeList)stype.Content; TypeData arrayTypeData = FindBuiltInType (slist.ItemTypeName, stype); ListMap listMap = new ListMap (); listMap.ItemInfo = new XmlTypeMapElementInfoList (); listMap.ItemInfo.Add (CreateElementInfo (typeQName.Namespace, null, "Item", arrayTypeData.ListItemTypeData, false, XmlSchemaForm.None, -1)); XmlTypeMapping map = CreateArrayTypeMapping (typeQName, arrayTypeData); map.ObjectMap = listMap; map.IsSimpleType = true; return map; } // It is an extension of a primitive or known type TypeData typeData = FindBuiltInType (typeQName, stype); XmlTypeMapping rmap = GetTypeMapping (typeData); // The resulting map must be a simple type. It needs to be explicitely set for arrays rmap.IsSimpleType = true; return rmap; }
void ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, string ns, bool mixed) { ElementAccessor accessor = ImportAny(any, !mixed); accessor.Name = identifier; accessor.Namespace = ns; MemberMapping member = new MemberMapping(); member.Elements = new ElementAccessor[] { accessor }; member.Name = members.MakeRightCase("Any"); member.Name = members.AddUnique(member.Name, member); member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc; bool repeats = any.IsMultipleOccurrence; if (mixed) { SpecialMapping textMapping = new SpecialMapping(); textMapping.TypeDesc = scope.GetTypeDesc(typeof(XmlNode)); textMapping.TypeName = textMapping.TypeDesc.Name; member.TypeDesc = textMapping.TypeDesc; TextAccessor text = new TextAccessor(); text.Mapping = textMapping; member.Text = text; repeats = true; } if (repeats) { member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); } }
void AddTextMember (XmlQualifiedName typeQName, ClassMap cmap, CodeIdentifiers classIds) { if (cmap.XmlTextCollector == null) { XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList (); member.Name = classIds.AddUnique ("Text", member); member.TypeData = TypeTranslator.GetTypeData (typeof(string[])); member.ElementInfo.Add (CreateTextElementInfo (typeQName.Namespace, member, member.TypeData.ListItemTypeData)); member.IsXmlTextCollector = true; member.ListMap = new ListMap (); member.ListMap.ItemInfo = member.ElementInfo; cmap.AddMember (member); } }
void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, string ns, bool repeats) { XmlSchemaElement abstractElement = GetAbstractElement(element); if (abstractElement != null) { ImportAbstractMember(abstractElement, identifier, members, ns, repeats); return; } ElementAccessor accessor; if ((accessor = ImportArray(element, identifier, ns, repeats)) == null) { if ((accessor = ImportSerializable(element, identifier, ns, repeats)) == null) { accessor = ImportElement(element, identifier, typeof(TypeMapping), null, ns); } } MemberMapping member = new MemberMapping(); member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = members.AddUnique(member.Name, member); if (member.Name.EndsWith("Specified")) { string name = member.Name; member.Name = members.AddUnique(member.Name, member); members.Remove(name); } member.TypeDesc = ((TypeMapping)accessor.Mapping).TypeDesc; member.Elements = new ElementAccessor[] { accessor }; if (element.IsMultipleOccurrence || repeats) member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = true; } }
CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember) { CodeIdentifiers pids = new CodeIdentifiers (); CodeMemberMethod method = new CodeMemberMethod (); CodeMemberMethod methodBegin = new CodeMemberMethod (); CodeMemberMethod methodEnd = new CodeMemberMethod (); method.Attributes = MemberAttributes.Public; methodBegin.Attributes = MemberAttributes.Public; methodEnd.Attributes = MemberAttributes.Public; // Find unique names for temporary variables for (int n=0; n<inputMembers.Count; n++) pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]); string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult"); string varCallback = pids.AddUnique ("callback","callback"); string varAsyncState = pids.AddUnique ("asyncState","asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method); method.Name = Operation.Name; methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name),method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name),method); method.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; for (int n=0; n<inputMembers.Count; n++) { string ptype = GetSimpleType (inputMembers[n]); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (ptype, inputMembers[n].MemberName); param.Direction = FieldDirection.In; method.Parameters.Add (param); methodBegin.Parameters.Add (param); paramArray [n] = new CodeVariableReferenceExpression (param.Name); } bool isVoid = true; if (outputMember != null) { method.ReturnType = new CodeTypeReference (outputMember.TypeFullName); methodEnd.ReturnType = new CodeTypeReference (outputMember.TypeFullName); xmlExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, outputMember, ""); isVoid = false; } methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback)); methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState)); methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) methodParams = new CodeArrayCreateExpression (typeof(object), paramArray); else methodParams = new CodeArrayCreateExpression (typeof(object), 0); // Generate method url CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url"); CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location); CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl); // Invoke call CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, expMethodLocation, methodParams); if (!isVoid) method.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (method.ReturnType, inv))); else method.Statements.Add (inv); // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState); inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add (new CodeMethodReturnStatement (inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult); inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr); if (!isVoid) methodEnd.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (methodEnd.ReturnType, inv))); else methodEnd.Statements.Add (inv); // Attributes CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.HttpMethodAttribute"); att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetOutMimeFormatter ()))); att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetInMimeFormatter ()))); AddCustomAttribute (method, att, true); CodeTypeDeclaration.Members.Add (method); CodeTypeDeclaration.Members.Add (methodBegin); CodeTypeDeclaration.Members.Add (methodEnd); return method; }
internal static string UniqueName(string baseName, string[] scope) { CodeIdentifiers identifiers = new CodeIdentifiers(); for (int i = 0; i < scope.Length; i++) { identifiers.AddUnique(scope[i], scope[i]); } return identifiers.AddUnique(baseName, baseName); }
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); writer.WriteLine(); writer.Write("public sealed class "); writer.Write(CodeIdentifier.GetCSharpName(serializerName)); writer.Write(" : "); writer.Write(baseSerializer); writer.WriteLine(" {"); writer.Indent++; writer.WriteLine(); writer.Write("public override "); writer.Write(typeof(bool).FullName); writer.Write(" CanDeserialize("); writer.Write(typeof(XmlReader).FullName); writer.WriteLine(" xmlReader) {"); writer.Indent++; if (mapping.Accessor.Any) { writer.WriteLine("return true;"); } else { writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); writer.WriteLine(");"); } writer.Indent--; writer.WriteLine("}"); if (writeMethod != null) { writer.WriteLine(); writer.Write("protected override void Serialize(object objectToSerialize, "); writer.Write(typeof(XmlSerializationWriter).FullName); writer.WriteLine(" writer) {"); writer.Indent++; writer.Write("(("); writer.Write(writerClass); writer.Write(")writer)."); writer.Write(writeMethod); writer.Write("("); if (mapping is XmlMembersMapping) { writer.Write("(object[])"); } writer.WriteLine("objectToSerialize);"); writer.Indent--; writer.WriteLine("}"); } if (readMethod != null) { writer.WriteLine(); writer.Write("protected override object Deserialize("); writer.Write(typeof(XmlSerializationReader).FullName); writer.WriteLine(" reader) {"); writer.Indent++; writer.Write("return (("); writer.Write(readerClass); writer.Write(")reader)."); writer.Write(readMethod); writer.WriteLine("();"); writer.Indent--; writer.WriteLine("}"); } writer.Indent--; writer.WriteLine("}"); return serializerName; }
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; }