Example #1
0
 CodeTypeMember CreateFieldMember(CodeTypeDeclaration codeClass, TypeData type, string name)
 {
     return(CreateFieldMember(codeClass, GetDomType(type, false), name, System.DBNull.Value, null, null));
 }
Example #2
0
        CodeTypeMember CreateFieldMember(CodeTypeDeclaration codeClass, CodeTypeReference type, string name, object defaultValue, TypeData defaultType, string documentation)
        {
            CodeMemberField codeField = null;
            CodeTypeMember  codeProp  = null;

            if ((options & CodeGenerationOptions.GenerateProperties) > 0)
            {
                string field = identifiers.AddUnique(CodeIdentifier.MakeCamel(name + "Field"), name);
                codeField            = new CodeMemberField(type, field);
                codeField.Attributes = MemberAttributes.Private;
                codeClass.Members.Add(codeField);

                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name       = name;
                prop.Type       = type;
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                codeProp        = prop;
                prop.HasGet     = prop.HasSet = true;

                CodeExpression ce = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field);
                prop.SetStatements.Add(new CodeAssignStatement(ce, new CodePropertySetValueReferenceExpression()));
                prop.GetStatements.Add(new CodeMethodReturnStatement(ce));
            }
            else
            {
                codeField            = new CodeMemberField(type, name);
                codeField.Attributes = MemberAttributes.Public;
                codeProp             = codeField;
            }

            if (defaultValue != System.DBNull.Value)
            {
                GenerateDefaultAttribute(codeField, codeProp, defaultType, defaultValue);
            }

            AddComments(codeProp, documentation);
            codeClass.Members.Add(codeProp);
            return(codeProp);
        }
Example #3
0
        protected override void GenerateArrayItemAttributes(CodeAttributeDeclarationCollection attributes, ListMap listMap, TypeData type, XmlTypeMapElementInfo ainfo, string defaultName, string defaultNamespace, int nestingLevel)
        {
            bool needsType = (listMap.ItemInfo.Count > 1) ||
                             (ainfo.TypeData.FullTypeName != type.FullTypeName && !listMap.IsMultiArray);

            CodeAttributeDeclaration att = new CodeAttributeDeclaration("Mpd.Xml.Serialization.XmlArrayItem");

            if (ainfo.ElementName != defaultName)
            {
                att.Arguments.Add(GetArg("ElementName", ainfo.ElementName));
            }
            if (ainfo.Namespace != defaultNamespace && ainfo.Namespace != XmlSchema.Namespace)
            {
                att.Arguments.Add(GetArg("Namespace", ainfo.Namespace));
            }
            if (needsType)
            {
                att.Arguments.Add(GetTypeArg("Type", ainfo.TypeData.FullTypeName));
            }
            if (!ainfo.IsNullable)
            {
                att.Arguments.Add(GetArg("IsNullable", false));
            }
            if (ainfo.Form == XmlSchemaForm.Unqualified)
            {
                att.Arguments.Add(MapCodeGenerator.GetEnumArg("Form", "System.Xml.Schema.XmlSchemaForm", ainfo.Form.ToString()));
            }
            if (att.Arguments.Count > 0 && nestingLevel > 0)
            {
                att.Arguments.Add(GetArg("NestingLevel", nestingLevel));
            }

            if (att.Arguments.Count > 0)
            {
                attributes.Add(att);
            }
        }
