// Verify the top element name and namespace.
        private static void Verify(KnownTypeCollection knownTypes, Type type, string name, string Namespace, XmlReader reader)
        {
            QName graph_qname = new QName(reader.Name, reader.NamespaceURI);

            if (graph_qname.Name == name && graph_qname.Namespace == Namespace)
            {
                return;
            }

            // <BClass .. i:type="EClass" >..</BClass>
            // Expecting type EClass : allowed
            // See test Serialize1b, and Serialize1c (for
            // negative cases)

            // Run through inheritance heirarchy ..
            for (Type baseType = type; baseType != null; baseType = baseType.BaseType)
            {
                if (knownTypes.GetQName(baseType) == graph_qname)
                {
                    return;
                }
            }

            QName typeQName = knownTypes.GetQName(type);

            throw new SerializationException(String.Format(
                                                 "Expecting element '{0}' from namespace '{1}'. Encountered 'Element' with name '{2}', namespace '{3}'",
                                                 typeQName.Name, typeQName.Namespace, graph_qname.Name, graph_qname.Namespace));
        }
        public void SerializePrimitive(Type type, object graph, QName qname)
        {
//			writer.WriteStartAttribute ("type", XmlSchema.InstanceNamespace);
//			writer.WriteQualifiedName (qname.Name, qname.Namespace);
//			writer.WriteEndAttribute ();
            writer.WriteString(KnownTypeCollection.PredefinedTypeObjectToString(graph));
        }
        Hashtable references = new Hashtable();          // preserve possibly referenced objects to ids. (new in 3.5 SP1)

        public static void Serialize(XmlDictionaryWriter writer, object graph,
                                     KnownTypeCollection types,
                                     bool ignoreUnknown, int maxItems, string root_ns)
        {
            new XmlFormatterSerializer(writer, types, ignoreUnknown, maxItems, root_ns)
            .Serialize(graph != null ? graph.GetType() : null, graph);
        }
        Type GetTypeFromNamePair(string name, string ns)
        {
            Type p = KnownTypeCollection.GetPrimitiveTypeFromName(name);              // FIXME: namespace?

            if (p != null)
            {
                return(p);
            }
            if (name.StartsWith("ArrayOf", StringComparison.Ordinal) && ns == KnownTypeCollection.MSArraysNamespace)
            {
                return(GetTypeFromNamePair(name.Substring(7), String.Empty).MakeArrayType());
            }

            int    xlen  = KnownTypeCollection.DefaultClrNamespaceBase.Length;
            string clrns = ns.Length > xlen?ns.Substring(xlen) : null;

            foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var t in ass.GetTypes())
                {
                    var dca = t.GetCustomAttribute <DataContractAttribute> (true);
                    if (dca != null && dca.Name == name && dca.Namespace == ns)
                    {
                        return(t);
                    }
                    if (clrns != null && t.Name == name && t.Namespace == clrns)
                    {
                        return(t);
                    }
                }
            }
            throw new XmlException(String.Format("Type not found; name: {0}, namespace: {1}", name, ns));
        }
Beispiel #5
0
        public void SerializePrimitive(Type type, object graph, QName qname)
        {
            string label;

            if (TrySerializeAsReference(false, graph, out label))
            {
                return;
            }
            if (label != null)
            {
                Writer.WriteAttributeString("z", "Id", KnownTypeCollection.MSSimpleNamespace, label);
            }

//			writer.WriteStartAttribute ("type", XmlSchema.InstanceNamespace);
//			writer.WriteQualifiedName (qname.Name, qname.Namespace);
//			writer.WriteEndAttribute ();

            // It is the only exceptional type that does not serialize to string but serializes into complex element.
            if (type == typeof(DateTimeOffset))
            {
                var v = (DateTimeOffset)graph;
                writer.WriteStartElement("DateTime", KnownTypeCollection.DefaultClrNamespaceSystem);
                SerializePrimitive(typeof(DateTime), DateTime.SpecifyKind(v.DateTime.Subtract(v.Offset), DateTimeKind.Utc), KnownTypeCollection.GetPredefinedTypeName(typeof(DateTime)));
                writer.WriteEndElement();
                writer.WriteStartElement("OffsetMinutes", KnownTypeCollection.DefaultClrNamespaceSystem);
                SerializePrimitive(typeof(int), v.Offset.TotalMinutes, KnownTypeCollection.GetPredefinedTypeName(typeof(int)));
                writer.WriteEndElement();
            }
            else
            {
                writer.WriteString(KnownTypeCollection.PredefinedTypeObjectToString(graph));
            }
        }
