public void ConstructorArgChecking()
 {
     var typeData = new TypeData(context, new TypeDataCache(context), GetType(), FudgeFieldNameConvention.Identity);
     Assert.Throws<ArgumentNullException>(() => new DotNetSerializableSurrogate(null, typeData));
     Assert.Throws<ArgumentNullException>(() => new DotNetSerializableSurrogate(context, null));
     Assert.Throws<ArgumentOutOfRangeException>(() => new DotNetSerializableSurrogate(context, typeData));
 }
		public XmlTypeMapElementInfo (XmlTypeMapMember member, TypeData type)
		{
			_member = member;
			_type = type;
			if (type.IsValueType && type.IsNullable)
				_isNullable = true;
		}
Beispiel #3
0
		internal XmlTypeMapping(string elementName, string ns, TypeData typeData, string xmlType, string xmlTypeNamespace)
		: base (elementName, ns)
		{
			this.type = typeData;
			this.xmlType = xmlType;
			this.xmlTypeNamespace = xmlTypeNamespace;
		}
		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;
		}
 public void ConstructorArgChecking()
 {
     var typeData = new TypeData(context, new TypeDataCache(context), GetType(), FudgeFieldNameConvention.Identity);
     var surrogate = new SurrogateClass();
     var selector = new SurrogateSelector();
     Assert.Throws<ArgumentNullException>(() => new DotNetSerializationSurrogateSurrogate(null, typeData, surrogate, selector));
     Assert.Throws<ArgumentNullException>(() => new DotNetSerializationSurrogateSurrogate(context, null, surrogate, selector));
     Assert.Throws<ArgumentNullException>(() => new DotNetSerializationSurrogateSurrogate(context, typeData, null, selector));
 }