Example #4
0
        static TypeTranslator()
        {
            nameCache           = new Hashtable();
            primitiveArrayTypes = Hashtable.Synchronized(new Hashtable());

#if !TARGET_JVM
            nameCache = Hashtable.Synchronized(nameCache);
#endif
            // XSD Types with direct map to CLR types

            nameCache.Add(typeof(bool), new TypeData(typeof(bool), "boolean", true));
            nameCache.Add(typeof(short), new TypeData(typeof(short), "short", true));
            nameCache.Add(typeof(ushort), new TypeData(typeof(ushort), "unsignedShort", true));
            nameCache.Add(typeof(int), new TypeData(typeof(int), "int", true));
            nameCache.Add(typeof(uint), new TypeData(typeof(uint), "unsignedInt", true));
            nameCache.Add(typeof(long), new TypeData(typeof(long), "long", true));
            nameCache.Add(typeof(ulong), new TypeData(typeof(ulong), "unsignedLong", true));
            nameCache.Add(typeof(float), new TypeData(typeof(float), "float", true));
            nameCache.Add(typeof(double), new TypeData(typeof(double), "double", true));
            nameCache.Add(typeof(DateTime), new TypeData(typeof(DateTime), "dateTime", true));                  // TODO: timeInstant, Xml date, xml time
            nameCache.Add(typeof(decimal), new TypeData(typeof(decimal), "decimal", true));
            nameCache.Add(typeof(XmlQualifiedName), new TypeData(typeof(XmlQualifiedName), "QName", true));
            nameCache.Add(typeof(string), new TypeData(typeof(string), "string", true));
            XmlSchemaPatternFacet guidFacet = new XmlSchemaPatternFacet();
            guidFacet.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
            nameCache.Add(typeof(Guid), new TypeData(typeof(Guid), "guid", true, (TypeData)nameCache[typeof(string)], guidFacet));
            nameCache.Add(typeof(byte), new TypeData(typeof(byte), "unsignedByte", true));
            nameCache.Add(typeof(sbyte), new TypeData(typeof(sbyte), "byte", true));
            nameCache.Add(typeof(char), new TypeData(typeof(char), "char", true, (TypeData)nameCache[typeof(ushort)], null));
            nameCache.Add(typeof(object), new TypeData(typeof(object), "anyType", false));
            nameCache.Add(typeof(byte[]), new TypeData(typeof(byte[]), "base64Binary", true));
            nameCache.Add(typeof(XmlNode), new TypeData(typeof(XmlNode), "XmlNode", false));
            nameCache.Add(typeof(XmlElement), new TypeData(typeof(XmlElement), "XmlElement", false));

            primitiveTypes = new Hashtable();
            ICollection types = nameCache.Values;
            foreach (TypeData td in types)
            {
                primitiveTypes.Add(td.XmlType, td);
            }

            // Additional XSD types

            primitiveTypes.Add("date", new TypeData(typeof(DateTime), "date", true));                   // TODO: timeInstant
            primitiveTypes.Add("time", new TypeData(typeof(DateTime), "time", true));
            primitiveTypes.Add("timePeriod", new TypeData(typeof(DateTime), "timePeriod", true));
            primitiveTypes.Add("gDay", new TypeData(typeof(string), "gDay", true));
            primitiveTypes.Add("gMonthDay", new TypeData(typeof(string), "gMonthDay", true));
            primitiveTypes.Add("gYear", new TypeData(typeof(string), "gYear", true));
            primitiveTypes.Add("gYearMonth", new TypeData(typeof(string), "gYearMonth", true));
            primitiveTypes.Add("month", new TypeData(typeof(DateTime), "month", true));
            primitiveTypes.Add("NMTOKEN", new TypeData(typeof(string), "NMTOKEN", true));
            primitiveTypes.Add("NMTOKENS", new TypeData(typeof(string), "NMTOKENS", true));
            primitiveTypes.Add("Name", new TypeData(typeof(string), "Name", true));
            primitiveTypes.Add("NCName", new TypeData(typeof(string), "NCName", true));
            primitiveTypes.Add("language", new TypeData(typeof(string), "language", true));
            primitiveTypes.Add("integer", new TypeData(typeof(string), "integer", true));
            primitiveTypes.Add("positiveInteger", new TypeData(typeof(string), "positiveInteger", true));
            primitiveTypes.Add("nonPositiveInteger", new TypeData(typeof(string), "nonPositiveInteger", true));
            primitiveTypes.Add("negativeInteger", new TypeData(typeof(string), "negativeInteger", true));
            primitiveTypes.Add("nonNegativeInteger", new TypeData(typeof(string), "nonNegativeInteger", true));
            primitiveTypes.Add("ENTITIES", new TypeData(typeof(string), "ENTITIES", true));
            primitiveTypes.Add("ENTITY", new TypeData(typeof(string), "ENTITY", true));
            primitiveTypes.Add("hexBinary", new TypeData(typeof(byte[]), "hexBinary", true));
            primitiveTypes.Add("ID", new TypeData(typeof(string), "ID", true));
            primitiveTypes.Add("IDREF", new TypeData(typeof(string), "IDREF", true));
            primitiveTypes.Add("IDREFS", new TypeData(typeof(string), "IDREFS", true));
            primitiveTypes.Add("NOTATION", new TypeData(typeof(string), "NOTATION", true));
            primitiveTypes.Add("token", new TypeData(typeof(string), "token", true));
            primitiveTypes.Add("normalizedString", new TypeData(typeof(string), "normalizedString", true));
            primitiveTypes.Add("anyURI", new TypeData(typeof(string), "anyURI", true));
            primitiveTypes.Add("base64", new TypeData(typeof(byte[]), "base64", true));
            primitiveTypes.Add("duration", new TypeData(typeof(string), "duration", true));

#if NET_2_0
            nullableTypes = Hashtable.Synchronized(new Hashtable());
            foreach (DictionaryEntry de in primitiveTypes)
            {
                TypeData td  = (TypeData)de.Value;
                TypeData ntd = new TypeData(td.Type, td.XmlType, true);
                ntd.IsNullable = true;
                nullableTypes.Add(de.Key, ntd);
            }
#endif
        }
Example #5
0
 protected virtual void GenerateArrayItemAttributes(CodeAttributeDeclarationCollection attributes, ListMap listMap, TypeData type, XmlTypeMapElementInfo ainfo, string defaultName, string defaultNamespace, int nestingLevel)
 {
 }
