void WriteQualifiedNameElement(string name, string ns, object defaultValue, SourceInfo source, bool nullable, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) { throw CodeGenerator.NotSupported("XmlQualifiedName DefaultValue not supported. Fail in WriteValue()"); } List<Type> argTypes = new List<Type>(); ilg.Ldarg(0); ilg.Ldstr(name); argTypes.Add(typeof(string)); if (ns != null) { ilg.Ldstr(ns); argTypes.Add(typeof(string)); } source.Load(mapping.TypeDesc.Type); argTypes.Add(mapping.TypeDesc.Type); MethodInfo XmlSerializationWriter_WriteXXX = typeof(XmlSerializationWriter).GetMethod( nullable ? ("WriteNullableQualifiedNameLiteral") : "WriteElementQualifiedName", CodeGenerator.InstanceBindingFlags, null, argTypes.ToArray(), null ); ilg.Call(XmlSerializationWriter_WriteXXX); if (hasDefault) { throw CodeGenerator.NotSupported("XmlQualifiedName DefaultValue not supported. Fail in WriteValue()"); } }
void ExportType(TypeMapping mapping) { if (mapping.IsReference) return; if (ExportedMappings[mapping] == null) { CodeTypeDeclaration codeClass = null; ExportedMappings.Add(mapping, mapping); if (mapping is EnumMapping) { codeClass = ExportEnum((EnumMapping)mapping, typeof(SoapEnumAttribute)); } else if (mapping is StructMapping) { codeClass = ExportStruct((StructMapping)mapping); } else if (mapping is ArrayMapping) { EnsureTypesExported(((ArrayMapping)mapping).Elements, null); } if (codeClass != null) { // Add [GeneratedCodeAttribute(Tool=.., Version=..)] codeClass.CustomAttributes.Add(GeneratedCodeAttribute); // Add [SerializableAttribute] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializableAttribute).FullName)); if (!codeClass.IsEnum) { // Add [DebuggerStepThrough] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DebuggerStepThroughAttribute).FullName)); // Add [DesignerCategory("code")] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DesignerCategoryAttribute).FullName, new CodeAttributeArgument[] {new CodeAttributeArgument(new CodePrimitiveExpression("code"))})); } AddTypeMetadata(codeClass.CustomAttributes, typeof(SoapTypeAttribute), mapping.TypeDesc.Name, Accessor.UnescapeName(mapping.TypeName), mapping.Namespace, mapping.IncludeInSchema); ExportedClasses.Add(mapping, codeClass); } } }
internal string ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } } return (string)_methodNames[mapping]; }
internal override void GenerateMethod(TypeMapping mapping) { if (GeneratedMethods.Contains(mapping)) return; GeneratedMethods[mapping] = mapping; if (mapping is StructMapping) { WriteStructMethod((StructMapping)mapping); } else if (mapping is EnumMapping) { WriteEnumMethod((EnumMapping)mapping); } }
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) { return new TypeMapping[0x20]; } if (index < a.Length) { return a; } TypeMapping[] destinationArray = new TypeMapping[a.Length + 0x20]; Array.Copy(a, destinationArray, index); return destinationArray; }
internal override void GenerateMethod(TypeMapping mapping) { if (!GeneratedMethods.Add(mapping)) return; if (mapping is StructMapping) { WriteStructMethod((StructMapping)mapping); } else if (mapping is EnumMapping) { WriteEnumMethod((EnumMapping)mapping); } }
void WritePrimitive(string method, string name, string ns, object defaultValue, string source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { TypeDesc typeDesc = mapping.TypeDesc; bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); #endif Writer.Write("if ("); if (mapping.TypeDesc.UseReflection) Writer.Write(RaCodeGen.GetStringForEnumLongValue(source, mapping.TypeDesc.UseReflection)); else Writer.Write(source); Writer.Write(" != "); if (((EnumMapping)mapping).IsFlags) { Writer.Write("("); string[] values = ((string)defaultValue).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i] == null || values[i].Length == 0) continue; if (i > 0) Writer.WriteLine(" | "); Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, values[i], mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } else { Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue, mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } else { WriteCheckDefault(source, defaultValue, isNullable); } Writer.WriteLine(" {"); Writer.Indent++; } Writer.Write(method); Writer.Write("("); WriteQuotedCSharpString(name); if (ns != null) { Writer.Write(", "); WriteQuotedCSharpString(ns); } Writer.Write(", "); if (mapping is EnumMapping) { WriteEnumValue((EnumMapping)mapping, source); } else { WritePrimitiveValue(typeDesc, source, isElement); } if (writeXsiType) { Writer.Write(", new System.Xml.XmlQualifiedName("); WriteQuotedCSharpString(mapping.TypeName); Writer.Write(", "); WriteQuotedCSharpString(mapping.Namespace); Writer.Write(")"); } Writer.WriteLine(");"); if (hasDefault) { Writer.Indent--; Writer.WriteLine("}"); } }
static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; element.Name = mapping.TypeName; //XmlConvert.EncodeLocalName(name == null || name.Length == 0 ? mapping.TypeName : name); element.Namespace = ns; element.Mapping = mapping; return element; }
internal virtual void GenerateMethod(TypeMapping mapping){}
internal void AddTypeMapping(TypeMapping typeMapping) { _typeMappings.Add(typeMapping); }
void WritePrimitive(TypeMapping mapping, string source) { if (mapping is EnumMapping) { string enumMethodName = ReferenceMapping(mapping); if (enumMethodName == null) throw new InvalidOperationException(Res.GetString(Res.XmlMissingMethodEnum, mapping.TypeDesc.Name)); if (mapping.IsSoap) { // SOAP methods are not strongly-typed (the return object), so we need to add a cast Writer.Write("("); Writer.Write(mapping.TypeDesc.CSharpName); Writer.Write(")"); } Writer.Write(enumMethodName); Writer.Write("("); if (!mapping.IsSoap) Writer.Write(source); Writer.Write(")"); } else if (mapping.TypeDesc == StringTypeDesc) { Writer.Write(source); } else if (mapping.TypeDesc.FormatterName == "String") { if (mapping.TypeDesc.CollapseWhitespace) { Writer.Write("CollapseWhitespace("); Writer.Write(source); Writer.Write(")"); } else { Writer.Write(source); } } else { if (!mapping.TypeDesc.HasCustomFormatter) { Writer.Write(typeof(XmlConvert).FullName); Writer.Write("."); } Writer.Write("To"); Writer.Write(mapping.TypeDesc.FormatterName); Writer.Write("("); Writer.Write(source); Writer.Write(")"); } }
internal static string ExportDefaultValue(TypeMapping mapping, object value) { if (!(mapping is PrimitiveMapping)) { return null; } if ((value == null) || (value == DBNull.Value)) { return null; } if (mapping is EnumMapping) { EnumMapping mapping2 = (EnumMapping) mapping; ConstantMapping[] constants = mapping2.Constants; if (mapping2.IsFlags) { string[] vals = new string[constants.Length]; long[] ids = new long[constants.Length]; Hashtable hashtable = new Hashtable(); for (int j = 0; j < constants.Length; j++) { vals[j] = constants[j].XmlName; ids[j] = ((int) 1) << j; hashtable.Add(constants[j].Name, ids[j]); } long val = XmlCustomFormatter.ToEnum((string) value, hashtable, mapping2.TypeName, false); if (val == 0L) { return null; } return XmlCustomFormatter.FromEnum(val, vals, ids, mapping.TypeDesc.FullName); } for (int i = 0; i < constants.Length; i++) { if (constants[i].Name == ((string) value)) { return constants[i].XmlName; } } return null; } PrimitiveMapping mapping3 = (PrimitiveMapping) mapping; if (!mapping3.TypeDesc.HasCustomFormatter) { if (mapping3.TypeDesc.FormatterName == "String") { return (string) value; } Type type = typeof(XmlConvert); MethodInfo method = type.GetMethod("ToString", new Type[] { mapping3.TypeDesc.Type }); if (method != null) { return (string) method.Invoke(type, new object[] { value }); } } else { string str = XmlCustomFormatter.FromDefaultValue(value, mapping3.TypeDesc.FormatterName); if (str == null) { throw new InvalidOperationException(Res.GetString("XmlInvalidDefaultValue", new object[] { value.ToString(), mapping3.TypeDesc.Name })); } return str; } throw new InvalidOperationException(Res.GetString("XmlInvalidDefaultValue", new object[] { value.ToString(), mapping3.TypeDesc.Name })); }
void ExportType(TypeMapping mapping) { if (exportedMappings[mapping] == null) { exportedMappings.Add(mapping, mapping); if (mapping is EnumMapping) { ExportEnum((EnumMapping)mapping); } else if (mapping is StructMapping) { ExportStruct((StructMapping)mapping); } else if (mapping is ArrayMapping) { EnsureTypesExported(((ArrayMapping)mapping).Elements); } } }
private void WriteElement(ref object o, CollectionMember collectionMember, ElementAccessor element, ChoiceIdentifierAccessor choice, bool checkSpecified, bool checkForNull, bool readOnly, string defaultNamespace, object masterObject = null) { object value = null; if (element.Mapping is ArrayMapping) { WriteArray(ref value, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, defaultNamespace); } else if (element.Mapping is NullableMapping) { value = WriteNullableMethod((NullableMapping)element.Mapping, true, defaultNamespace); } else if (!element.Mapping.IsSoap && (element.Mapping is PrimitiveMapping)) { if (element.IsNullable && ReadNull()) { if (element.Mapping.TypeDesc.IsValueType) { value = ReflectionCreateObject(element.Mapping.TypeDesc.Type); } else { value = null; } } else if ((element.Default != null && !Globals.IsDBNullValue(element.Default) && element.Mapping.TypeDesc.IsValueType) && (Reader.IsEmptyElement)) { Reader.Skip(); } else { if (element.Mapping.TypeDesc == QnameTypeDesc) { value = ReadElementQualifiedName(); } else { if (element.Mapping.TypeDesc.FormatterName == "ByteArrayBase64") { value = ToByteArrayBase64(false); } else if (element.Mapping.TypeDesc.FormatterName == "ByteArrayHex") { value = ToByteArrayHex(false); } else { Func <string> readFunc = () => Reader.ReadElementContentAsString(); value = WritePrimitive(element.Mapping, readFunc); } } } } else if (element.Mapping is StructMapping || (element.Mapping.IsSoap && element.Mapping is PrimitiveMapping)) { TypeMapping mapping = element.Mapping; if (mapping.IsSoap) { throw new PlatformNotSupportedException(); } else { if (checkForNull && o == null) { Reader.Skip(); } else { value = WriteStructMethod( mapping: (StructMapping)mapping, isNullable: mapping.TypeDesc.IsNullable && element.IsNullable, checkType: true, defaultNamespace: defaultNamespace ); } } } else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; switch (special.TypeDesc.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; if (isDoc) { value = ReadXmlDocument(!element.Any); } else { value = ReadXmlNode(!element.Any); } break; case TypeKind.Serializable: SerializableMapping sm = (SerializableMapping)element.Mapping; // check to see if we need to do the derivation bool flag = true; if (sm.DerivedMappings != null) { XmlQualifiedName tser = GetXsiType(); if (tser == null || QNameEqual(tser, sm.XsiType.Name, sm.XsiType.Namespace, defaultNamespace)) { } else { flag = false; } } if (flag) { bool isWrappedAny = !element.Any && IsWildcard(sm); value = ReadSerializable((IXmlSerializable)ReflectionCreateObject(sm.TypeDesc.Type), isWrappedAny); } if (sm.DerivedMappings != null) { // #10587: To Support SpecialMapping Types Having DerivedMappings throw new NotImplementedException("sm.DerivedMappings != null"); //WriteDerivedSerializable(sm, sm, source, isWrappedAny); //WriteUnknownNode("UnknownNode", "null", null, true); } break; default: throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlInternalError)); } if (choice != null && masterObject != null) { foreach (var name in choice.MemberIds) { if (name == element.Name) { object choiceValue = Enum.Parse(choice.Mapping.TypeDesc.Type, name); SetOrAddValueToMember(masterObject, choiceValue, choice.MemberInfo); break; } } } if (collectionMember != null) { collectionMember.Add(value); } else { o = value; } }
private TypeMapping ImportTypeMapping(TypeModel model, string dataType, RecursionLimiter limiter) { if (dataType.Length > 0) { if (!model.TypeDesc.IsPrimitive) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "SoapElementAttribute.DataType")); } TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "SoapElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); } if (model.TypeDesc.FullName != td.FullName) { throw new InvalidOperationException(SR.Format(SR.XmlDataTypeMismatch, dataType, "SoapElementAttribute.DataType", model.TypeDesc.FullName)); } } SoapAttributes a = GetAttributes(model.Type); if ((a.GetSoapFlags() & ~SoapAttributeFlags.Type) != 0) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidTypeAttributes, model.Type.FullName)); } switch (model.TypeDesc.Kind) { case TypeKind.Enum: return(ImportEnumMapping((EnumModel)model)); case TypeKind.Primitive: return(ImportPrimitiveMapping((PrimitiveModel)model, dataType)); case TypeKind.Array: case TypeKind.Collection: case TypeKind.Enumerable: return(ImportArrayLikeMapping((ArrayModel)model, limiter)); case TypeKind.Root: case TypeKind.Class: case TypeKind.Struct: if (model.TypeDesc.IsOptionalValue) { TypeDesc baseTypeDesc = model.TypeDesc.BaseTypeDesc; SoapAttributes baseAttributes = GetAttributes(baseTypeDesc.Type); string typeNs = _defaultNs; if (baseAttributes.SoapType != null && baseAttributes.SoapType.Namespace != null) { typeNs = baseAttributes.SoapType.Namespace; } TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc.Name : dataType; TypeMapping baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); if (baseMapping == null) { baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type), dataType, limiter); } return(CreateNullableMapping(baseMapping, model.TypeDesc.Type)); } else { return(ImportStructLikeMapping((StructModel)model, limiter)); } default: throw new NotSupportedException(SR.Format(SR.XmlUnsupportedSoapTypeKind, model.TypeDesc.FullName)); } }
internal void AddTypeMapping(TypeMapping typeMapping) { this.typeMappings.Add(typeMapping); }
internal virtual void GenerateMethod(TypeMapping mapping) { }
// UNDONE Nullable private void SetArrayMappingType(ArrayMapping mapping) { bool useDefaultNs = false; string itemTypeName; string itemTypeNamespace; TypeMapping itemTypeMapping; if (mapping.Elements.Length == 1) { itemTypeMapping = mapping.Elements[0].Mapping; } else { itemTypeMapping = null; } if (itemTypeMapping is EnumMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else if (itemTypeMapping is PrimitiveMapping) { itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; itemTypeName = itemTypeMapping.TypeDesc.DataType.Name; useDefaultNs = true; } else if (itemTypeMapping is StructMapping) { if (itemTypeMapping.TypeDesc.IsRoot) { itemTypeNamespace = XmlSchema.Namespace; itemTypeName = Soap.UrType; useDefaultNs = true; } else { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } } else if (itemTypeMapping is ArrayMapping) { itemTypeNamespace = itemTypeMapping.Namespace; itemTypeName = itemTypeMapping.TypeName; } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName)); } itemTypeName = CodeIdentifier.MakePascal(itemTypeName); string uniqueName = "ArrayOf" + itemTypeName; string ns = useDefaultNs ? _defaultNs : itemTypeNamespace; int i = 1; TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) { ArrayMapping arrayMapping = (ArrayMapping)existingMapping; if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements)) { break; } } // need to re-name the mapping uniqueName = itemTypeName + i.ToString(CultureInfo.InvariantCulture); existingMapping = (TypeMapping)_types[uniqueName, ns]; i++; } mapping.Namespace = ns; mapping.TypeName = uniqueName; }
internal string ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap && (this.generatedMethods[mapping] == null)) { this.referencedMethods = this.EnsureArrayIndex(this.referencedMethods, this.references); this.referencedMethods[this.references++] = mapping; } return (string) this.methodNames[mapping]; }
void AddDefaultValueAttribute(CodeMemberField field, CodeAttributeDeclarationCollection metadata, object defaultValue, TypeMapping mapping, CodeCommentStatementCollection comments, TypeDesc memberTypeDesc, Accessor accessor, CodeConstructor ctor) { string attributeName = accessor.IsFixed ? "fixed" : "default"; if (!memberTypeDesc.HasDefaultSupport) { if (comments != null && defaultValue is string) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); // do not generate intializers for the user prefered types if they do not have default capability AddWarningComment(comments, Res.GetString(Res.XmlDropAttributeValue, attributeName, mapping.TypeName, defaultValue.ToString())); } return; } if (memberTypeDesc.IsArrayLike && accessor is ElementAccessor) { if (comments != null && defaultValue is string) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); // do not generate intializers for array-like types AddWarningComment(comments, Res.GetString(Res.XmlDropArrayAttributeValue, attributeName, defaultValue.ToString(), ((ElementAccessor)accessor).Name)); } return; } if (mapping.TypeDesc.IsMappedType && field != null && defaultValue is string) { SchemaImporterExtension extension = mapping.TypeDesc.ExtendedType.Extension; CodeExpression init = extension.ImportDefaultValue((string)defaultValue, mapping.TypeDesc.FullName); if (init != null) { if (ctor != null) { AddInitializationStatement(ctor, field, init); } else { field.InitExpression = extension.ImportDefaultValue((string)defaultValue, mapping.TypeDesc.FullName); } } if (comments != null) { DropDefaultAttribute(accessor, comments, mapping.TypeDesc.FullName); if (init == null) { AddWarningComment(comments, Res.GetString(Res.XmlNotKnownDefaultValue, extension.GetType().FullName, attributeName, (string)defaultValue, mapping.TypeName, mapping.Namespace)); } } return; } object value = null; if (defaultValue is string || defaultValue == null) { value = ImportDefault(mapping, (string)defaultValue); } if (value == null) return; if (!(mapping is PrimitiveMapping)) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); AddWarningComment(comments, Res.GetString(Res.XmlDropNonPrimitiveAttributeValue, attributeName, defaultValue.ToString())); return; } PrimitiveMapping pm = (PrimitiveMapping)mapping; if (comments != null && !pm.TypeDesc.HasDefaultSupport && pm.TypeDesc.IsMappedType) { // do not generate intializers for the user prefered types if they do not have default capability DropDefaultAttribute(accessor, comments, pm.TypeDesc.FullName); return; } if (value == DBNull.Value) { if (comments != null) { AddWarningComment(comments, Res.GetString(Res.XmlDropAttributeValue, attributeName, pm.TypeName, defaultValue.ToString())); } return; } CodeAttributeArgument[] arguments = null; CodeExpression initExpression = null; if (pm.IsList) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (value.GetType() != typeof(object[])) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value for list should be object[], not " + value.GetType().Name)); #endif object[] vals = (object[])value; CodeExpression[] initializers = new CodeExpression[vals.Length]; for (int i = 0; i < vals.Length; i++) { GetDefaultValueArguments(pm, vals[i], out initializers[i]); } initExpression = new CodeArrayCreateExpression(field.Type, initializers); } else { arguments = GetDefaultValueArguments(pm, value, out initExpression); } if (field != null) { if (ctor != null) { AddInitializationStatement(ctor, field, initExpression); } else { field.InitExpression = initExpression; } } if (arguments != null && pm.TypeDesc.HasDefaultSupport && accessor.IsOptional && !accessor.IsFixed) { // Add [DefaultValueAttribute] CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(DefaultValueAttribute).FullName, arguments); metadata.Add(attribute); } else if (comments != null) { DropDefaultAttribute(accessor, comments, memberTypeDesc.FullName); } }
static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); if (mapping.TypeDesc.Kind == TypeKind.Node) { element.Any = true; } else { element.Name = Accessor.EscapeName(mapping.TypeName, false); element.Namespace = ns; } element.Mapping = mapping; return element; }
static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping mapping) { if (mapping is NullableMapping) return; if (mapping is SerializableMapping) return; if (isNullable && !typeDesc.IsNullable) throw new InvalidOperationException(Res.GetString(Res.XmlInvalidIsNullable, typeDesc.FullName)); }
private void CheckForDuplicateType(TypeMapping mapping, string newNamespace) { if (!mapping.IsAnonymousType) { string typeName = mapping.TypeName; XmlSchema schema = this.schemas[newNamespace]; if (schema != null) { foreach (XmlSchemaType type in schema.Items) { if ((type != null) && (type.Name == typeName)) { throw new InvalidOperationException(Res.GetString("XmlDuplicateTypeName", new object[] { typeName, newNamespace })); } } } } }
static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); bool isAny = mapping.TypeDesc.Kind == TypeKind.Node; if (!isAny && mapping is SerializableMapping) { isAny = ((SerializableMapping)mapping).IsAny; } if (isAny) { element.Any = true; } else { element.Name = mapping.DefaultElementName; element.Namespace = ns; } element.Mapping = mapping; return element; }
internal string ReferenceMapping(TypeMapping mapping) { if (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } string methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; }
void CheckForDuplicateType(TypeMapping mapping, string newNamespace) { if (mapping.IsAnonymousType) return; string newTypeName = mapping.TypeName; XmlSchema schema = schemas[newNamespace]; if (schema != null){ foreach (XmlSchemaObject o in schema.Items) { XmlSchemaType type = o as XmlSchemaType; if ( type != null && type.Name == newTypeName) throw new InvalidOperationException(Res.GetString(Res.XmlDuplicateTypeName, newTypeName, newNamespace)); } } }
void WriteCreateMapping(TypeMapping mapping, string local) { string fullTypeName = mapping.TypeDesc.CSharpName; bool useReflection = mapping.TypeDesc.UseReflection; bool ctorInaccessible = mapping.TypeDesc.CannotNew; Writer.Write(useReflection ? "object" : fullTypeName); Writer.Write(" "); Writer.Write(local); Writer.WriteLine(";"); if (ctorInaccessible) { Writer.WriteLine("try {"); Writer.Indent++; } Writer.Write(local); Writer.Write(" = "); Writer.Write(RaCodeGen.GetStringForCreateInstance(fullTypeName, useReflection, mapping.TypeDesc.CannotNew, true)); Writer.WriteLine(";"); if (ctorInaccessible) { WriteCatchException(typeof(MissingMethodException)); Writer.Indent++; Writer.Write("throw CreateInaccessibleConstructorException("); WriteQuotedCSharpString(fullTypeName); Writer.WriteLine(");"); WriteCatchException(typeof(SecurityException)); Writer.Indent++; Writer.Write("throw CreateCtorHasSecurityException("); WriteQuotedCSharpString(fullTypeName); Writer.WriteLine(");"); Writer.Indent--; Writer.WriteLine("}"); } }
static internal string ExportDefaultValue(TypeMapping mapping, object value) { if (!(mapping is PrimitiveMapping)) // should throw, but it will be a breaking change; return null; if (value == null || value == DBNull.Value) return null; if (mapping is EnumMapping) { EnumMapping em = (EnumMapping)mapping; #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (value.GetType() != typeof(string)) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), value.GetType().FullName))); #endif // check the validity of the value ConstantMapping[] c = em.Constants; if (em.IsFlags) { string[] names = new string[c.Length]; long[] ids = new long[c.Length]; Hashtable values = new Hashtable(); for (int i = 0; i < c.Length; i++) { names[i] = c[i].XmlName; ids[i] = 1 << i; values.Add(c[i].Name, ids[i]); } long val = XmlCustomFormatter.ToEnum((string)value, values, em.TypeName, false); return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc.FullName) : null; } else { for (int i = 0; i < c.Length; i++) { if (c[i].Name == (string)value) { return c[i].XmlName; } } return null; // unknown value } } PrimitiveMapping pm = (PrimitiveMapping)mapping; if (!pm.TypeDesc.HasCustomFormatter) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (pm.TypeDesc.Type == null) { throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Mapping for " + pm.TypeDesc.Name + " missing type property")); } #endif if (pm.TypeDesc.FormatterName == "String") return (string)value; Type formatter = typeof(XmlConvert); System.Reflection.MethodInfo format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type }); if (format != null) return (string)format.Invoke(formatter, new Object[] {value}); } else { string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName); if (defaultValue == null) throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name)); return defaultValue; } throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name)); }
TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, b, index); return b; }
internal string ReferenceMapping(TypeMapping mapping) { if (generatedMethods[mapping] == null) { referencedMethods = EnsureArrayIndex(referencedMethods, references); referencedMethods[references++] = mapping; } return (string)methodNames[mapping]; }
NullableMapping CreateNullableMapping(TypeMapping baseMapping, TypeDesc typeDesc) { TypeMapping existingMapping = (TypeMapping)types[typeDesc.Name, baseMapping.Namespace]; NullableMapping mapping; if (existingMapping != null) { if (existingMapping is NullableMapping) { mapping = (NullableMapping)existingMapping; if (mapping.BaseMapping is PrimitiveMapping && baseMapping is PrimitiveMapping) return mapping; else if (mapping.BaseMapping == baseMapping) { return mapping; } else { throw new InvalidOperationException(Res.GetString(Res.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); } } else if (!(baseMapping is PrimitiveMapping)){ throw new InvalidOperationException(Res.GetString(Res.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); mapping.BaseMapping = baseMapping; mapping.TypeDesc = typeDesc; mapping.TypeName = baseMapping.TypeName; mapping.Namespace = baseMapping.Namespace; mapping.IncludeInSchema = false; //baseMapping.IncludeInSchema; types.Add(typeDesc.Name, baseMapping.Namespace, mapping); typeScope.AddTypeMapping(mapping); return mapping; }
private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { TypeDesc typeDesc = mapping.TypeDesc; bool hasDefault = defaultValue != null && !Globals.IsDBNullValue(defaultValue) && mapping.TypeDesc.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { if (((EnumMapping)mapping).IsFlags) { var defaultEnumFlagValues = defaultValue.ToString().Split(null).Where((s) => !string.IsNullOrWhiteSpace(s)); string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues); if (o.ToString() == defaultEnumFlagString) return; } else { if (o.ToString() == defaultValue.ToString()) return; } } else { if (IsDefaultValue(mapping, o, defaultValue, isNullable)) { return; } } } XmlQualifiedName xmlQualifiedName = null; if (writeXsiType) { xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } string stringValue = null; bool hasValidStringValue = false; if (mapping is EnumMapping) { stringValue = WriteEnumMethod((EnumMapping)mapping, o); hasValidStringValue = true; } else { hasValidStringValue = WritePrimitiveValue(typeDesc, o, isElement, out stringValue); } if (hasValidStringValue) { if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString)) { if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw)) { WriteElementString(name, ns, stringValue, xmlQualifiedName); } else { WriteElementStringRaw(name, ns, stringValue, xmlQualifiedName); } } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral)) { if (hasRequirement(method, WritePrimitiveMethodRequirement.Raw)) { WriteNullableStringLiteral(name, ns, stringValue); } else { WriteNullableStringLiteralRaw(name, ns, stringValue); } } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { WriteAttribute(name, ns, stringValue); } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } } else if (o is byte[]) { byte[] a = (byte[])o; if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteElementString | WritePrimitiveMethodRequirement.Raw)) { WriteElementStringRaw(name, ns, FromByteArrayBase64(a)); } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteNullableStringLiteral | WritePrimitiveMethodRequirement.Raw)) { WriteNullableStringLiteralRaw(name, ns, FromByteArrayBase64(a)); } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { WriteAttribute(name, ns, a); } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } } else { // #10593: Add More Tests for Serialization Code Debug.Assert(false); } }
void WriteQualifiedNameElement(string name, string ns, object defaultValue, string source, bool nullable, bool IsSoap, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) { WriteCheckDefault(source, defaultValue, nullable); Writer.WriteLine(" {"); Writer.Indent++; } string suffix = IsSoap ? "Encoded" : "Literal"; Writer.Write(nullable ? ("WriteNullableQualifiedName" + suffix): "WriteElementQualifiedName"); Writer.Write("("); WriteQuotedCSharpString(name); if (ns != null) { Writer.Write(", "); WriteQuotedCSharpString(ns); } Writer.Write(", "); Writer.Write(source); if (IsSoap) { Writer.Write(", new System.Xml.XmlQualifiedName("); WriteQuotedCSharpString(mapping.TypeName); Writer.Write(", "); WriteQuotedCSharpString(mapping.Namespace); Writer.Write(")"); } Writer.WriteLine(");"); if (hasDefault) { Writer.Indent--; Writer.WriteLine("}"); } }
private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable) { if (value is string && ((string)value).Length == 0) { string str = (string)o; return str == null || str.Length == 0; } else { return value.Equals(o); } }
void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type type){ string typeFullName = mapping.TypeDesc.CSharpName; if(mapping is StructMapping){ StructMapping structMapping = mapping as StructMapping; for (int i = 0; i < structMapping.Members.Length; i++) { MemberMapping member = structMapping.Members[i]; string memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, member.Name); if (member.CheckShouldPersist){ string memberName = "ShouldSerialize"+member.Name; memberVariable = WriteMethodInfo(typeFullName, typeVariable, memberName, false); } if (member.CheckSpecified != SpecifiedAccessor.None) { string memberName = member.Name+"Specified"; memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); } if (member.ChoiceIdentifier != null){ string memberName = member.ChoiceIdentifier.MemberName; memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); } } } else if (mapping is EnumMapping){ FieldInfo[] enumFields = type.GetFields(); for (int i = 0; i < enumFields.Length; i++) { WriteMemberInfo(type, typeFullName, typeVariable, enumFields[i].Name); } } }
internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods ![--_references];