Beispiel #6
0
		public TypeData (Type type, string elementName, bool isPrimitive, TypeData mappedType, XmlSchemaPatternFacet facet)
		{
#if NET_2_0
			if (type.IsGenericTypeDefinition)
				throw new InvalidOperationException ("Generic type definition cannot be used in serialization. Only specific generic types can be used.");
#endif
			this.mappedType = mappedType;
			this.facet = facet;
			this.type = type;
			this.typeName = type.Name;
			this.fullTypeName = type.FullName.Replace ('+', '.');

			if (isPrimitive)
				sType = SchemaTypes.Primitive;
			else
			{
				if (type.IsEnum)
					sType = SchemaTypes.Enum;
				else if (typeof(IXmlSerializable).IsAssignableFrom (type))
					sType = SchemaTypes.XmlSerializable;
#if !MOONLIGHT
				else if (typeof (System.Xml.XmlNode).IsAssignableFrom (type))
					sType = SchemaTypes.XmlNode;
#endif
				else if (type.IsArray || typeof(IEnumerable).IsAssignableFrom (type))
					sType = SchemaTypes.Array;
				else
					sType = SchemaTypes.Class;
			}
			
			if (IsListType)
				this.elementName = TypeTranslator.GetArrayName (ListItemTypeData.XmlType);
			else
				this.elementName = elementName;

			if (sType == SchemaTypes.Array || sType == SchemaTypes.Class) {
				hasPublicConstructor = !type.IsInterface && (type.IsArray || type.GetConstructor (Type.EmptyTypes) != null || type.IsAbstract || type.IsValueType);
			}
		}
        static string GenerateFromXmlStringCore(TypeData type, string value)
        {
            switch (type.XmlType)
            {
            case "boolean":
                return("XmlConvert.ToBoolean (" + value + ")");

            case "unsignedByte":
                return("byte.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "char":
                return("(char)Int32.Parse (" + value + ", CultureInfo.InvariantCulture)");

#if NET_2_0
            case "dateTime":
                return("XmlConvert.ToDateTime (" + value + ", XmlDateTimeSerializationMode.RoundtripKind)");

            case "date":
                return("DateTime.ParseExact (" + value + ", \"yyyy-MM-dd\", CultureInfo.InvariantCulture)");

            case "time":
                return("DateTime.ParseExact (" + value + ", \"HH:mm:ss.FFFFFFF\", CultureInfo.InvariantCulture)");
#else
            case "dateTime":
                return("XmlConvert.ToDateTime (" + value + ")");

            case "date":
                return("DateTime.ParseExact (" + value + ", \"yyyy-MM-dd\", CultureInfo.InvariantCulture)");

            case "time":
                return("DateTime.ParseExact (" + value + ", \"HH:mm:ss.fffffffzzz\", CultureInfo.InvariantCulture)");
#endif
            case "decimal":
                return("Decimal.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "double":
                return("XmlConvert.ToDouble (" + value + ")");

            case "short":
                return("Int16.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "int":
                return("Int32.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "long":
                return("Int64.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "byte":
                return("SByte.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "float":
                return("XmlConvert.ToSingle (" + value + ")");

            case "unsignedShort":
                return("UInt16.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "unsignedInt":
                return("UInt32.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "unsignedLong":
                return("UInt64.Parse (" + value + ", CultureInfo.InvariantCulture)");

            case "guid":
                return("XmlConvert.ToGuid (" + value + ")");

            case "base64:":
            case "base64Binary":
                return("Convert.FromBase64String (" + value + ")");

            case "hexBinary":
                return("FromBinHexString (" + value + ")");

            case "duration":
                return(value);

            default:
                return(value);
            }
        }
        static string GenerateToXmlStringCore(TypeData type, string value)
        {
            if (type.NullableOverride)
            {
                value = value + ".Value";
            }
            switch (type.XmlType)
            {
            case "boolean":
                return("(" + value + "?\"true\":\"false\")");

            case "unsignedByte":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "char":
                return("((int)(" + value + ")).ToString(CultureInfo.InvariantCulture)");

#if NET_2_0
            case "dateTime":
                return("XmlConvert.ToString (" + value + ", XmlDateTimeSerializationMode.RoundtripKind)");

            case "date":
                return(value + ".ToString(\"yyyy-MM-dd\", CultureInfo.InvariantCulture)");

            case "time":
                return(value + ".ToString(\"HH:mm:ss.FFFFFFF\", CultureInfo.InvariantCulture)");
#else
            case "dateTime":
                return(value + ".ToString(\"yyyy-MM-ddTHH:mm:ss.fffffffzzz\", CultureInfo.InvariantCulture)");

            case "date":
                return(value + ".ToString(\"yyyy-MM-dd\", CultureInfo.InvariantCulture)");

            case "time":
                return(value + ".ToString(\"HH:mm:ss.fffffffzzz\", CultureInfo.InvariantCulture)");
#endif
            case "decimal":
                return("XmlConvert.ToString (" + value + ")");

            case "double":
                return("XmlConvert.ToString (" + value + ")");

            case "short":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "int":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "long":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "byte":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "float":
                return("XmlConvert.ToString (" + value + ")");

            case "unsignedShort":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "unsignedInt":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "unsignedLong":
                return(value + ".ToString(CultureInfo.InvariantCulture)");

            case "guid":
                return("XmlConvert.ToString (" + value + ")");

            case "base64":
            case "base64Binary":
                return(value + " == null ? String.Empty : Convert.ToBase64String (" + value + ")");

            case "hexBinary":
                return(value + " == null ? String.Empty : ToBinHexString (" + value + ")");

            case "duration":
                return(value);

            case "NMTOKEN":
            case "Name":
            case "NCName":
            case "language":
            case "ENTITY":
            case "ID":
            case "IDREF":
            case "NOTATION":
            case "token":
            case "normalizedString":
            case "string":
                return(value);

            default:
                return("((" + value + " != null) ? (" + value + ").ToString() : null)");
            }
        }
 public static bool IsDefaultPrimitiveTpeData(TypeData primType)
 {
     return(GetDefaultPrimitiveTypeData(primType) == primType);
 }
Beispiel #10
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;
		}
		internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
		{
			return ImportTypeMapping (typeData, (XmlRootAttribute) null, 
				defaultNamespace);
		}
		XmlTypeMapping CreateTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultXmlType, string defaultNamespace)
		{
			string rootNamespace = defaultNamespace;
			string typeNamespace = null;
			string elementName;
			bool includeInSchema = true;
			XmlAttributes atts = null;
			bool nullable = CanBeNull (typeData);

			if (defaultXmlType == null) defaultXmlType = typeData.XmlType;

			if (!typeData.IsListType)
			{
				if (attributeOverrides != null) 
					atts = attributeOverrides[typeData.Type];

				if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
					throw new InvalidOperationException ("XmlRoot and XmlType attributes may not be specified for the type " + typeData.FullTypeName);
			}

			if (atts == null) 
				atts = new XmlAttributes (typeData.Type);

			if (atts.XmlRoot != null && root == null)
				root = atts.XmlRoot;

			if (atts.XmlType != null)
			{
				if (atts.XmlType.Namespace != null)
					typeNamespace = atts.XmlType.Namespace;

				if (atts.XmlType.TypeName != null && atts.XmlType.TypeName != string.Empty)
					defaultXmlType = XmlConvert.EncodeLocalName (atts.XmlType.TypeName);
					
				includeInSchema = atts.XmlType.IncludeInSchema;
			}

			elementName = defaultXmlType;

			if (root != null)
			{
				if (root.ElementName.Length != 0)
					elementName = XmlConvert.EncodeLocalName(root.ElementName);
				if (root.Namespace != null)
					rootNamespace = root.Namespace;
				nullable = root.IsNullable;
			}

			if (rootNamespace == null) rootNamespace = "";
			if (typeNamespace == null) typeNamespace = rootNamespace;
			
			XmlTypeMapping map;
			switch (typeData.SchemaType) {
				case SchemaTypes.XmlSerializable:
					map = new XmlSerializableMapping (root, elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
					break;
				case SchemaTypes.Primitive:
					if (!typeData.IsXsdType)
						map = new XmlTypeMapping (elementName, rootNamespace, 
							typeData, defaultXmlType, XmlSerializer.WsdlTypesNamespace);
					else
						map = new XmlTypeMapping (elementName, rootNamespace, 
							typeData, defaultXmlType, typeNamespace);
					break;
				default:
					map = new XmlTypeMapping (elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
					break;
			}

			map.IncludeInSchema = includeInSchema;
			map.IsNullable = nullable;
			relatedMaps.Add (map);
			
			return map;
		}
Beispiel #13
0
        object ReadTypedPrimitive(XmlQualifiedName qname, bool reportUnknown)
        {
            if (qname == null)
            {
                qname = GetXsiType();
            }

            TypeData typeData = TypeTranslator.FindPrimitiveTypeData(qname.Name);

            if (typeData == null || typeData.SchemaType != SchemaTypes.Primitive)
            {
#if MOONLIGHT
                // skip everything
                reader.Skip();
                return(new Object());
#else
                // Put everything into a node array
                readCount++;
                XmlNode node = Document.ReadNode(reader);

                if (reportUnknown)
                {
                    OnUnknownNode(node, null, null);
                }

                if (node.ChildNodes.Count == 0 && node.Attributes.Count == 0)
                {
                    return(new Object());
                }

                XmlElement elem = node as XmlElement;

                if (elem == null)
                {
                    return new XmlNode[] { node }
                }
                ;
                else
                {
                    XmlNode[] nodes = new XmlNode[elem.Attributes.Count + elem.ChildNodes.Count];

                    int n = 0;
                    foreach (XmlNode no in elem.Attributes)
                    {
                        nodes[n++] = no;
                    }
                    foreach (XmlNode no in elem.ChildNodes)
                    {
                        nodes[n++] = no;
                    }
                    return(nodes);
                }
#endif
            }

            if (typeData.Type == typeof(XmlQualifiedName))
            {
                return(ReadNullableQualifiedName());
            }
            readCount++;
            return(XmlCustomFormatter.FromXmlString(typeData, Reader.ReadElementString()));
        }
		bool CanBeNull (TypeData type)
		{
#if !NET_2_0	// idiotic compatibility
			if (type.Type == typeof (XmlQualifiedName))
				return false;
#endif
			return !type.Type.IsValueType || type.IsNullable;
		}
        internal XmlSerializableMapping(string elementName, string ns, TypeData typeData, string xmlType, string xmlTypeNamespace) : base(elementName, ns, typeData, xmlType, xmlTypeNamespace)
        {
            XmlSchemaProviderAttribute xmlSchemaProviderAttribute = (XmlSchemaProviderAttribute)Attribute.GetCustomAttribute(typeData.Type, typeof(XmlSchemaProviderAttribute));

            if (xmlSchemaProviderAttribute != null)
            {
                string     methodName = xmlSchemaProviderAttribute.MethodName;
                MethodInfo method     = typeData.Type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
                if (method == null)
                {
                    throw new InvalidOperationException(string.Format("Type '{0}' must implement public static method '{1}'", typeData.Type, methodName));
                }
                if (!typeof(XmlQualifiedName).IsAssignableFrom(method.ReturnType) && !typeof(XmlSchemaComplexType).IsAssignableFrom(method.ReturnType))
                {
                    throw new InvalidOperationException(string.Format("Method '{0}' indicated by XmlSchemaProviderAttribute must have its return type as XmlQualifiedName", methodName));
                }
                XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
                object       obj          = method.Invoke(null, new object[]
                {
                    xmlSchemaSet
                });
                this._schemaTypeName = XmlQualifiedName.Empty;
                if (obj == null)
                {
                    return;
                }
                if (obj is XmlSchemaComplexType)
                {
                    this._schemaType = (XmlSchemaComplexType)obj;
                    if (!this._schemaType.QualifiedName.IsEmpty)
                    {
                        this._schemaTypeName = this._schemaType.QualifiedName;
                    }
                    else
                    {
                        this._schemaTypeName = new XmlQualifiedName(xmlType, xmlTypeNamespace);
                    }
                }
                else
                {
                    if (!(obj is XmlQualifiedName))
                    {
                        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, methodName));
                    }
                    this._schemaTypeName = (XmlQualifiedName)obj;
                }
                base.UpdateRoot(new XmlQualifiedName(this._schemaTypeName.Name, base.Namespace ?? this._schemaTypeName.Namespace));
                base.XmlTypeNamespace = this._schemaTypeName.Namespace;
                base.XmlType          = this._schemaTypeName.Name;
                if (!this._schemaTypeName.IsEmpty && xmlSchemaSet.Count > 0)
                {
                    XmlSchema[] array = new XmlSchema[xmlSchemaSet.Count];
                    xmlSchemaSet.CopyTo(array, 0);
                    this._schema = array[0];
                }
                return;
            }
            else
            {
                IXmlSerializable xmlSerializable = (IXmlSerializable)Activator.CreateInstance(typeData.Type, true);
                try
                {
                    this._schema = xmlSerializable.GetSchema();
                }
                catch (Exception)
                {
                }
                if (this._schema != null && (this._schema.Id == null || this._schema.Id.Length == 0))
                {
                    throw new InvalidOperationException("Schema Id is missing. The schema returned from " + typeData.Type.FullName + ".GetSchema() must have an Id.");
                }
                return;
            }
        }
Beispiel #16
0
 public XmlTypeMapElementInfo(XmlTypeMapMember member, TypeData type)
 {
     _member = member;
     _type   = type;
 }
        protected override void GenerateElementInfoMember(CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName)
        {
            CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.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);
            }
        }
        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
        }
        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);
        }
Beispiel #20
0
		ListMap BuildArrayMap (XmlQualifiedName typeQName, XmlSchemaComplexType stype, out TypeData arrayTypeData)
		{
			if (encodedFormat)
			{
				XmlSchemaComplexContent content = stype.ContentModel as XmlSchemaComplexContent;
				XmlSchemaComplexContentRestriction rest = content.Content as XmlSchemaComplexContentRestriction;
				XmlSchemaAttribute arrayTypeAt = FindArrayAttribute (rest.Attributes);
				
				if (arrayTypeAt != null)
				{
					XmlAttribute[] uatts = arrayTypeAt.UnhandledAttributes;
					if (uatts == null || uatts.Length == 0) throw new InvalidOperationException ("arrayType attribute not specified in array declaration: " + typeQName);
					
					XmlAttribute xat = null;
					foreach (XmlAttribute at in uatts)
						if (at.LocalName == "arrayType" && at.NamespaceURI == XmlSerializer.WsdlNamespace)
							{ xat = at; break; }
					
					if (xat == null) 
						throw new InvalidOperationException ("arrayType attribute not specified in array declaration: " + typeQName);
	
					string name, ns, dims;
					TypeTranslator.ParseArrayType (xat.Value, out name, out ns, out dims);
					return BuildEncodedArrayMap (name + dims, ns, out arrayTypeData);
				}
				else
				{
					XmlSchemaElement elem = null;
					XmlSchemaSequence seq = rest.Particle as XmlSchemaSequence;
					if (seq != null && seq.Items.Count == 1) 
						elem = seq.Items[0] as XmlSchemaElement;
					else {
						XmlSchemaAll all = rest.Particle as XmlSchemaAll;
						if (all != null && all.Items.Count == 1)
							elem = all.Items[0] as XmlSchemaElement;
					}
					if (elem == null)
						throw new InvalidOperationException ("Unknown array format");
						
					return BuildEncodedArrayMap (elem.SchemaTypeName.Name + "[]", elem.SchemaTypeName.Namespace, out arrayTypeData);
				}
			}
			else
			{
				ClassMap cmap = new ClassMap ();
				CodeIdentifiers classIds = new CodeIdentifiers();
				ImportParticleComplexContent (typeQName, cmap, stype.Particle, classIds, stype.IsMixed);

				XmlTypeMapMemberFlatList list = (cmap.AllMembers.Count == 1) ? cmap.AllMembers[0] as XmlTypeMapMemberFlatList : null;
				if (list != null && list.ChoiceMember == null)
				{
					arrayTypeData = list.TypeData;
					return list.ListMap;
				}
				else
				{
					arrayTypeData = null;
					return null;
				}
			}
		}
		string GetTypeNamespace (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			string typeNamespace = null;
			
			XmlAttributes atts = null;
			if (!typeData.IsListType)
			{
				if (attributeOverrides != null)
					atts = attributeOverrides[typeData.Type];
			}

			if (atts == null)
				atts = new XmlAttributes (typeData.Type);

   			if (atts.XmlType != null)
   			{
   				if (atts.XmlType.Namespace != null && atts.XmlType.Namespace.Length != 0 && typeData.SchemaType != SchemaTypes.Enum)
   					typeNamespace = atts.XmlType.Namespace;
			}

			if (typeNamespace != null && typeNamespace.Length != 0) return typeNamespace;
			
   			if (atts.XmlRoot != null && root == null)
   				root = atts.XmlRoot;

			if (root != null)
			{
				if (root.Namespace != null && root.Namespace.Length != 0)
					return root.Namespace;
			}

			if (defaultNamespace == null) return "";
			else return defaultNamespace;
		}
Beispiel #22
0
		ListMap BuildEncodedArrayMap (string type, string ns, out TypeData arrayTypeData)
		{
			ListMap map = new ListMap ();
			
			int i = type.LastIndexOf ("[");
			if (i == -1) throw new InvalidOperationException ("Invalid arrayType value: " + type);
			if (type.IndexOf (",",i) != -1) throw new InvalidOperationException ("Multidimensional arrays are not supported");
			
			string itemType = type.Substring (0,i);
			
			TypeData itemTypeData;
			if (itemType.IndexOf ("[") != -1) 
			{
				ListMap innerListMap = BuildEncodedArrayMap (itemType, ns, out itemTypeData);
				
				int dims = itemType.Split ('[').Length - 1;
				string name = TypeTranslator.GetArrayName (type, dims);
				XmlQualifiedName qname = new XmlQualifiedName (name, ns);
				XmlTypeMapping tmap = CreateArrayTypeMapping (qname, itemTypeData);
				tmap.ObjectMap = innerListMap;
			}
			else
			{
				itemTypeData = GetTypeData (new XmlQualifiedName (itemType, ns), null, false);
			}
			
			arrayTypeData = itemTypeData.ListTypeData;
			
			map.ItemInfo = new XmlTypeMapElementInfoList();
			map.ItemInfo.Add (CreateElementInfo ("", null, "Item", itemTypeData, true, XmlSchemaForm.None, -1));
			return map;
		}
		XmlTypeMapping ImportXmlNodeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			Type type = typeData.Type;
			XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
			if (map != null) return map;

			map = CreateTypeMapping (typeData, root, null, defaultNamespace);
			helper.RegisterClrType (map, type, map.XmlTypeNamespace);
			
			if (type.BaseType != null)
			{
				XmlTypeMapping bmap = ImportTypeMapping (type.BaseType, root, defaultNamespace);
				if (type.BaseType != typeof (object))
					map.BaseMap = bmap;
				
				RegisterDerivedMap (bmap, map);
			}

			return map;
		}
		private object GetDefaultValue (TypeData typeData, object defaultValue)
		{
			if (defaultValue == DBNull.Value || typeData.SchemaType != SchemaTypes.Enum)
				return defaultValue;

#if MOONLIGHT
			string namedValue = (defaultValue as Enum).ToString ("g");
			string decimalValue = (defaultValue as Enum).ToString ("d");
#else
			// get string representation of enum value
			string namedValue = Enum.Format (typeData.Type, defaultValue, "g");
			// get decimal representation of enum value
			string decimalValue = Enum.Format (typeData.Type, defaultValue, "d");
#endif
			// if decimal representation matches string representation, then
			// the value is not defined in the enum type (as the "g" format
			// will return the decimal equivalent of the value if the value
			// is not equal to a combination of named enumerated constants
			if (namedValue == decimalValue) {
				string msg = string.Format (CultureInfo.InvariantCulture,
					"Value '{0}' cannot be converted to {1}.", defaultValue,
					defaultValue.GetType ().FullName);
				throw new InvalidOperationException (msg);
			}

			// XmlSerializer expects integral enum value
			//return namedValue.Replace (',', ' ');
			return defaultValue;
		}
		XmlTypeMapping ImportEnumMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			Type type = typeData.Type;
			XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
			if (map != null) return map;
			
			if (!allowPrivateTypes)
				ReflectionHelper.CheckSerializableType (type, false);
				
			map = CreateTypeMapping (typeData, root, null, defaultNamespace);
			map.IsNullable = false;
			helper.RegisterClrType (map, type, map.XmlTypeNamespace);

			ArrayList members = new ArrayList();