Example #6
0
        internal XmlSerializableMapping(string elementName, string ns, TypeData typeData, string xmlType, string xmlTypeNamespace)
            : base(elementName, ns, typeData, xmlType, xmlTypeNamespace)
        {
#if NET_2_0
            XmlSchemaProviderAttribute schemaProvider = (XmlSchemaProviderAttribute)Attribute.GetCustomAttribute(typeData.Type, typeof(XmlSchemaProviderAttribute));

            if (schemaProvider != null)
            {
                string     method = schemaProvider.MethodName;
                MethodInfo mi     = typeData.Type.GetMethod(method, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                if (mi == null)
                {
                    throw new InvalidOperationException(String.Format("Type '{0}' must implement public static method '{1}'", typeData.Type, method));
                }
                if (!typeof(XmlQualifiedName).IsAssignableFrom(mi.ReturnType) &&
                    // LAMESPEC: it is undocumented. (We don't have to tell users about it in the error message.)
                    // Also do not add such a silly compatibility test to assert that it does not raise an error.
                    !typeof(XmlSchemaComplexType).IsAssignableFrom(mi.ReturnType))
                {
                    throw new InvalidOperationException(String.Format("Method '{0}' indicated by XmlSchemaProviderAttribute must have its return type as XmlQualifiedName", method));
                }
                XmlSchemaSet xs     = new XmlSchemaSet();
                object       retVal = mi.Invoke(null, new object [] { xs });
                _schemaTypeName = XmlQualifiedName.Empty;
                if (retVal == null)
                {
                    return;
                }

                if (retVal is XmlSchemaComplexType)
                {
                    _schemaType = (XmlSchemaComplexType)retVal;
                    if (!_schemaType.QualifiedName.IsEmpty)
                    {
                        _schemaTypeName = _schemaType.QualifiedName;
                    }
                    else
                    {
                        _schemaTypeName = new XmlQualifiedName(xmlType, xmlTypeNamespace);
                    }
                }
                else if (retVal is XmlQualifiedName)
                {
                    _schemaTypeName = (XmlQualifiedName)retVal;
                }
                else
                {
                    throw new InvalidOperationException(
                              String.Format("Method {0}.{1}() specified by XmlSchemaProviderAttribute has invalid signature: return type must be compatible with System.Xml.XmlQualifiedName.", typeData.Type.Name, method));
                }

                // defaultNamespace at XmlReflectionImporter takes precedence for Namespace, but not for XsdTypeNamespace.
                UpdateRoot(new XmlQualifiedName(_schemaTypeName.Name, Namespace ?? _schemaTypeName.Namespace));
                XmlTypeNamespace = _schemaTypeName.Namespace;
                XmlType          = _schemaTypeName.Name;

                if (!_schemaTypeName.IsEmpty && xs.Count > 0)
                {
                    XmlSchema [] schemas = new XmlSchema [xs.Count];
                    xs.CopyTo(schemas, 0);
                    _schema = schemas [0];
                }

                return;
            }
#endif
            IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(typeData.Type, true);
#if NET_2_0
            try {
                _schema = serializable.GetSchema();
            } catch (Exception) {
                // LAMESPEC: .NET has a bad exception catch and swallows it silently.
            }
#else
            _schema = serializable.GetSchema();
#endif
            if (_schema != null)
            {
                if (_schema.Id == null || _schema.Id.Length == 0)
                {
                    throw new InvalidOperationException("Schema Id is missing. The schema returned from " + typeData.Type.FullName + ".GetSchema() must have an Id.");
                }
            }
        }
        private XmlTypeMapMember CreateMapMember(XmlReflectionMember rmember, string defaultNamespace)
        {
            XmlTypeMapMember mapMember;
            SoapAttributes   atts     = rmember.SoapAttributes;
            TypeData         typeData = TypeTranslator.GetTypeData(rmember.MemberType);

            if (atts.SoapAttribute != null)
            {
                // An attribute

                if (typeData.SchemaType != SchemaTypes.Enum && typeData.SchemaType != SchemaTypes.Primitive)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                                      "Cannot serialize member '{0}' of type {1}. " +
                                                                      "SoapAttribute cannot be used to encode complex types.",
                                                                      rmember.MemberName, typeData.FullTypeName));
                }

                if (atts.SoapElement != null)
                {
                    throw new Exception("SoapAttributeAttribute and SoapElementAttribute cannot be applied to the same member");
                }

                XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute();
                if (atts.SoapAttribute.AttributeName.Length == 0)
                {
                    mapAttribute.AttributeName = XmlConvert.EncodeLocalName(rmember.MemberName);
                }
                else
                {
                    mapAttribute.AttributeName = XmlConvert.EncodeLocalName(atts.SoapAttribute.AttributeName);
                }

                mapAttribute.Namespace = (atts.SoapAttribute.Namespace != null) ? atts.SoapAttribute.Namespace : "";
                if (typeData.IsComplexType)
                {
                    mapAttribute.MappedType = ImportTypeMapping(typeData.Type, defaultNamespace);
                }

                typeData  = TypeTranslator.GetTypeData(rmember.MemberType, atts.SoapAttribute.DataType);
                mapMember = mapAttribute;
                mapMember.DefaultValue = GetDefaultValue(typeData, atts.SoapDefaultValue);
            }
            else
            {
                if (typeData.SchemaType == SchemaTypes.Array)
                {
                    mapMember = new XmlTypeMapMemberList();
                }
                else
                {
                    mapMember = new XmlTypeMapMemberElement();
                }

                if (atts.SoapElement != null && atts.SoapElement.DataType.Length != 0)
                {
                    typeData = TypeTranslator.GetTypeData(rmember.MemberType, atts.SoapElement.DataType);
                }

                // Creates an ElementInfo that identifies the element
                XmlTypeMapElementInfoList infoList = new XmlTypeMapElementInfoList();
                XmlTypeMapElementInfo     elem     = new XmlTypeMapElementInfo(mapMember, typeData);

                elem.ElementName = XmlConvert.EncodeLocalName((atts.SoapElement != null && atts.SoapElement.ElementName.Length != 0) ? atts.SoapElement.ElementName : rmember.MemberName);
                elem.Namespace   = string.Empty;
                elem.IsNullable  = (atts.SoapElement != null) ? atts.SoapElement.IsNullable : false;
                if (typeData.IsComplexType)
                {
                    elem.MappedType = ImportTypeMapping(typeData.Type, defaultNamespace);
                }

                infoList.Add(elem);
                ((XmlTypeMapMemberElement)mapMember).ElementInfo = infoList;
            }

            mapMember.TypeData      = typeData;
            mapMember.Name          = rmember.MemberName;
            mapMember.IsReturnValue = rmember.IsReturnValue;
            return(mapMember);
        }