Beispiel #6
0
        List <DataMemberInfo> GetMembers(Type type, QName qname, bool declared_only)
        {
            List <DataMemberInfo> data_members = new List <DataMemberInfo> ();
            BindingFlags          flags        = AllInstanceFlags | BindingFlags.DeclaredOnly;

            for (Type t = type; t != null; t = t.BaseType)
            {
                foreach (FieldInfo fi in t.GetFields(flags))
                {
                    if (fi.GetCustomAttributes(
                            typeof(NonSerializedAttribute),
                            false).Length > 0)
                    {
                        continue;
                    }

                    if (fi.IsInitOnly)
                    {
                        throw new InvalidDataContractException(String.Format("DataMember field {0} must not be read-only.", fi));
                    }
                    DataMemberAttribute dma = new DataMemberAttribute();
                    data_members.Add(CreateDataMemberInfo(dma, fi, fi.FieldType, KnownTypeCollection.GetStaticQName(fi.DeclaringType).Namespace));
                }
            }

            data_members.Sort(DataMemberInfo.DataMemberInfoComparer.Instance);              // alphabetic order.

            return(data_members);
        }
 private XmlFormatterDeserializer(
     KnownTypeCollection knownTypes,
     IDataContractSurrogate surrogate)
 {
     this.types     = knownTypes;
     this.surrogate = surrogate;
 }
Beispiel #8
0
        public CollectionTypeMap(
            Type type, Type elementType,
            QName qname, KnownTypeCollection knownTypes)
            : base(type, qname, knownTypes)
        {
            element_type  = elementType;
            element_qname = KnownTypes.GetQName(element_type);
            var icoll = GetGenericCollectionInterface(RuntimeType);

            if (icoll != null)
            {
                if (RuntimeType.IsInterface)
                {
                    add_method = RuntimeType.GetMethod("Add", icoll.GetGenericArguments());
                }
                else
                {
                    var imap = RuntimeType.GetInterfaceMap(icoll);
                    for (int i = 0; i < imap.InterfaceMethods.Length; i++)
                    {
                        if (imap.InterfaceMethods [i].Name == "Add")
                        {
                            add_method = imap.TargetMethods [i];
                            break;
                        }
                    }
                    if (add_method == null)
                    {
                        add_method = type.GetMethod("Add", icoll.GetGenericArguments());
                    }
                }
            }
        }
Beispiel #9
0
        List <DataMemberInfo> GetDefaultMembers()
        {
            var l = new List <DataMemberInfo> ();

            foreach (var mi in RuntimeType.GetMembers())
            {
                Type      mt = null;
                FieldInfo fi = mi as FieldInfo;
                mt = fi == null ? null : fi.FieldType;
                PropertyInfo pi = mi as PropertyInfo;
                if (pi != null && pi.CanRead && pi.CanWrite && pi.GetIndexParameters().Length == 0)
                {
                    mt = pi.PropertyType;
                }
                if (mt == null)
                {
                    continue;
                }
                if (mi.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).Length != 0)
                {
                    continue;
                }
                string ns = KnownTypeCollection.GetStaticQName(mi.DeclaringType).Namespace;
                l.Add(CreateDataMemberInfo(new DataMemberAttribute(), mi, mt, ns));
            }
            l.Sort(DataMemberInfo.DataMemberInfoComparer.Instance);
            return(l);
        }
Beispiel #10
0
        protected SerializationMap(
            Type type, QName qname, KnownTypeCollection knownTypes)
        {
            KnownTypes  = knownTypes;
            RuntimeType = type;
            if (qname.Namespace == null)
            {
                qname = new QName(qname.Name,
                                  KnownTypeCollection.DefaultClrNamespaceBase + type.Namespace);
            }

            XmlName = qname;
            Members = new List <DataMemberInfo> ();

            foreach (var mi in type.GetMethods(AllInstanceFlags))
            {
                if (mi.GetCustomAttributes(typeof(OnDeserializingAttribute), false).Length > 0)
                {
                    OnDeserializing = mi;
                }
                else if (mi.GetCustomAttributes(typeof(OnDeserializedAttribute), false).Length > 0)
                {
                    OnDeserialized = mi;
                }
            }
        }