#if MOONLIGHT
			foreach (string name in GetEnumNames (type)) {
#else
			string [] names = Enum.GetNames (type);
			foreach (string name in names) {
#endif
				FieldInfo field = type.GetField (name);
				string xmlName = null;
				if (field.IsDefined(typeof(XmlIgnoreAttribute), false))
					continue;
				object[] atts = field.GetCustomAttributes (typeof(XmlEnumAttribute), false);
				if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
				if (xmlName == null) xmlName = name;
				long value = ((IConvertible) field.GetValue (null)).ToInt64 (CultureInfo.InvariantCulture);
				members.Add (new EnumMap.EnumMapMember (xmlName, name, value));
			}

			bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
			map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
			ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
			return map;
		}

		XmlTypeMapping ImportXmlSerializableMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			Type type = typeData.Type;
			XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
			if (map != null) return map;
			
			if (!allowPrivateTypes)
				ReflectionHelper.CheckSerializableType (type, false);
				
			map = CreateTypeMapping (typeData, root, null, defaultNamespace);
			helper.RegisterClrType (map, type, map.XmlTypeNamespace);
			return map;
		}

		void ImportIncludedTypes (Type type, string defaultNamespace)
		{
			XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
			for (int n=0; n<includes.Length; n++)
			{
				Type includedType = includes[n].Type;
				ImportTypeMapping (includedType, null, defaultNamespace);
			}
		}

		ICollection GetReflectionMembers (Type type)
		{
			// First we want to find the inheritance hierarchy in reverse order.
			Type currentType = type;
			ArrayList typeList = new ArrayList();
			typeList.Add(currentType);
			while (currentType != typeof(object))
			{
				currentType = currentType.BaseType; // Read the base type.
				typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
			}

			// Read all Fields via reflection.
			ArrayList fieldList = new ArrayList();
			FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
#if TARGET_JVM
			// This statement ensures fields are ordered starting from the base type.
			for (int ti=0; ti<typeList.Count; ti++) {
				for (int i=0; i<tfields.Length; i++) {
					FieldInfo field = tfields[i];
					if (field.DeclaringType == typeList[ti])
						fieldList.Add (field);
				}
			}
#else
			currentType = null;
			int currentIndex = 0;
			foreach (FieldInfo field in tfields)
			{
				// This statement ensures fields are ordered starting from the base type.
				if (currentType != field.DeclaringType)
				{
					currentType = field.DeclaringType;
					currentIndex=0;
				}
				fieldList.Insert(currentIndex++, field);
			}
#endif
			// Read all Properties via reflection.
			ArrayList propList = new ArrayList();
			PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
#if TARGET_JVM
			// This statement ensures properties are ordered starting from the base type.
			for (int ti=0; ti<typeList.Count; ti++) {
				for (int i=0; i<tprops.Length; i++) {
					PropertyInfo prop = tprops[i];
					if (!prop.CanRead) continue;
					if (prop.GetIndexParameters().Length > 0) continue;
					if (prop.DeclaringType == typeList[ti])
						propList.Add (prop);
				}
			}
#else
			currentType = null;
			currentIndex = 0;
			foreach (PropertyInfo prop in tprops)
			{
				// This statement ensures properties are ordered starting from the base type.
				if (currentType != prop.DeclaringType)
				{
					currentType = prop.DeclaringType;
					currentIndex = 0;
				}
				if (!prop.CanRead) continue;
				if (prop.GetIndexParameters().Length > 0) continue;
				propList.Insert(currentIndex++, prop);
			}
#endif
			ArrayList members = new ArrayList();
			int fieldIndex=0;
			int propIndex=0;
			// We now step through the type hierarchy from the base (object) through
			// to the supplied class, as each step outputting all Fields, and then
			// all Properties.  This is the exact same ordering as .NET 1.0/1.1.
			foreach (Type t in typeList)
			{
				// Add any fields matching the current DeclaringType.
				while (fieldIndex < fieldList.Count)
				{
					FieldInfo field = (FieldInfo)fieldList[fieldIndex];
					if (field.DeclaringType==t)
					{
						fieldIndex++;
						XmlAttributes atts = attributeOverrides[type, field.Name];
						if (atts == null) atts = new XmlAttributes (field);
						if (atts.XmlIgnore) continue;
						XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
						member.DeclaringType = field.DeclaringType;
						members.Add(member);
					}
					else break;
				}

				// Add any properties matching the current DeclaringType.
				while (propIndex < propList.Count)
				{
					PropertyInfo prop = (PropertyInfo)propList[propIndex];
					if (prop.DeclaringType==t)
					{
						propIndex++;
						XmlAttributes atts = attributeOverrides[type, prop.Name];
						if (atts == null) atts = new XmlAttributes (prop);
						if (atts.XmlIgnore) continue;
						if (!prop.CanWrite && (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray)) continue;
						XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
						member.DeclaringType = prop.DeclaringType;
						members.Add(member);
					}
					else break;
				}
			}
			return members;		
		}
		private XmlTypeMapping ImportTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			if (typeData == null)
				throw new ArgumentNullException ("typeData");

			if (typeData.Type == null)
				throw new ArgumentException ("Specified TypeData instance does not have Type set.");

			if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
			if (defaultNamespace == null) defaultNamespace = string.Empty;

			try {
				XmlTypeMapping map;

				switch (typeData.SchemaType) {
					case SchemaTypes.Class: map = ImportClassMapping (typeData, root, defaultNamespace); break;
					case SchemaTypes.Array: map = ImportListMapping (typeData, root, defaultNamespace, null, 0); break;
					case SchemaTypes.XmlNode: map = ImportXmlNodeMapping (typeData, root, defaultNamespace); break;
					case SchemaTypes.Primitive: map = ImportPrimitiveMapping (typeData, root, defaultNamespace); break;
					case SchemaTypes.Enum: map = ImportEnumMapping (typeData, root, defaultNamespace); break;
					case SchemaTypes.XmlSerializable: map = ImportXmlSerializableMapping (typeData, root, defaultNamespace); break;
					default: throw new NotSupportedException ("Type " + typeData.Type.FullName + " not supported for XML stialization");
				}

#if NET_2_0
				// bug #372780
				map.SetKey (typeData.Type.ToString ());
#endif
				map.RelatedMaps = relatedMaps;
				map.Format = SerializationFormat.Literal;
				Type[] extraTypes = includedTypes != null ? (Type[]) includedTypes.ToArray (typeof (Type)) : null;
#if !NET_2_1
				map.Source = new XmlTypeSerializationSource (typeData.Type, root, attributeOverrides, defaultNamespace, extraTypes);
				if (allowPrivateTypes) map.Source.CanBeGenerated = false;
#endif
				return map;
			} catch (InvalidOperationException ex) {
				throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture,
					"There was an error reflecting type '{0}'.", typeData.Type.FullName), ex);
			}
		}