Example #8
0
        protected virtual void GenerateDefaultAttribute(CodeMemberField internalField, CodeTypeMember externalField, TypeData typeData, object defaultValue)
        {
            if (typeData.Type == null)
            {
                // It must be an enumeration defined in the schema.
                if (typeData.SchemaType != SchemaTypes.Enum)
                {
                    throw new InvalidOperationException("Type " + typeData.TypeName + " not supported");
                }

                IFormattable defaultValueFormattable = defaultValue as IFormattable;
                CodeFieldReferenceExpression fref    = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(GetDomType(typeData, false)), defaultValueFormattable != null ? defaultValueFormattable.ToString(null, CultureInfo.InvariantCulture) : defaultValue.ToString());
                CodeAttributeArgument        arg     = new CodeAttributeArgument(fref);
                AddCustomAttribute(externalField, "System.ComponentModel.DefaultValue", arg);
                //internalField.InitExpression = fref;
            }
            else
            {
                AddCustomAttribute(externalField, "System.ComponentModel.DefaultValue", GetArg(defaultValue));
                //internalField.InitExpression = new CodePrimitiveExpression (defaultValue);
            }
        }
        XmlTypeMapping ImportClassMapping(Type type, string defaultNamespace)
        {
            TypeData typeData = TypeTranslator.GetTypeData(type);

            return(ImportClassMapping(typeData, defaultNamespace));
        }
        XmlTypeMapping ImportClassMapping(TypeData typeData, string defaultNamespace)
        {
            Type type = typeData.Type;

            if (type.IsValueType)
            {
                throw CreateStructException(type);
            }

            if (type == typeof(object))
            {
                defaultNamespace = XmlSchema.Namespace;
            }

            ReflectionHelper.CheckSerializableType(type, false);
            XmlTypeMapping map = helper.GetRegisteredClrType(type, GetTypeNamespace(typeData, defaultNamespace));

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

            map = CreateTypeMapping(typeData, null, defaultNamespace);
            helper.RegisterClrType(map, type, map.Namespace);
            map.MultiReferenceType = true;

            ClassMap classMap = new ClassMap();

            map.ObjectMap = classMap;

            // Import members

            ICollection members = GetReflectionMembers(type);

            foreach (XmlReflectionMember rmember in members)
            {
                if (rmember.SoapAttributes.SoapIgnore)
                {
                    continue;
                }
                classMap.AddMember(CreateMapMember(rmember, defaultNamespace));
            }

            // Import included classes

            SoapIncludeAttribute[] includes = (SoapIncludeAttribute[])type.GetCustomAttributes(typeof(SoapIncludeAttribute), false);
            for (int n = 0; n < includes.Length; n++)
            {
                Type includedType = includes[n].Type;
                ImportTypeMapping(includedType);
            }

            if (type == typeof(object) && includedTypes != null)
            {
                foreach (Type intype in includedTypes)
                {
                    map.DerivedTypes.Add(ImportTypeMapping(intype));
                }
            }

            // Register inheritance relations

            if (type.BaseType != null)
            {
                XmlTypeMapping bmap = ImportClassMapping(type.BaseType, defaultNamespace);

                if (type.BaseType != typeof(object))
                {
                    map.BaseMap = bmap;
                }

                // At this point, derived classes of this map must be already registered

                RegisterDerivedMap(bmap, map);
            }

            return(map);
        }