Beispiel #11
0
		public void SerializePrimitive (Type type, object graph, QName qname)
		{
			string label;
			if (TrySerializeAsReference (false, graph, out label))
				return;
			if (label != null)
				Writer.WriteAttributeString ("z", "Id", KnownTypeCollection.MSSimpleNamespace, label);

			bool isDateTimeOffset = false;
			// Handle DateTimeOffset type and DateTimeOffset?
			if (type == typeof (DateTimeOffset))
				isDateTimeOffset = true;
			else if(type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) 
				isDateTimeOffset = type.GetGenericArguments () [0] == typeof (DateTimeOffset);	
			// It is the only exceptional type that does not serialize to string but serializes into complex element.
			if (isDateTimeOffset) {
				var v = (DateTimeOffset) graph;
				writer.WriteStartElement ("DateTime", KnownTypeCollection.DefaultClrNamespaceSystem);
				SerializePrimitive (typeof (DateTime), DateTime.SpecifyKind (v.DateTime.Subtract (v.Offset), DateTimeKind.Utc), KnownTypeCollection.GetPredefinedTypeName (typeof (DateTime)));
				writer.WriteEndElement ();
				writer.WriteStartElement ("OffsetMinutes", KnownTypeCollection.DefaultClrNamespaceSystem);
				SerializePrimitive (typeof (int), v.Offset.TotalMinutes, KnownTypeCollection.GetPredefinedTypeName (typeof (int)));
				writer.WriteEndElement ();
			}
			else
				writer.WriteString (KnownTypeCollection.PredefinedTypeObjectToString (graph));
		}
Beispiel #12
0
        void PopulateTypes(IEnumerable <Type> knownTypes)
        {
            if (known_types == null)
            {
                known_types = new KnownTypeCollection();
            }

            if (knownTypes != null)
            {
                foreach (Type t in knownTypes)
                {
                    known_types.Add(t);
                }
            }

            Type elementType = type;

            if (type.HasElementType)
            {
                elementType = type.GetElementType();
            }

            /* Get all KnownTypeAttribute-s, including inherited ones */
            object [] attrs = elementType.GetCustomAttributes(typeof(KnownTypeAttribute), true);
            for (int i = 0; i < attrs.Length; i++)
            {
                KnownTypeAttribute kt = (KnownTypeAttribute)attrs [i];
                known_types.Add(kt.Type);
            }
        }
Beispiel #13
0
        CodeTypeReference GetCodeTypeReferenceInternal(XmlQualifiedName typeName, bool throwError)
        {
            if (typeName == null)
            {
                throw new ArgumentNullException("typeName");
            }

            switch (typeName.Namespace)
            {
            case XmlSchema.Namespace:
                return(new CodeTypeReference(KnownTypeCollection.GetPrimitiveTypeFromName(typeName.Name)));

            case KnownTypeCollection.MSSimpleNamespace:
                switch (typeName.Name)
                {
                case "guid":
                    return(new CodeTypeReference(typeof(Guid)));

                case "duration":
                    return(new CodeTypeReference(typeof(TimeSpan)));
                }
                break;
            }

            var info = GetTypeInfo(typeName, throwError);

            return(info != null ? info.ClrType : null);
        }
Beispiel #14
0
        public void Serialize(Type type, object graph)
        {
            if (graph == null)
            {
                writer.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true");
            }
            else
            {
                Type actualType = graph.GetType();

                SerializationMap map = types.FindUserMap(actualType);
                // For some collection types, the actual type does not matter. So get nominal serialization type instead.
                // (The code below also covers the lines above, but I don't remove above lines to avoid extra search cost.)
                if (map == null)
                {
                    actualType = types.GetSerializedType(actualType);
                    map        = types.FindUserMap(actualType);
                }
                // If it is still unknown, then register it.
                if (map == null)
                {
                    types.Add(actualType);
                    map = types.FindUserMap(actualType);
                }

                if (actualType != type && (map == null || map.OutputXsiType))
                {
                    QName  qname = types.GetXmlName(actualType);
                    string name  = qname.Name;
                    string ns    = qname.Namespace;
                    if (qname == QName.Empty)
                    {
                        name = XmlConvert.EncodeLocalName(actualType.Name);
                        ns   = KnownTypeCollection.DefaultClrNamespaceBase + actualType.Namespace;
                    }
                    else if (qname.Namespace == KnownTypeCollection.MSSimpleNamespace)
                    {
                        ns = XmlSchema.Namespace;
                    }
                    if (writer.LookupPrefix(ns) == null)                      // it goes first (extraneous, but it makes att order compatible)
                    {
                        writer.WriteXmlnsAttribute(null, ns);
                    }
                    writer.WriteStartAttribute("type", XmlSchema.InstanceNamespace);
                    writer.WriteQualifiedName(name, ns);
                    writer.WriteEndAttribute();
                }
                QName predef = KnownTypeCollection.GetPredefinedTypeName(actualType);
                if (predef != QName.Empty)
                {
                    SerializePrimitive(type, graph, predef);
                }
                else
                {
                    map.Serialize(graph, this);
                }
            }
        }