Beispiel #27
0
		public static TypeData GetDefaultPrimitiveTypeData (TypeData primType)
		{
			// Returns the TypeData that is mapped by default to the clr type
			// that primType represents
			
			if (primType.SchemaType == SchemaTypes.Primitive)
			{
				TypeData newPrim = GetTypeData (primType.Type, null);
				if (newPrim != primType) return newPrim;
			}
			return primType;
		}
		XmlTypeMapping ImportClassMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			Type type = typeData.Type;

			XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
			if (map != null) return map;

			if (!allowPrivateTypes)
				ReflectionHelper.CheckSerializableType (type, false);
			
			map = CreateTypeMapping (typeData, root, null, defaultNamespace);
			helper.RegisterClrType (map, type, map.XmlTypeNamespace);
			helper.RegisterSchemaType (map, map.XmlType, map.XmlTypeNamespace);

			// Import members

			ClassMap classMap = new ClassMap ();
			map.ObjectMap = classMap;

			ICollection members = GetReflectionMembers (type);
			foreach (XmlReflectionMember rmember in members)
			{
				string ns = map.XmlTypeNamespace;
				if (rmember.XmlAttributes.XmlIgnore) continue;
				if (rmember.DeclaringType != null && rmember.DeclaringType != type) {
					XmlTypeMapping bmap = ImportClassMapping (rmember.DeclaringType, root, defaultNamespace);
					ns = bmap.XmlTypeNamespace;
				}

				try {
					XmlTypeMapMember mem = CreateMapMember (type, rmember, ns);
					mem.CheckOptionalValueType (type);
					classMap.AddMember (mem);
				} catch (Exception ex) {
					throw new InvalidOperationException (string.Format (
						CultureInfo.InvariantCulture, "There was an error" +
						" reflecting field '{0}'.", rmember.MemberName), ex);
				}
			}

			// Import extra classes

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

			// Register inheritance relations

			if (type.BaseType != null)
			{
				XmlTypeMapping bmap = ImportClassMapping (type.BaseType, root, defaultNamespace);
				ClassMap cbmap = bmap.ObjectMap as ClassMap;
				
				if (type.BaseType != typeof (object)) {
					map.BaseMap = bmap;
					if (!cbmap.HasSimpleContent)
						classMap.SetCanBeSimpleType (false);
				}
				
				// At this point, derived classes of this map must be already registered
				
				RegisterDerivedMap (bmap, map);
				
				if (cbmap.HasSimpleContent && classMap.ElementMembers != null && classMap.ElementMembers.Count != 1)
					throw new InvalidOperationException (String.Format (errSimple, map.TypeData.TypeName, map.BaseMap.TypeData.TypeName));
			}
			
			ImportIncludedTypes (type, defaultNamespace);
			
			if (classMap.XmlTextCollector != null && !classMap.HasSimpleContent)
			{
				XmlTypeMapMember mem = classMap.XmlTextCollector;
				if (mem.TypeData.Type != typeof(string) && 
				   mem.TypeData.Type != typeof(string[]) && 
#if !MOONLIGHT
				   mem.TypeData.Type != typeof(XmlNode[]) && 
#endif
				   mem.TypeData.Type != typeof(object[]))
				   
					throw new InvalidOperationException (String.Format (errSimple2, map.TypeData.TypeName, mem.Name, mem.TypeData.TypeName));
			}
			
			return map;
		}
        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);
        }
		XmlTypeMapping ImportListMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
		{
			Type type = typeData.Type;
			ListMap obmap = new ListMap ();

			if (!allowPrivateTypes)
				ReflectionHelper.CheckSerializableType (type, true);
			
			if (atts == null) atts = new XmlAttributes();
			Type itemType = typeData.ListItemType;

			// warning: byte[][] should not be considered multiarray
			bool isMultiArray = (type.IsArray && (TypeTranslator.GetTypeData(itemType).SchemaType == SchemaTypes.Array) && itemType.IsArray);

			XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();

			foreach (XmlArrayItemAttribute att in atts.XmlArrayItems)
			{
				if (att.Namespace != null && att.Form == XmlSchemaForm.Unqualified)
					throw new InvalidOperationException ("XmlArrayItemAttribute.Form must not be Unqualified when it has an explicit Namespace value.");
				if (att.NestingLevel != nestingLevel) continue;
				Type elemType = (att.Type != null) ? att.Type : itemType;
				XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData(elemType, att.DataType));
				elem.Namespace = att.Namespace != null ? att.Namespace : defaultNamespace;
				if (elem.Namespace == null) elem.Namespace = "";
				elem.Form = att.Form;
				if (att.Form == XmlSchemaForm.Unqualified)
					elem.Namespace = string.Empty;
				elem.IsNullable = att.IsNullable && CanBeNull (elem.TypeData);
				elem.NestingLevel = att.NestingLevel;

				if (isMultiArray) {
					elem.MappedType = ImportListMapping (elemType, null, elem.Namespace, atts, nestingLevel + 1);
				} else if (elem.TypeData.IsComplexType) {
					elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
				}

				if (att.ElementName.Length != 0) {
					elem.ElementName = XmlConvert.EncodeLocalName (att.ElementName);
				} else if (elem.MappedType != null) {
					elem.ElementName = elem.MappedType.ElementName;
				} else {
					elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
				}

				list.Add (elem);
			}

			if (list.Count == 0)
			{
				XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData (itemType));
				if (isMultiArray)
					elem.MappedType = ImportListMapping (itemType, null, defaultNamespace, atts, nestingLevel + 1);
				else if (elem.TypeData.IsComplexType)
					elem.MappedType = ImportTypeMapping (itemType, null, defaultNamespace);

				if (elem.MappedType != null) {
					elem.ElementName = elem.MappedType.XmlType;
				} else {
					elem.ElementName = TypeTranslator.GetTypeData (itemType).XmlType;
				}

				elem.Namespace = (defaultNamespace != null) ? defaultNamespace : "";
				elem.IsNullable = CanBeNull (elem.TypeData);
				list.Add (elem);
			}

			obmap.ItemInfo = list;

			// If there can be different element names (types) in the array, then its name cannot
			// be "ArrayOfXXX" it must be something like ArrayOfChoiceNNN

			string baseName;
			if (list.Count > 1) {
				baseName = "ArrayOfChoice" + (arrayChoiceCount++);
			} else {
				XmlTypeMapElementInfo elem = ((XmlTypeMapElementInfo) list[0]);
				if (elem.MappedType != null) {
					baseName = TypeTranslator.GetArrayName (elem.MappedType.XmlType);
				} else {
					baseName = TypeTranslator.GetArrayName (elem.ElementName);
				}
			}

			// Avoid name colisions

			int nameCount = 1;
			string name = baseName;

			do {
				XmlTypeMapping foundMap = helper.GetRegisteredSchemaType (name, defaultNamespace);
				if (foundMap == null) nameCount = -1;
				else if (obmap.Equals (foundMap.ObjectMap) && typeData.Type == foundMap.TypeData.Type) return foundMap;
				else name = baseName + (nameCount++);
			}
			while (nameCount != -1);

			XmlTypeMapping map = CreateTypeMapping (typeData, root, name, defaultNamespace);
			map.ObjectMap = obmap;
			
			// Register any of the including types as a derived class of object
			XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
			
			XmlTypeMapping objectMapping = ImportTypeMapping (typeof(object));
			for (int i = 0; i < includes.Length; i++)
			{
				Type includedType = includes[i].Type;
				objectMapping.DerivedTypes.Add(ImportTypeMapping (includedType, null, defaultNamespace));
			}
			
			// Register this map as a derived class of object

			helper.RegisterSchemaType (map, name, defaultNamespace);
			ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);

			return map;
		}