Example #11
0
        protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType, bool suppressReference, bool isNullable)
        {
            if (o == null)
            {
                if (isNullable)
                {
                    WriteNullTagEncoded(n, ns);
                }
                return;
            }

            WriteStartElement(n, ns, true);

            CheckReferenceQueue();

            if (callbacks != null && callbacks.ContainsKey(o.GetType()))
            {
                WriteCallbackInfo info = (WriteCallbackInfo)callbacks[o.GetType()];
                if (o.GetType().IsEnum)
                {
                    info.Callback(o);
                }
                else if (suppressReference)
                {
                    Writer.WriteAttributeString("id", GetId(o, false));
                    if (ambientType != o.GetType())
                    {
                        WriteXsiType(info.TypeName, info.TypeNs);
                    }
                    info.Callback(o);
                }
                else
                {
                    if (!AlreadyQueued(o))
                    {
                        referencedElements.Enqueue(o);
                    }
                    Writer.WriteAttributeString("href", "#" + GetId(o, true));
                }
            }
            else
            {
                // Must be a primitive type or array of primitives
                TypeData td = TypeTranslator.GetTypeData(o.GetType());
                if (td.SchemaType == SchemaTypes.Primitive)
                {
                    WriteXsiType(td.XmlType, XmlSchema.Namespace);
                    Writer.WriteString(XmlCustomFormatter.ToXmlString(td, o));
                }
                else if (IsPrimitiveArray(td))
                {
                    if (!AlreadyQueued(o))
                    {
                        referencedElements.Enqueue(o);
                    }
                    Writer.WriteAttributeString("href", "#" + GetId(o, true));
                }
                else
                {
                    throw new InvalidOperationException("Invalid type: " + o.GetType().FullName);
                }
            }

            WriteEndElement();
        }
Example #12
0
 internal TypeData(string typeName, string fullTypeName, string xmlType, SchemaTypes schemaType, TypeData listItemTypeData)
 {
     this.elementName          = xmlType;
     this.typeName             = typeName;
     this.fullTypeName         = fullTypeName.Replace('+', '.');
     this.listItemTypeData     = listItemTypeData;
     this.sType                = schemaType;
     this.hasPublicConstructor = true;
 }
Example #13
0
        protected override void GenerateTextElementAttribute(CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, TypeData defaultType)
        {
            CodeAttributeDeclaration uatt = new CodeAttributeDeclaration("Mpd.Xml.Serialization.XmlTextAttribute");

            if (einfo.TypeData.FullTypeName != defaultType.FullTypeName)
            {
                uatt.Arguments.Add(GetTypeArg("Type", einfo.TypeData.FullTypeName));
            }
            attributes.Add(uatt);
        }
Example #14
0
        public void AddArrayItemAttributes(CodeAttributeDeclarationCollection attributes, ListMap listMap, TypeData type, string defaultNamespace, int nestingLevel)
        {
            foreach (XmlTypeMapElementInfo ainfo in listMap.ItemInfo)
            {
                string defaultName;
                if (ainfo.MappedType != null)
                {
                    defaultName = ainfo.MappedType.ElementName;
                }
                else
                {
                    defaultName = ainfo.TypeData.XmlType;
                }

                GenerateArrayItemAttributes(attributes, listMap, type, ainfo, defaultName, defaultNamespace, nestingLevel);
                if (ainfo.MappedType != null)
                {
                    if (!IsMapExported(ainfo.MappedType) && includeArrayTypes)
                    {
                        AddInclude(ainfo.MappedType);
                    }
                    ExportMapCode(ainfo.MappedType, false);
                }
            }

            if (listMap.IsMultiArray)
            {
                XmlTypeMapping nmap = listMap.NestedArrayMapping;
                AddArrayItemAttributes(attributes, (ListMap)nmap.ObjectMap, nmap.TypeData.ListItemTypeData, defaultNamespace, nestingLevel + 1);
            }
        }
Example #15
0
        protected override void GenerateElementInfoMember(CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName)
        {
            CodeAttributeDeclaration att = new CodeAttributeDeclaration("Mpd.Xml.Serialization.SoapElement");

            if (forceUseMemberName || einfo.ElementName != member.Name)
            {
                att.Arguments.Add(GetArg(einfo.ElementName));
            }
//			if (einfo.IsNullable) att.Arguments.Add (GetArg ("IsNullable", true));	MS seems to ignore this
            if (!TypeTranslator.IsDefaultPrimitiveTpeData(einfo.TypeData))
            {
                att.Arguments.Add(GetArg("DataType", einfo.TypeData.XmlType));
            }
            if (addAlwaysAttr || att.Arguments.Count > 0)
            {
                attributes.Add(att);
            }
        }