Beispiel #15
0
 public XmlFormatterSerializer(XmlDictionaryWriter writer,
                               KnownTypeCollection types,
                               bool ignoreUnknown, int maxItems, string root_ns)
 {
     this.writer    = writer;
     this.types     = types;
     ignore_unknown = ignoreUnknown;
     max_items      = maxItems;
 }
Beispiel #16
0
 // Note that this does not handle DBNull and DateTimeOffset
 // (they are not included in the predefined schema)
 static Type GetPredefinedTypeFromQName(QName qname)
 {
     switch (qname.Namespace)
     {
     case XmlSchema.Namespace:
     case KnownTypeCollection.MSSimpleNamespace:
         return(KnownTypeCollection.GetPrimitiveTypeFromName(qname));
     }
     throw new Exception("Should not happen");
 }
Beispiel #17
0
 bool IsPredefinedType(XmlQualifiedName qname)
 {
     switch (qname.Namespace)
     {
     case KnownTypeCollection.MSSimpleNamespace:
     case XmlSchema.Namespace:
         return(KnownTypeCollection.GetPrimitiveTypeFromName(qname) != null);
     }
     return(false);
 }
Beispiel #18
0
 private XmlFormatterDeserializer(
     KnownTypeCollection knownTypes,
     IDataContractSurrogate surrogate,
     DataContractResolver resolver,
     DataContractResolver defaultResolver)
 {
     this.types            = knownTypes;
     this.surrogate        = surrogate;
     this.resolver         = resolver;
     this.default_resolver = defaultResolver;
 }
        private void ReadRootStartElement(XmlReader reader, Type type)
        {
            SerializationMap map =
                known_types.FindUserMap(type);
            QName name = map != null ? map.XmlName :
                         KnownTypeCollection.GetPredefinedTypeName(type);

            reader.MoveToContent();
            reader.ReadStartElement(name.Name, name.Namespace);
            // FIXME: could there be any attributes to handle here?
            reader.Read();
        }
Beispiel #20
0
 bool IsUnknownType(Type contractType, Type type)
 {
     if (type.IsArray)
     {
         if (KnownTypeCollection.GetAttribute <CollectionDataContractAttribute> (contractType) != null ||
             KnownTypeCollection.GetAttribute <DataContractAttribute> (contractType) != null)
         {
             return(true);
         }
     }
     return(IsUnknownType(type));
 }
Beispiel #21
0
 public CollectionContractTypeMap(
     Type type, CollectionDataContractAttribute a, Type elementType,
     QName qname, KnownTypeCollection knownTypes)
     : base(type, elementType, qname, knownTypes)
 {
     this.a      = a;
     IsReference = a.IsReference;
     if (!String.IsNullOrEmpty(a.ItemName))
     {
         element_qname = new XmlQualifiedName(a.ItemName, a.Namespace ?? CurrentNamespace);
     }
 }
Beispiel #22
0
 public XmlFormatterSerializer(XmlDictionaryWriter writer, KnownTypeCollection types, bool ignoreUnknown,
                               int maxItems, string root_ns, bool preserveObjectReferences,
                               DataContractResolver resolver, DataContractResolver defaultResolver)
 {
     this.writer              = writer;
     this.types               = types;
     ignore_unknown           = ignoreUnknown;
     max_items                = maxItems;
     PreserveObjectReferences = preserveObjectReferences;
     this.resolver            = resolver;
     this.default_resolver    = defaultResolver;
 }
 bool IsUnknownType(Type type)
 {
     if (known_types.Contains(type) ||
         KnownTypeCollection.GetPrimitiveTypeName(type) != QName.Empty)
     {
         return(false);
     }
     if (type.IsArray)
     {
         return(IsUnknownType(type.GetElementType()));
     }
     return(true);
 }