Beispiel #31
0
		XmlTypeMapping CreateSystemMap (TypeData typeData)
		{
			XmlTypeMapping map = new XmlTypeMapping (typeData.XmlType, XmlSchema.Namespace, typeData, typeData.XmlType, XmlSchema.Namespace);
			map.IncludeInSchema = false;
			map.ObjectMap = new ClassMap ();
			dataMappedTypes [typeData] = map;
			return map;
		}
		XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
		{
			Type type = typeData.Type;
			XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
			if (map != null) return map;
			map = CreateTypeMapping (typeData, root, null, defaultNamespace);
			helper.RegisterClrType (map, type, map.XmlTypeNamespace);
			return map;
		}
Beispiel #33
0
		XmlTypeMapping GetRegisteredTypeMapping (TypeData typeData)
		{
			return (XmlTypeMapping) dataMappedTypes [typeData];
		}
Beispiel #34
0
		public static TypeData GetTypeData (Type runtimeType, string xmlDataType, bool underlyingEnumType = false)
		{
			if (underlyingEnumType && runtimeType.IsEnum)
				runtimeType = Enum.GetUnderlyingType (runtimeType);

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


			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 + "'");
				}
				if (nullableOverride){
					TypeData tt = (TypeData) nullableTypes [at.XmlType];
					if (tt == null){
						tt = new TypeData (type, at.XmlType, false);
						tt.IsNullable = true;
						nullableTypes [at.XmlType] = tt;
					}
					return tt;
				}
				return at;
			}

			if (nullableOverride){
				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
			
				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;
		}