Example #16
0
 bool ExportExtraElementAttributes(CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, string defaultNamespace, TypeData defaultType)
 {
     if (einfo.IsTextElement)
     {
         GenerateTextElementAttribute(attributes, einfo, defaultType);
         return(true);
     }
     else if (einfo.IsUnnamedAnyElement)
     {
         GenerateUnnamedAnyElementAttribute(attributes, einfo, defaultNamespace);
         return(true);
     }
     return(false);
 }
Example #17
0
        public static TypeData GetTypeData(Type runtimeType, string xmlDataType)
        {
            Type type             = runtimeType;
            bool nullableOverride = false;

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

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

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

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

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

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

            typeData = new TypeData(type, name, false);
            if (nullableOverride)
            {
                typeData.IsNullable = true;
            }
#if TARGET_JVM
            dynamicCache[runtimeType] = typeData;
#else
            nameCache[runtimeType] = typeData;
#endif
            return(typeData);
        }
Example #18
0
 protected virtual void GenerateElementInfoMember(CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName)
 {
 }
Example #19
0
 public static bool IsDefaultPrimitiveTpeData(TypeData primType)
 {
     return(GetDefaultPrimitiveTypeData(primType) == primType);
 }
Example #20
0
 protected virtual void GenerateTextElementAttribute(CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, TypeData defaultType)
 {
 }