Beispiel #24
0
        string GetXmlTypeName(Type type)
        {
            var qname = KnownTypeCollection.GetPrimitiveTypeName(type);

            if (!qname.Equals(QName.Empty))
            {
                return(qname.Name);
            }
            var ret = type.Name;
            int idx = ret.IndexOf('`');

            return(idx < 0 ? ret : ret.Substring(0, idx));
        }
        object DeserializePrimitive(Type type, XmlReader reader, QName qname)
        {
            bool isDateTimeOffset = false;

            // Handle DateTimeOffset type and DateTimeOffset?.
            if (type == typeof(DateTimeOffset))
            {
                isDateTimeOffset = true;
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                isDateTimeOffset = type.GetGenericArguments() [0] == typeof(DateTimeOffset);
            }
            // It is the only exceptional type that does not serialize to string but serializes into complex element.
            if (isDateTimeOffset)
            {
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(default(DateTimeOffset));
                }
                reader.ReadStartElement();
                reader.MoveToContent();
                var date = reader.ReadElementContentAsDateTime("DateTime", KnownTypeCollection.DefaultClrNamespaceSystem);
                var off  = TimeSpan.FromMinutes(reader.ReadElementContentAsInt("OffsetMinutes", KnownTypeCollection.DefaultClrNamespaceSystem));
                reader.MoveToContent();
                reader.ReadEndElement();
                return(new DateTimeOffset(DateTime.SpecifyKind(date.ToUniversalTime() + off, DateTimeKind.Unspecified), off));
            }

            string value;

            if (reader.IsEmptyElement)
            {
                reader.Read();                  // advance
                if (type.IsValueType)
                {
                    return(Activator.CreateInstance(type));
                }
                else
                {
                    // FIXME: Workaround for creating empty objects of the correct type.
                    value = String.Empty;
                }
            }
            else
            {
                value = reader.ReadElementContentAsString();
            }
            return(KnownTypeCollection.PredefinedTypeStringToObject(value, qname.Name, reader));
        }
Beispiel #26
0
        protected DataMemberInfo CreateDataMemberInfo(DataMemberAttribute dma, MemberInfo mi, Type memberType, string ownerNamespace)
        {
            KnownTypes.Add(memberType);
            QName qname = KnownTypes.GetQName(memberType);

            if (KnownTypeCollection.GetPrimitiveTypeFromName(qname) != null)
            {
                return(new DataMemberInfo(mi, dma, ownerNamespace, null));
            }
            else
            {
                return(new DataMemberInfo(mi, dma, ownerNamespace, qname.Namespace));
            }
        }
Beispiel #27
0
        public DataContractSerializer(Type type,
                                      IEnumerable <Type> knownTypes)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            this.type   = type;
            known_types = new KnownTypeCollection();
            PopulateTypes(knownTypes);
            known_types.TryRegister(type);
            QName qname = known_types.GetQName(type);

            FillDictionaryString(qname.Name, qname.Namespace);
        }
        void PopulateTypes(IEnumerable <Type> knownTypes)
        {
            if (known_types == null)
            {
                known_types = new KnownTypeCollection();
            }

            if (knownTypes != null)
            {
                foreach (Type t in knownTypes)
                {
                    known_types.Add(t);
                }
            }

            RegisterTypeAsKnown(type);
        }
Beispiel #29
0
        internal virtual QName GetDictionaryQName()
        {
            string name = a != null ? a.Name : null;
            string ns   = a != null ? a.Namespace : null;

            if (RuntimeType.IsGenericType && RuntimeType.GetGenericTypeDefinition() != typeof(Dictionary <,>))
            {
                name = name ?? KnownTypeCollection.GetDefaultName(RuntimeType);
            }
            else
            {
                name = "ArrayOf" + GetItemQName().Name;
            }
            ns = ns ?? KnownTypeCollection.MSArraysNamespace;

            return(new QName(name, ns));
        }
        public static object Deserialize(XmlReader reader, Type type,
                                         KnownTypeCollection knownTypes, IDataContractSurrogate surrogate,
                                         string name, string ns, bool verifyObjectName)
        {
            reader.MoveToContent();
            if (verifyObjectName)
            {
                if (reader.NodeType != XmlNodeType.Element ||
                    reader.LocalName != name ||
                    reader.NamespaceURI != ns)
                {
                    throw new SerializationException(String.Format("Expected element '{0}' in namespace '{1}', but found {2} node '{3}' in namespace '{4}'", name, ns, reader.NodeType, reader.LocalName, reader.NamespaceURI));
                }
            }
//				Verify (knownTypes, type, name, ns, reader);
            return(new XmlFormatterDeserializer(knownTypes, surrogate).Deserialize(type, reader));
        }