Beispiel #35
0
		void RegisterTypeMapping (XmlQualifiedName qname, TypeData typeData, XmlTypeMapping map)
		{
			// Primitive types with a forced base class are stored in a different table.
			// In this way it is possible to have two maps for primitive types: one with
			// the forced base class (returned by ImportDerivedTypeMapping) and one
			// with the regular primitive map.
			
			dataMappedTypes [typeData] = map;
			if (IsPrimitiveTypeNamespace (qname.Namespace) && !map.IsSimpleType)
				primitiveDerivedMappedTypes [qname] = map;
			else
				mappedTypes [qname] = map;
		}
Beispiel #36
0
		public static bool IsDefaultPrimitiveTpeData (TypeData primType)
		{
			return GetDefaultPrimitiveTypeData (primType) == primType;
		}
Beispiel #37
0
		XmlTypeMapping ReflectType (TypeData typeData, string ns)
		{
			if (!encodedFormat)
			{
				if (auxXmlRefImporter == null) auxXmlRefImporter = new XmlReflectionImporter ();
				return auxXmlRefImporter.ImportTypeMapping (typeData, ns);
			}
			else
			{
				if (auxSoapRefImporter == null) auxSoapRefImporter = new SoapReflectionImporter ();
				return auxSoapRefImporter.ImportTypeMapping (typeData, ns);
			}
		}