Example #21
0
        public static TypeData CreateCustomType(string typeName, string fullTypeName, string xmlType, SchemaTypes schemaType, TypeData listItemTypeData)
        {
            TypeData td = new TypeData(typeName, fullTypeName, xmlType, schemaType, listItemTypeData);

            return(td);
        }
        void ReadMembers(ClassMap map, object ob, bool isValueList, bool readByOrder)
        {
            // Reads attributes
            ReadAttributeMembers(map, ob, isValueList);

            if (!isValueList)
            {
                Reader.MoveToElement();
                if (Reader.IsEmptyElement)
                {
                    SetListMembersDefaults(map, ob, isValueList);
                    return;
                }

                Reader.ReadStartElement();
            }

            // Reads elements

            bool[] readFlag = new bool[(map.ElementMembers != null) ? map.ElementMembers.Count : 0];

            bool hasAnyReturnMember = (isValueList && _format == SerializationFormat.Encoded && map.ReturnMember != null);

            Reader.MoveToContent();

            int[]    indexes          = null;
            object[] flatLists        = null;
            object[] flatListsChoices = null;
            Fixup    fixup            = null;
            int      ind = 0;
            int      maxInd;

            if (readByOrder)
            {
                if (map.ElementMembers != null)
                {
                    maxInd = map.ElementMembers.Count;
                }
                else
                {
                    maxInd = 0;
                }
            }
            else
            {
                maxInd = int.MaxValue;
            }

            if (map.FlatLists != null)
            {
                indexes   = new int[map.FlatLists.Count];
                flatLists = new object[map.FlatLists.Count];
                foreach (XmlTypeMapMemberExpandable mem in map.FlatLists)
                {
                    if (IsReadOnly(mem, mem.TypeData, ob, isValueList))
                    {
                        flatLists [mem.FlatArrayIndex] = mem.GetValue(ob);
                    }
                    else if (mem.TypeData.Type.IsArray)
                    {
                        flatLists [mem.FlatArrayIndex] = InitializeList(mem.TypeData);
                    }
                    else
                    {
                        object list = mem.GetValue(ob);
                        if (list == null)
                        {
                            list = InitializeList(mem.TypeData);
                            SetMemberValue(mem, ob, list, isValueList);
                        }
                        flatLists [mem.FlatArrayIndex] = list;
                    }

                    if (mem.ChoiceMember != null)
                    {
                        if (flatListsChoices == null)
                        {
                            flatListsChoices = new object [map.FlatLists.Count];
                        }
                        flatListsChoices [mem.FlatArrayIndex] = InitializeList(mem.ChoiceTypeData);
                    }
                }
            }

            if (_format == SerializationFormat.Encoded && map.ElementMembers != null)
            {
                FixupCallbackInfo info = new FixupCallbackInfo(this, map, isValueList);
                fixup = new Fixup(ob, new XmlSerializationFixupCallback(info.FixupMembers), map.ElementMembers.Count);
                AddFixup(fixup);
            }

            while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && (ind < maxInd))
            {
                if (Reader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    XmlTypeMapElementInfo info;

                    if (readByOrder)
                    {
                        info = map.GetElement(ind++);
                    }
                    else if (hasAnyReturnMember)
                    {
                        info = (XmlTypeMapElementInfo)((XmlTypeMapMemberElement)map.ReturnMember).ElementInfo[0];
                        hasAnyReturnMember = false;
                    }
                    else
                    {
                        info = map.GetElement(Reader.LocalName, Reader.NamespaceURI);
                    }

                    if (info != null && !readFlag[info.Member.Index])
                    {
                        if (info.Member.GetType() == typeof(XmlTypeMapMemberList))
                        {
                            if (_format == SerializationFormat.Encoded && info.MultiReferenceType)
                            {
                                object list = ReadReferencingElement(out fixup.Ids[info.Member.Index]);
                                if (fixup.Ids[info.Member.Index] == null)                                       // Already read
                                {
                                    if (IsReadOnly(info.Member, info.TypeData, ob, isValueList))
                                    {
                                        throw CreateReadOnlyCollectionException(info.TypeData.FullTypeName);
                                    }
                                    else
                                    {
                                        SetMemberValue(info.Member, ob, list, isValueList);
                                    }
                                }
                                else if (!info.MappedType.TypeData.Type.IsArray)
                                {
                                    if (IsReadOnly(info.Member, info.TypeData, ob, isValueList))
                                    {
                                        list = GetMemberValue(info.Member, ob, isValueList);
                                    }
                                    else
                                    {
                                        list = CreateList(info.MappedType.TypeData.Type);
                                        SetMemberValue(info.Member, ob, list, isValueList);
                                    }
                                    AddFixup(new CollectionFixup(list, new XmlSerializationCollectionFixupCallback(FillList), fixup.Ids[info.Member.Index]));
                                    fixup.Ids[info.Member.Index] = null;                                        // The member already has the value, no further fix needed.
                                }
                            }
                            else
                            {
                                if (IsReadOnly(info.Member, info.TypeData, ob, isValueList))
                                {
                                    ReadListElement(info.MappedType, info.IsNullable, GetMemberValue(info.Member, ob, isValueList), false);
                                }
                                else if (info.MappedType.TypeData.Type.IsArray)
                                {
                                    object list = ReadListElement(info.MappedType, info.IsNullable, null, true);
                                    if (list != null || info.IsNullable)
                                    {
                                        SetMemberValue(info.Member, ob, list, isValueList);
                                    }
                                }
                                else
                                {
                                    // If the member already has a list, reuse that list. No need to create a new one.
                                    object list = GetMemberValue(info.Member, ob, isValueList);
                                    if (list == null)
                                    {
                                        list = CreateList(info.MappedType.TypeData.Type);
                                        SetMemberValue(info.Member, ob, list, isValueList);
                                    }
                                    ReadListElement(info.MappedType, info.IsNullable, list, true);
                                }
                            }
                            readFlag[info.Member.Index] = true;
                        }
                        else if (info.Member.GetType() == typeof(XmlTypeMapMemberFlatList))
                        {
                            XmlTypeMapMemberFlatList mem = (XmlTypeMapMemberFlatList)info.Member;
                            AddListValue(mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadObjectElement(info), !IsReadOnly(info.Member, info.TypeData, ob, isValueList));
                            if (mem.ChoiceMember != null)
                            {
                                AddListValue(mem.ChoiceTypeData, ref flatListsChoices [mem.FlatArrayIndex], indexes[mem.FlatArrayIndex] - 1, info.ChoiceValue, true);
                            }
                        }
                        else if (info.Member.GetType() == typeof(XmlTypeMapMemberAnyElement))
                        {
                            XmlTypeMapMemberAnyElement mem = (XmlTypeMapMemberAnyElement)info.Member;
                            if (mem.TypeData.IsListType)
                            {
                                AddListValue(mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadXmlNode(mem.TypeData.ListItemTypeData, false), true);
                            }
                            else
                            {
                                SetMemberValue(mem, ob, ReadXmlNode(mem.TypeData, false), isValueList);
                            }
                        }
                        else if (info.Member.GetType() == typeof(XmlTypeMapMemberElement))
                        {
                            object val;
                            readFlag[info.Member.Index] = true;
                            if (_format == SerializationFormat.Encoded)
                            {
                                if (info.Member.TypeData.SchemaType != SchemaTypes.Primitive)
                                {
                                    val = ReadReferencingElement(out fixup.Ids[info.Member.Index]);
                                }
                                else
                                {
                                    val = ReadReferencingElement(info.Member.TypeData.XmlType, System.Xml.Schema.XmlSchema.Namespace, out fixup.Ids[info.Member.Index]);
                                }

                                if (info.MultiReferenceType)
                                {
                                    if (fixup.Ids[info.Member.Index] == null)                                           // already read
                                    {
                                        SetMemberValue(info.Member, ob, val, isValueList);
                                    }
                                }
                                else if (val != null)
                                {
                                    SetMemberValue(info.Member, ob, val, isValueList);
                                }
                            }
                            else
                            {
                                SetMemberValue(info.Member, ob, ReadObjectElement(info), isValueList);
                                if (info.ChoiceValue != null)
                                {
                                    XmlTypeMapMemberElement imem = (XmlTypeMapMemberElement)info.Member;
                                    imem.SetChoice(ob, info.ChoiceValue);
                                }
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException("Unknown member type");
                        }
                    }
                    else if (map.DefaultAnyElementMember != null)
                    {
                        XmlTypeMapMemberAnyElement mem = map.DefaultAnyElementMember;
                        if (mem.TypeData.IsListType)
                        {
                            AddListValue(mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, ReadXmlNode(mem.TypeData.ListItemTypeData, false), true);
                        }
                        else
                        {
                            SetMemberValue(mem, ob, ReadXmlNode(mem.TypeData, false), isValueList);
                        }
                    }
                    else
                    {
                        ProcessUnknownElement(ob);
                    }
                }
                else if ((Reader.NodeType == System.Xml.XmlNodeType.Text || Reader.NodeType == System.Xml.XmlNodeType.CDATA) && map.XmlTextCollector != null)
                {
                    if (map.XmlTextCollector is XmlTypeMapMemberExpandable)
                    {
                        XmlTypeMapMemberExpandable mem   = (XmlTypeMapMemberExpandable)map.XmlTextCollector;
                        XmlTypeMapMemberFlatList   flatl = mem as XmlTypeMapMemberFlatList;
                        TypeData itype = (flatl == null) ? mem.TypeData.ListItemTypeData : flatl.ListMap.FindTextElement().TypeData;

                        object val = (itype.Type == typeof(string)) ? (object)Reader.ReadString() : (object)ReadXmlNode(itype, false);
                        AddListValue(mem.TypeData, ref flatLists[mem.FlatArrayIndex], indexes[mem.FlatArrayIndex]++, val, true);
                    }
                    else
                    {
                        XmlTypeMapMemberElement mem  = (XmlTypeMapMemberElement)map.XmlTextCollector;
                        XmlTypeMapElementInfo   info = (XmlTypeMapElementInfo)mem.ElementInfo [0];
                        if (info.TypeData.Type == typeof(string))
                        {
                            SetMemberValue(mem, ob, ReadString((string)GetMemberValue(mem, ob, isValueList)), isValueList);
                        }
                        else
                        {
                            SetMemberValue(mem, ob, GetValueFromXmlString(Reader.ReadString(), info.TypeData, info.MappedType), isValueList);
                        }
                    }
                }
                else
                {
                    UnknownNode(ob);
                }

                Reader.MoveToContent();
            }

            if (flatLists != null)
            {
                foreach (XmlTypeMapMemberExpandable mem in map.FlatLists)
                {
                    Object list = flatLists[mem.FlatArrayIndex];
                    if (mem.TypeData.Type.IsArray)
                    {
                        list = ShrinkArray((Array)list, indexes[mem.FlatArrayIndex], mem.TypeData.Type.GetElementType(), true);
                    }
                    if (!IsReadOnly(mem, mem.TypeData, ob, isValueList) && mem.TypeData.Type.IsArray)
                    {
                        SetMemberValue(mem, ob, list, isValueList);
                    }
                }
            }

            if (flatListsChoices != null)
            {
                foreach (XmlTypeMapMemberExpandable mem in map.FlatLists)
                {
                    Object list = flatListsChoices[mem.FlatArrayIndex];
                    if (list == null)
                    {
                        continue;
                    }
                    list = ShrinkArray((Array)list, indexes[mem.FlatArrayIndex], mem.ChoiceTypeData.Type.GetElementType(), true);
                    XmlTypeMapMember.SetValue(ob, mem.ChoiceMember, list);
                }
            }
            SetListMembersDefaults(map, ob, isValueList);
        }
Example #23
0
        protected override void GenerateElementInfoMember(CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName)
        {
            CodeAttributeDeclaration att = new CodeAttributeDeclaration("Mpd.Xml.Serialization.XmlElementAttribute");

            if (forceUseMemberName || einfo.ElementName != member.Name)
            {
                att.Arguments.Add(GetArg(einfo.ElementName));
            }
            if (einfo.TypeData.FullTypeName != defaultType.FullTypeName)
            {
                att.Arguments.Add(GetTypeArg("Type", einfo.TypeData.FullTypeName));
            }
            if (einfo.Namespace != defaultNamespace)
            {
                att.Arguments.Add(GetArg("Namespace", einfo.Namespace));
            }
            if (einfo.Form == XmlSchemaForm.Unqualified)
            {
                att.Arguments.Add(GetEnumArg("Form", "System.Xml.Schema.XmlSchemaForm", einfo.Form.ToString()));
            }
            if (einfo.IsNullable)
            {
                att.Arguments.Add(GetArg("IsNullable", true));
            }
            if (!TypeTranslator.IsDefaultPrimitiveTpeData(einfo.TypeData))
            {
                att.Arguments.Add(GetArg("DataType", einfo.TypeData.XmlType));
            }
            if (addAlwaysAttr || att.Arguments.Count > 0)
            {
                attributes.Add(att);
            }
        }