Beispiel #38
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));
#if !MOONLIGHT
			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));
#endif
			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));
#if !MOONLIGHT
			nameCache.Add (typeof (XmlNode), new TypeData (typeof (XmlNode), "XmlNode", false));
			nameCache.Add (typeof (XmlElement), new TypeData (typeof (XmlElement), "XmlElement", false));
#endif

			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
		}
Beispiel #39
0
		XmlMemberMapping ImportMemberMapping (string name, string ns, bool isNullable, TypeData type, XmlTypeMapping emap, int order)
		{
			XmlTypeMapMemberElement mapMem;
			
			if (type.IsListType)
				mapMem = new XmlTypeMapMemberList ();
			else
				mapMem = new XmlTypeMapMemberElement ();
			
			mapMem.Name = name;
			mapMem.TypeData = type;
			mapMem.ElementInfo.Add (CreateElementInfo (ns, mapMem, name, type, isNullable, XmlSchemaForm.None, emap, order));
			return new XmlMemberMapping (name, ns, mapMem, encodedFormat);
		}
		protected override void GenerateElementInfoMember (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName)
		{
			CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.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);
		}
        internal static object FromXmlString(TypeData type, string value)
        {
            if (value == null)
            {
                return(null);
            }

            switch (type.XmlType)
            {
            case "boolean":
                return(XmlConvert.ToBoolean(value));

            case "unsignedByte":
                return(XmlConvert.ToByte(value));

            case "char":
                return((char)XmlConvert.ToInt32(value));

#if NET_2_0
            case "dateTime":
                return(XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind));

            case "date":
                return(DateTime.ParseExact(value, "yyyy-MM-dd", null));

            case "time":
                return(DateTime.ParseExact(value, "HH:mm:ss.FFFFFFF", null));
#else
            case "dateTime":
                return(XmlConvert.ToDateTime(value));

            case "date":
                return(DateTime.ParseExact(value, "yyyy-MM-dd", null));

            case "time":
                return(DateTime.ParseExact(value, "HH:mm:ss.fffffffzzz", null));
#endif
            case "decimal":
                return(XmlConvert.ToDecimal(value));

            case "double":
                return(XmlConvert.ToDouble(value));

            case "short":
                return(XmlConvert.ToInt16(value));

            case "int":
                return(XmlConvert.ToInt32(value));

            case "long":
                return(XmlConvert.ToInt64(value));

            case "byte":
                return(XmlConvert.ToSByte(value));

            case "float":
                return(XmlConvert.ToSingle(value));

            case "unsignedShort":
                return(XmlConvert.ToUInt16(value));

            case "unsignedInt":
                return(XmlConvert.ToUInt32(value));

            case "unsignedLong":
                return(XmlConvert.ToUInt64(value));

            case "guid":
                return(XmlConvert.ToGuid(value));

            case "base64":
            case "base64Binary":
                return(Convert.FromBase64String(value));

            case "hexBinary":
                return(XmlConvert.FromBinHexString(value));

            case "duration":
                return(value);

            default:
                if (type.Type != null)
                {
                    return(Convert.ChangeType(value, type.Type));
                }
                else
                {
                    return(value);
                }
            }
        }