public static List<object> ConvertGenericDictionaryToArray(DataContractJsonSerializer serializer, IEnumerable value, CollectionDataContract dataContract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType)
        {
            List<object> keyValuePair = new List<object>();
            Dictionary<string, object> currentEntry;
            Type[] declaredTypes = dataContract.ItemType.GetGenericArguments();
            MethodInfo getEnumeratorMethod = dataContract.GetEnumeratorMethod;

            IDictionaryEnumerator enumerator = (IDictionaryEnumerator)((getEnumeratorMethod == null) ? value.GetEnumerator() : (IDictionaryEnumerator)getEnumeratorMethod.Invoke(value, Array.Empty<Type>()));
            while (enumerator.MoveNext())
            {
                DictionaryEntry current = enumerator.Entry;
                DataContract currentDataContract = DataContract.GetDataContract(enumerator.Current.GetType());
                currentEntry = new Dictionary<string, object>();
                if (writeServerType)
                {
                    AddTypeInformation(currentEntry, currentDataContract);
                }
                context.PushKnownTypes(dataContract);
                AddDictionaryEntryData(serializer, currentEntry, writeServerType ? JsonGlobals.KeyString.ToLowerInvariant() : JsonGlobals.KeyString, declaredTypes[0], current.Key, context);
                AddDictionaryEntryData(serializer, currentEntry, writeServerType ? JsonGlobals.ValueString.ToLowerInvariant() : JsonGlobals.ValueString, declaredTypes[1], current.Value, context);
                keyValuePair.Add(currentEntry);
                context.PopKnownTypes(dataContract);
            }
            return keyValuePair;
        }
        public static IEnumerable ConvertGenericListToArray(DataContractJsonSerializer serializer, IEnumerable value, CollectionDataContract dataContract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType)
        {
            Type listArgumentType = dataContract.ItemType;
            if (listArgumentType.GetTypeInfo().IsGenericType)
            {
                listArgumentType = listArgumentType.GetGenericArguments()[0];
            }
            List<object> serializedList = new List<object>();
            MethodInfo getEnumeratorMethod = dataContract.GetEnumeratorMethod;

            IEnumerator enumerator = (getEnumeratorMethod == null) ? value.GetEnumerator() : (IEnumerator)getEnumeratorMethod.Invoke(value, Array.Empty<Type>());
            while (enumerator.MoveNext())
            {
                if (enumerator.Current == null || enumerator.Current.GetType().GetTypeInfo().IsPrimitive)
                {
                    serializedList.Add(enumerator.Current);
                }
                else
                {
                    Type currentItemType = enumerator.Current.GetType();
                    DataContract currentItemDataContract = DataContract.GetDataContract(currentItemType);
                    bool emitTypeInformation = EmitTypeInformation(dataContract.ItemContract, currentItemType);
                    if (writeServerType || emitTypeInformation)
                    {
                        context.CheckIfTypeNeedsVerifcation(dataContract.ItemContract, currentItemDataContract);
                    }
                    context.PushKnownTypes(dataContract);
                    serializedList.Add(serializer.ConvertDataContractToObject(enumerator.Current, currentItemDataContract, context, (writeServerType || emitTypeInformation), dataContract.ItemType.TypeHandle));
                    context.PopKnownTypes(dataContract);
                }
            }
            return serializedList;
        }
 private static void AddDictionaryEntryData(DataContractJsonSerializer serializer, Dictionary<string, object> currentEntry, string key, Type declaredType, object value, XmlObjectSerializerWriteContextComplexJson context)
 {
     if (value == null)
     {
         currentEntry[key] = value;
         return;
     }
     Type runtimeType = value.GetType();
     if (IsTypePrimitive(runtimeType))
     {
         currentEntry[key] = value;
     }
     else
     {
         if (declaredType.GetTypeInfo().IsGenericType && declaredType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
         {
             declaredType = Nullable.GetUnderlyingType(declaredType);
         }
         DataContract runtimeDataContract = DataContract.GetDataContract(runtimeType);
         if (declaredType != runtimeType)
         {
             context.VerifyType(runtimeDataContract);
         }
         currentEntry[key] = serializer.ConvertDataContractToObject(value, runtimeDataContract, context, EmitTypeInformation(runtimeDataContract, runtimeType), runtimeDataContract.UnderlyingType.TypeHandle);
     }
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     DataContractSerializer serializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), this.GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false, null);
     MemoryStream stream = new MemoryStream();
     serializer.WriteObject(stream, obj);
     stream.Position = 0L;
     string str = new StreamReader(stream).ReadToEnd();
     jsonWriter.WriteString(str);
 }
Example #5
0
        private static void WriteClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, ref Dictionary <string, object> classToDictionary, object value, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (dataContract.BaseContract != null)
            {
                WriteClassDataContractMembers(serializer, dataContract.BaseContract, ref classToDictionary, value, context);
            }

            for (int i = 0; i < dataContract.Members.Count; i++)
            {
                DataMember member      = dataContract.Members[i];
                object     memberValue = GetMemberValue(value, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
                string     memberName  = System.Xml.XmlConvert.DecodeName(member.Name);

                if (classToDictionary.ContainsKey(memberName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.JsonDuplicateMemberNames,
                                                                                                                   DataContract.GetClrTypeFullName(dataContract.UnderlyingType), memberName)));
                }

                if (!member.EmitDefaultValue)
                {
                    //Dont emit value if its null or default(valuetype)
                    if (memberValue == null || (member.MemberTypeContract.IsValueType && object.Equals(memberValue, Activator.CreateInstance(member.MemberType))))
                    {
                        continue;
                    }
                }
                if (memberValue == null || IsTypePrimitive(member.MemberType))
                {
                    classToDictionary[memberName] = memberValue;
                }
                else
                {
                    Type memberValueType = memberValue.GetType();
                    if (member.MemberType == memberValueType ||
                        //Special case Nullable<DateTimeOffset> and Nullable<Struct>
                        (member.IsNullable && !EmitTypeInformation(member.MemberTypeContract, memberValueType)))
                    {
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, member.MemberTypeContract, context, false, member.MemberTypeContract.UnderlyingType.TypeHandle);
                    }
                    else
                    {
                        //Push KnownTypes of this DataContract
                        context.PushKnownTypes(dataContract);
                        DataContract memberValueContract = DataContract.GetDataContract(memberValue.GetType());
                        if (member.MemberType.GetTypeInfo().IsInterface)
                        {
                            XmlObjectSerializerWriteContextComplexJson.VerifyObjectCompatibilityWithInterface(memberValueContract, memberValue, member.MemberType);
                        }
                        context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, memberValueContract, context, true, member.MemberTypeContract.UnderlyingType.TypeHandle);
                        context.PopKnownTypes(dataContract);
                    }
                }
            }
        }
        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
        {
            DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle),
                GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences

            MemoryStream memoryStream = new MemoryStream();
            dataContractSerializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            string serialized = new StreamReader(memoryStream).ReadToEnd();
            jsonWriter.WriteString(serialized);
        }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     if (IsULong)
     {
         jsonWriter.WriteUnsignedLong(((IConvertible)obj).ToUInt64(null));
     }
     else
     {
         jsonWriter.WriteLong(((IConvertible)obj).ToInt64(null));
     }
 }
        protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract)
        {
            var jsonContext = context as XmlObjectSerializerReadContextComplexJson;

            Debug.Assert(jsonContext != null);
            Debug.Assert(collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary);
            context.ReadAttributes(xmlReader);

            var itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);

            return(DataContractJsonSerializer.ReadJsonValue(itemContract, xmlReader, jsonContext));
        }
        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
        {
            if (MaxItemsInObjectGraph == 0)
            {
                throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph));
            }

            DataContract contract     = RootContract;
            Type         declaredType = contract.UnderlyingType;
            Type         graphType    = (graph == null) ? declaredType : graph.GetType();

            //if (dataContractSurrogate != null)
            //{
            //    graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType);
            //}

            if (graph == null)
            {
                WriteJsonNull(writer);
            }
            else
            {
                if (declaredType == graphType)
                {
                    if (contract.CanContainReferences)
                    {
                        XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract);
                        context.OnHandleReference(writer, graph, true); //  canContainReferences
                        context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
                    }
                    else
                    {
                        DataContractJsonSerializerImpl.WriteJsonValue(JsonDataContract.GetJsonDataContract(contract), writer, graph, null, declaredType.TypeHandle); //  XmlObjectSerializerWriteContextComplexJson
                    }
                }
                else
                {
                    XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract);
                    contract = DataContractJsonSerializerImpl.GetDataContract(contract, declaredType, graphType);
                    if (contract.CanContainReferences)
                    {
                        context.OnHandleReference(writer, graph, true); //  canContainCyclicReference
                        context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
                    }
                    else
                    {
                        context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
                    }
                }
            }
        }
 object ReadCollectionItem(CollectionDataContract collectionContract, Type itemType)
 {
     if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
     {
         context.ResetAttributes();
         var revisedContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);
         var v = DataContractJsonSerializer.ReadJsonValue(revisedContract, xmlReader, context);
         return(CodeInterpreter.ConvertValue(v, Globals.TypeOfObject, itemType));
     }
     else
     {
         return(ReadValue(itemType, JsonGlobals.itemString));
     }
 }
        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
        {
            if (this.MaxItemsInObjectGraph == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("ExceededMaxItemsQuota", new object[] { this.MaxItemsInObjectGraph })));
            }
            DataContract rootContract   = this.RootContract;
            Type         underlyingType = rootContract.UnderlyingType;
            Type         objType        = (graph == null) ? underlyingType : graph.GetType();

            if (this.dataContractSurrogate != null)
            {
                graph = DataContractSerializer.SurrogateToDataContractType(this.dataContractSurrogate, graph, underlyingType, ref objType);
            }
            if (graph == null)
            {
                WriteJsonNull(writer);
            }
            else if (underlyingType == objType)
            {
                if (rootContract.CanContainReferences)
                {
                    XmlObjectSerializerWriteContextComplexJson json = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, rootContract);
                    json.OnHandleReference(writer, graph, true);
                    json.SerializeWithoutXsiType(rootContract, writer, graph, underlyingType.TypeHandle);
                }
                else
                {
                    WriteJsonValue(JsonDataContract.GetJsonDataContract(rootContract), writer, graph, null, underlyingType.TypeHandle);
                }
            }
            else
            {
                XmlObjectSerializerWriteContextComplexJson json2 = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, this.RootContract);
                rootContract = GetDataContract(rootContract, underlyingType, objType);
                if (rootContract.CanContainReferences)
                {
                    json2.OnHandleReference(writer, graph, true);
                    json2.SerializeWithXsiTypeAtTopLevel(rootContract, writer, graph, underlyingType.TypeHandle, objType);
                }
                else
                {
                    json2.SerializeWithoutXsiType(rootContract, writer, graph, underlyingType.TypeHandle);
                }
            }
        }
		public void WriteCollectionToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.context = context;
			this.dataContract = dataContract;

			InitArgs (collectionContract.UnderlyingType);			

			// DemandMemberAccessPermission(memberAccessFlag);
			if (collectionContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
			}

			WriteCollection (collectionContract);
		}
        public void WriteCollectionToJson(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract)
        {
            this.writer       = xmlWriter;
            this.obj          = obj;
            this.context      = context;
            this.dataContract = dataContract;

            InitArgs(collectionContract.UnderlyingType);

            // DemandMemberAccessPermission(memberAccessFlag);
            if (collectionContract.IsReadOnlyContract)
            {
                DataContract.ThrowInvalidDataContractException(collectionContract.SerializationExceptionMessage, null);
            }

            WriteCollection(collectionContract);
        }
        public void WriteObject(Stream stream, object graph)
        {
            _jsonSerializer = new JavaScriptSerializer(stream);
            DataContract contract     = RootContract;
            Type         declaredType = contract.UnderlyingType;
            Type         graphType    = (graph == null) ? declaredType : graph.GetType();

            System.Runtime.Serialization.XmlWriterDelegator writer = null;
            if (graph == null)
            {
                _jsonSerializer.SerializeObject(null);
            }
            else
            {
                if (declaredType == graphType)
                {
                    if (contract.CanContainReferences)
                    {
                        XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract);
                        context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
                    }
                    else
                    {
                        WriteObjectInternal(graph, contract, null, false, declaredType.TypeHandle);
                    }
                }
                else
                {
                    XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract);
                    contract = DataContractSerializer.GetDataContract(contract, declaredType, graphType);

                    if (contract.CanContainReferences)
                    {
                        context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
                    }
                    else
                    {
                        context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
                    }
                }
            }
        }
        static internal void InvokeOnSerialized(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (contract is ClassDataContract)
            {
                ClassDataContract classContract = contract as ClassDataContract;

                if (classContract.BaseContract != null)
                {
                    InvokeOnSerialized(value, classContract.BaseContract, context);
                }
                if (classContract.OnSerialized != null)
                {
                    bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null, JsonGlobals.JsonSerializationPatterns);
                    try
                    {
                        DisallowMemberAccess(memberAccessFlag);
                        classContract.OnSerialized.Invoke(value, new object[] { context.GetStreamingContext() });
                    }
                    catch (SecurityException securityException)
                    {
                        if (memberAccessFlag)
                        {
                            classContract.RequiresMemberAccessForWrite(securityException, JsonGlobals.JsonSerializationPatterns);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (TargetInvocationException targetInvocationException)
                    {
                        if (targetInvocationException.InnerException == null)
                        {
                            throw;
                        }
                        //We are catching the TIE here and throws the inner exception only,
                        //this is needed to have a consistent exception story in all serializers
                        throw targetInvocationException.InnerException;
                    }
                }
            }
        }
		public void WriteToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString [] memberNames)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.context = context;
			this.dataContract = dataContract;
			this.memberNames = memberNames;

			InitArgs (classContract.UnderlyingType);

			// DemandSerializationFormatterPermission (classContract) - irrelevant
			// DemandMemberAccessPermission (memberAccessFlag) - irrelevant

			if (classContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
			}

			WriteClass (classContract);
		}
        public void WriteToJson(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString [] memberNames)
        {
            this.writer       = xmlWriter;
            this.obj          = obj;
            this.context      = context;
            this.dataContract = dataContract;
            this.memberNames  = memberNames;

            InitArgs(classContract.UnderlyingType);

            // DemandSerializationFormatterPermission (classContract) - irrelevant
            // DemandMemberAccessPermission (memberAccessFlag) - irrelevant

            if (classContract.IsReadOnlyContract)
            {
                DataContract.ThrowInvalidDataContractException(classContract.SerializationExceptionMessage, null);
            }

            WriteClass(classContract);
        }
        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
        {
            DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle),
                                                                                       GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences

            MemoryStream memoryStream = new MemoryStream();

            dataContractSerializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            string serialized = new StreamReader(memoryStream).ReadToEnd();

            jsonWriter.WriteString(serialized);
        }
Example #19
0
 public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
 }
Example #20
0
 public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     PushKnownDataContracts(context);
     WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
     PopKnownDataContracts(context);
 }
Example #21
0
 internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
 {
     _traditionalDataContract = traditionalDataContract;
     AddCollectionItemContractsToKnownDataContracts();
     _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
 }
Example #22
0
        private static void AddDictionaryEntryData(DataContractJsonSerializer serializer, Dictionary <string, object> currentEntry, string key, Type declaredType, object value, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (value == null)
            {
                currentEntry[key] = value;
                return;
            }
            Type runtimeType = value.GetType();

            if (IsTypePrimitive(runtimeType))
            {
                currentEntry[key] = value;
            }
            else
            {
                if (declaredType.GetTypeInfo().IsGenericType&& declaredType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
                {
                    declaredType = Nullable.GetUnderlyingType(declaredType);
                }
                DataContract runtimeDataContract = DataContract.GetDataContract(runtimeType);
                if (declaredType != runtimeType)
                {
                    context.VerifyType(runtimeDataContract);
                }
                currentEntry[key] = serializer.ConvertDataContractToObject(value, runtimeDataContract, context, EmitTypeInformation(runtimeDataContract, runtimeType), runtimeDataContract.UnderlyingType.TypeHandle);
            }
        }
        static internal void InvokeOnSerialized(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (contract is ClassDataContract)
            {
                ClassDataContract classContract = contract as ClassDataContract;

                if (classContract.BaseContract != null)
                    InvokeOnSerialized(value, classContract.BaseContract, context);
                if (classContract.OnSerialized != null)
                {
                    bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null);
                    try
                    {
                        classContract.OnSerialized.Invoke(value, new object[] { context.GetStreamingContext() });
                    }
                    catch (SecurityException securityException)
                    {
                        if (memberAccessFlag)
                        {
                            classContract.RequiresMemberAccessForWrite(securityException);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (TargetInvocationException targetInvocationException)
                    {
                        if (targetInvocationException.InnerException == null)
                            throw;
                        //We are catching the TIE here and throws the inner exception only,
                        //this is needed to have a consistent exception story in all serializers
                        throw targetInvocationException.InnerException;
                    }
                }
            }
        }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. 
     context.IsGetOnlyCollection = false;
     JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract);
 }
 internal void WriteObjectInternal(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
 {
     _jsonSerializer.SerializeObject(ConvertDataContractToObject(value, contract, context, writeServerType, declaredTypeHandle));
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
     JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames);
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
 }
        void WriteCollection(CollectionDataContract collectionContract)
        {
            XmlDictionaryString itemName = context.CollectionItemName;

            if (collectionContract.Kind == CollectionKind.Array)
            {
                Type itemType = collectionContract.ItemType;
                int  i;

                // This check does not exist in the original dynamic code,
                // but there is no other way to check type mismatch.
                // CollectionSerialization.ArrayContract() shows that it is required.
                if (objLocal.GetType().GetElementType() != itemType)
                {
                    throw new InvalidCastException(string.Format("Cannot cast array of {0} to array of {1}", objLocal.GetType().GetElementType(), itemType));
                }

                context.IncrementArrayCount(writer, (Array)objLocal);

                if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName))
                {
                    WriteArrayAttribute();
                    var arr = (Array)objLocal;
                    var idx = new int [1];
                    for (i = 0; i < arr.Length; i++)
                    {
                        if (!TryWritePrimitive(itemType, null, null, i, itemName, 0))
                        {
                            WriteStartElement(itemName, 0);
                            idx [0] = i;
                            var mbrVal = arr.GetValue(idx);
                            WriteValue(itemType, mbrVal);
                            WriteEndElement();
                        }
                    }
                }
            }
            else
            {
                // This check does not exist in the original dynamic code,
                // but there is no other way to check type mismatch.
                // CollectionSerialization.ArrayContract() shows that it is required.
                if (!collectionContract.UnderlyingType.IsAssignableFrom(objLocal.GetType()))
                {
                    throw new InvalidCastException(string.Format("Cannot cast {0} to {1}", objLocal.GetType(), collectionContract.UnderlyingType));
                }

                MethodInfo incrementCollectionCountMethod = null;
                switch (collectionContract.Kind)
                {
                case CollectionKind.Collection:
                case CollectionKind.List:
                case CollectionKind.Dictionary:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
                    break;

                case CollectionKind.GenericCollection:
                case CollectionKind.GenericList:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
                    break;

                case CollectionKind.GenericDictionary:
                    incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
                    break;
                }
                if (incrementCollectionCountMethod != null)
                {
                    incrementCollectionCountMethod.Invoke(context, new object [] { writer, objLocal });
                }

                bool    isDictionary = false, isGenericDictionary = false;
                Type    enumeratorType = null;
                Type [] keyValueTypes  = null;
                if (collectionContract.Kind == CollectionKind.GenericDictionary)
                {
                    isGenericDictionary = true;
                    keyValueTypes       = collectionContract.ItemType.GetGenericArguments();
                    enumeratorType      = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
                }
                else if (collectionContract.Kind == CollectionKind.Dictionary)
                {
                    isDictionary   = true;
                    keyValueTypes  = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
                    enumeratorType = Globals.TypeOfDictionaryEnumerator;
                }
                else
                {
                    enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
                }
                MethodInfo moveNextMethod   = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
                MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
                if (moveNextMethod == null || getCurrentMethod == null)
                {
                    if (enumeratorType.IsInterface)
                    {
                        if (moveNextMethod == null)
                        {
                            moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
                        }
                        if (getCurrentMethod == null)
                        {
                            getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
                        }
                    }
                    else
                    {
                        Type           ienumeratorInterface = Globals.TypeOfIEnumerator;
                        CollectionKind kind = collectionContract.Kind;
                        if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
                        {
                            Type[] interfaceTypes = enumeratorType.GetInterfaces();
                            foreach (Type interfaceType in interfaceTypes)
                            {
                                if (interfaceType.IsGenericType &&
                                    interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric &&
                                    interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
                                {
                                    ienumeratorInterface = interfaceType;
                                    break;
                                }
                            }
                        }
                        if (moveNextMethod == null)
                        {
                            moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
                        }
                        if (getCurrentMethod == null)
                        {
                            getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
                        }
                    }
                }
                Type   elementType  = getCurrentMethod.ReturnType;
                object currentValue = null;                 // of elementType

                var enumerator = (IEnumerator)collectionContract.GetEnumeratorMethod.Invoke(objLocal, new object [0]);
                if (isDictionary)
                {
                    ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { Globals.TypeOfIDictionaryEnumerator }, null);
                    enumerator = (IEnumerator)dictEnumCtor.Invoke(new object [] { enumerator });
                }
                else if (isGenericDictionary)
                {
                    Type            ctorParam    = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
                    ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, null, new Type[] { ctorParam }, null);
                    enumerator = (IEnumerator)Activator.CreateInstance(enumeratorType, new object [] { enumerator });
                }

                bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;

                bool         writeSimpleDictionary = canWriteSimpleDictionary && context.UseSimpleDictionaryFormat;
                PropertyInfo genericDictionaryKeyProperty = null, genericDictionaryValueProperty = null;

                if (canWriteSimpleDictionary)
                {
                    Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
                    genericDictionaryKeyProperty   = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString);
                    genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString);
                }

                if (writeSimpleDictionary)
                {
                    WriteObjectAttribute();
                    object key, value;
                    var    empty_args = new object [0];
                    while ((bool)moveNextMethod.Invoke(enumerator, empty_args))
                    {
                        currentValue = getCurrentMethod.Invoke(enumerator, empty_args);
                        key          = CodeInterpreter.GetMember(genericDictionaryKeyProperty, currentValue);
                        value        = CodeInterpreter.GetMember(genericDictionaryValueProperty, currentValue);

                        WriteStartElement(key, 0 /*nameIndex*/);
                        WriteValue(genericDictionaryValueProperty.PropertyType, value);
                        WriteEndElement();
                    }
                }
                else
                {
                    WriteArrayAttribute();

                    var emptyArray = new object [0];
                    while (enumerator != null && enumerator.MoveNext())
                    {
                        currentValue = getCurrentMethod.Invoke(enumerator, emptyArray);

                        if (incrementCollectionCountMethod == null)
                        {
                            XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke(context, new object [] { 1 });
                        }

                        if (!TryWritePrimitive(elementType, () => currentValue, null, null, itemName, 0))
                        {
                            WriteStartElement(itemName, 0);
                            if (isGenericDictionary || isDictionary)
                            {
                                var jc = JsonDataContract.GetJsonDataContract(XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(
                                                                                  collectionDataContract.ItemContract));
                                // FIXME: this TypeHandle might be wrong; there is no easy way to get Type for currentValue though.
                                DataContractJsonSerializer.WriteJsonValue(jc, writer, currentValue, context, currentValue.GetType().TypeHandle);
                            }
                            else
                            {
                                WriteValue(elementType, currentValue);
                            }
                            WriteEndElement();
                        }
                    }
                }
            }
        }
 public JsonClassDataContractCriticalHelper(ClassDataContract traditionalDataContract)
     : base(traditionalDataContract)
 {
     _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
     _traditionalClassDataContract = traditionalDataContract;
     CopyMembersAndCheckDuplicateNames();
 }
        int WriteMembers(ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract)
        {
            int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionData, derivedMostClassContract);

            context.IncrementItemCount(classContract.Members.Count);

            for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
            {
                DataMember member      = classContract.Members[i];
                Type       memberType  = member.MemberType;
                object     memberValue = null;
                if (member.IsGetOnlyCollection)
                {
                    context.StoreIsGetOnlyCollection();
                }
                bool doWrite = true, hasMemberValue = false;
                if (!member.EmitDefaultValue)
                {
                    hasMemberValue = true;
                    memberValue    = LoadMemberValue(member);
                    doWrite        = !IsDefaultValue(memberType, memberValue);
                }

                if (doWrite)
                {
                    bool requiresNameAttribute = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping(classContract.MemberNames [i]);

                    if (requiresNameAttribute || !TryWritePrimitive(memberType, hasMemberValue ? () => memberValue : (Func <object>)null, member.MemberInfo, null /*arrayItemIndex*/, null /*nameLocal*/, i + childElementIndex))
                    {
                        // Note: DataContractSerializer has member-conflict logic here to deal with the schema export
                        //       requirement that the same member can't be of two different types.
                        if (requiresNameAttribute)
                        {
                            XmlObjectSerializerWriteContextComplexJson.WriteJsonNameWithMapping(writer, memberNames, i + childElementIndex);
                        }
                        else
                        {
                            WriteStartElement(null /*nameLocal*/, i + childElementIndex);
                        }

                        if (memberValue == null)
                        {
                            memberValue = LoadMemberValue(member);
                        }
                        WriteValue(memberType, memberValue);
                        WriteEndElement();
                    }

                    if (classContract.HasExtensionData)
                    {
                        context.WriteExtensionData(writer, extensionData, memberCount);
                    }
                }
                else if (!member.EmitDefaultValue)
                {
                    if (member.IsRequired)
                    {
                        XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(member.Name, classContract.UnderlyingType);
                    }
                }
            }

            typeIndex++;
            childElementIndex += classContract.Members.Count;
            return(memberCount);
        }
 internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     contract.WriteJsonValue(writer, graph, context, declaredTypeHandle);
 }
Example #32
0
 public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     PushKnownDataContracts(context);
     WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
     PopKnownDataContracts(context);
 }
 internal void WriteObjectInternal(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
 {
     _jsonSerializer.SerializeObject(ConvertDataContractToObject(value, contract, context, writeServerType, declaredTypeHandle));
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
 }
Example #35
0
 public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
 }
        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
        {
            DataContractSerializer serializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), this.GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false, null);
            MemoryStream           stream     = new MemoryStream();

            serializer.WriteObject(stream, obj);
            stream.Position = 0L;
            string str = new StreamReader(stream).ReadToEnd();

            jsonWriter.WriteString(str);
        }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
     JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames);
 }
        internal object ConvertDataContractToObject(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
        {
            if (context != null)
            {
                context.OnHandleReference(null /*XmlWriter*/, value, true); //  canContainReferences 
            }
            try
            {
                if (contract is ObjectDataContract)
                {
                    Type valueType = value.GetType();
                    if (valueType != Globals.TypeOfObject)
                        return ConvertDataContractToObject(value, DataContract.GetDataContract(valueType), context, true, contract.UnderlyingType.TypeHandle);
                    else
                        return value;
                }
                else if (contract is TimeSpanDataContract)
                {
                    return XmlConvert.ToString((TimeSpan)value);
                }
                else if (contract is QNameDataContract)
                {
                    XmlQualifiedName qname = (XmlQualifiedName)value;
                    return (qname.IsEmpty) ? string.Empty : (qname.Name + ":" + qname.Namespace);
                }
                else if (contract is PrimitiveDataContract)
                {
                    return value;
                }
                else if (contract is CollectionDataContract)
                {
                    CollectionDataContract collectionContract = contract as CollectionDataContract;

                    switch (collectionContract.Kind)
                    {
                        case CollectionKind.GenericDictionary:
                        case CollectionKind.Dictionary:
                            return DataContractToObjectConverter.ConvertGenericDictionaryToArray(this, (IEnumerable)value, collectionContract, context, writeServerType);
                        default:
                            return DataContractToObjectConverter.ConvertGenericListToArray(this, (IEnumerable)value, collectionContract, context, writeServerType);
                    }
                }
                else if (contract is ClassDataContract)
                {
                    ClassDataContract classContract = contract as ClassDataContract;

                    if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType))
                    {
                        return ConvertScriptObjectToObject(value);
                    }

                    return DataContractToObjectConverter.ConvertClassDataContractToDictionary(this, (ClassDataContract)contract, value, context, writeServerType);
                }
                else if (contract is EnumDataContract)
                {
                    if (((EnumDataContract)contract).IsULong)
                        return Convert.ToUInt64(value, null);
                    else
                        return Convert.ToInt64(value, null);
                }
                else if (contract is XmlDataContract)
                {
                    DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList));
                    MemoryStream memoryStream = new MemoryStream();
                    dataContractSerializer.WriteObject(memoryStream, value);
                    memoryStream.Position = 0;
                    return new StreamReader(memoryStream, Encoding.UTF8).ReadToEnd();
                }
            }
            finally
            {
                if (context != null)
                {
                    context.OnEndHandleReference(null /*XmlWriter*/, value, true); //  canContainReferences 
                }
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownDataContract, contract.Name)));
        }
        //Deserialize '[...]' json string. The contents of the list can also be a dictionary i.e. [{...}]. The content type is detected
        //based on the type of CollectionDataContract.ItemContract.
        public static object ConvertICollectionToCollectionDataContract(DataContractJsonSerializer serializer, CollectionDataContract contract, object deserializedValue, XmlObjectSerializerReadContextComplexJson context)
        {
            Dictionary <string, object> valueAsDictionary = deserializedValue as Dictionary <string, object>;

            //Check to see if the dictionary (if it is a dictionary)is a regular Dictionary i.e { Key="key"; Value="value} and doesnt contain the __type string
            //for ex. the dictionary { __type="XXX"; Key="key"; Value="value} needs to be parsed as ClassDataContract
            if (valueAsDictionary != null && (!valueAsDictionary.ContainsKey(JsonGlobals.KeyString) || valueAsDictionary.ContainsKey(JsonGlobals.ServerTypeString)))
            {
                //If not then its a dictionary for either of these cases
                //1. Empty object - {}
                //2. Containes the __type information
                //3. Is a DateTimeOffsetDictionary
                return(ConvertDictionary(serializer, contract, valueAsDictionary, context));
            }

            object returnValue = (contract.Constructor != null) ? contract.Constructor.Invoke(Globals.EmptyTypeArray) : null;

            bool       isCollectionDataContractDictionary = contract.IsDictionary;
            MethodInfo addMethod      = contract.AddMethod;
            bool       convertToArray = contract.Kind == CollectionKind.Array;

            if (contract.UnderlyingType.GetTypeInfo().IsInterface || returnValue == null)
            {
                switch (contract.Kind)
                {
                case CollectionKind.Collection:
                case CollectionKind.GenericCollection:
                case CollectionKind.Enumerable:
                case CollectionKind.GenericEnumerable:
                case CollectionKind.List:
                case CollectionKind.GenericList:
                case CollectionKind.Array:
                    if (contract.UnderlyingType.GetTypeInfo().IsValueType)
                    {
                        //Initialize struct
                        returnValue = XmlFormatReaderGenerator.TryGetUninitializedObjectWithFormatterServices(contract.UnderlyingType);
                    }
                    else
                    {
                        returnValue    = Activator.CreateInstance(Globals.TypeOfListGeneric.MakeGenericType(contract.ItemType));
                        convertToArray = true;
                    }
                    break;

                case CollectionKind.GenericDictionary:
                    returnValue = Activator.CreateInstance(Globals.TypeOfDictionaryGeneric.MakeGenericType(contract.ItemType.GetGenericArguments()));
                    break;

                case CollectionKind.Dictionary:
                    returnValue = Activator.CreateInstance(Globals.TypeOfDictionaryGeneric.MakeGenericType(Globals.TypeOfObject, Globals.TypeOfObject));
                    break;
                }
            }
            if (addMethod == null)
            {
                //addMethod is null for IDictionary, IList and array types.
                Type[] paramArray = (contract.ItemType.GetTypeInfo().IsGenericType&& !convertToArray) ? contract.ItemType.GetGenericArguments() : new Type[] { contract.ItemType };
                addMethod = returnValue.GetType().GetMethod(Globals.AddMethodName, paramArray);
            }

            IEnumerator enumerator  = ((ICollection)deserializedValue).GetEnumerator();
            object      currentItem = null;

            object[] currentItemArray = null;
            while (enumerator.MoveNext())
            {
                DataContract itemContract = contract.ItemContract;
                if (itemContract is ClassDataContract)
                {
                    itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(itemContract);
                }
                currentItem      = serializer.ConvertObjectToDataContract(itemContract, enumerator.Current, context);
                currentItemArray = new object[] { currentItem };
                if (isCollectionDataContractDictionary)
                {
                    Type       currentItemType = currentItem.GetType();
                    MemberInfo keyMember       = currentItemType.GetMember("Key")[0];
                    MemberInfo valueMember     = currentItemType.GetMember("Value")[0];
                    currentItemArray = new object[] { DataContractToObjectConverter.GetMemberValue(currentItem, keyMember, currentItemType), DataContractToObjectConverter.GetMemberValue(currentItem, valueMember, currentItemType) };
                }
                addMethod.Invoke(returnValue, currentItemArray);
            }

            return((convertToArray) ? ConvertToArray(contract.ItemType, (ICollection)returnValue) : returnValue);
        }
Example #40
0
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
     context.IsGetOnlyCollection = false;
     JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract);
 }
 internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     contract.WriteJsonValue(writer, graph, context, declaredTypeHandle);
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     if (IsULong)
     {
         jsonWriter.WriteUnsignedLong(((IConvertible)obj).ToUInt64(null));
     }
     else
     {
         jsonWriter.WriteLong(((IConvertible)obj).ToInt64(null));
     }
 }
Example #43
0
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     context.IsGetOnlyCollection = false;
     this.JsonFormatWriterDelegate(jsonWriter, obj, context, this.TraditionalCollectionDataContract);
 }
        public static Dictionary<string, object> ConvertClassDataContractToDictionary(DataContractJsonSerializer serializer, ClassDataContract dataContract, object value, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType)
        {
            Dictionary<string, object> classToDictionary = new Dictionary<string, object>();

            if (writeServerType)
            {
                AddTypeInformation(classToDictionary, DataContract.GetDataContract(value.GetType()));
            }

            if (dataContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
            {
                DateTimeOffset dto = (DateTimeOffset)value;
                classToDictionary["DateTime"] = dto.UtcDateTime;
                classToDictionary["OffsetMinutes"] = (short)dto.Offset.TotalMinutes;
                return classToDictionary;
            }
            else if (dataContract.IsKeyValuePairAdapter)
            {
                //Convert KeyValuePair<K,T> to KeyValuePairAdapter<K,T>
                value = dataContract.KeyValuePairAdapterConstructorInfo.Invoke(new object[] { value });
            }

            DataContractJsonSerializer.InvokeOnSerializing(value, dataContract, context);
            WriteClassDataContractMembers(serializer, dataContract, ref classToDictionary, value, context);
            DataContractJsonSerializer.InvokeOnSerialized(value, dataContract, context);

            return classToDictionary;
        }
        private static void WriteClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, ref Dictionary<string, object> classToDictionary, object value, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (dataContract.BaseContract != null)
            {
                WriteClassDataContractMembers(serializer, dataContract.BaseContract, ref classToDictionary, value, context);
            }

            for (int i = 0; i < dataContract.Members.Count; i++)
            {
                DataMember member = dataContract.Members[i];
                object memberValue = GetMemberValue(value, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
                string memberName = System.Xml.XmlConvert.DecodeName(member.Name);

                if (classToDictionary.ContainsKey(memberName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.JsonDuplicateMemberNames,
    DataContract.GetClrTypeFullName(dataContract.UnderlyingType), memberName)));
                }

                if (!member.EmitDefaultValue)
                {
                    //Dont emit value if its null or default(valuetype)
                    if (memberValue == null || (member.MemberTypeContract.IsValueType && object.Equals(memberValue, Activator.CreateInstance(member.MemberType))))
                    {
                        continue;
                    }
                }
                if (memberValue == null || IsTypePrimitive(member.MemberType))
                {
                    classToDictionary[memberName] = memberValue;
                }
                else
                {
                    Type memberValueType = memberValue.GetType();
                    if (member.MemberType == memberValueType ||
                       //Special case Nullable<DateTimeOffset> and Nullable<Struct>
                       (member.IsNullable && !EmitTypeInformation(member.MemberTypeContract, memberValueType)))
                    {
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, member.MemberTypeContract, context, false, member.MemberTypeContract.UnderlyingType.TypeHandle);
                    }
                    else
                    {
                        //Push KnownTypes of this DataContract
                        context.PushKnownTypes(dataContract);
                        DataContract memberValueContract = DataContract.GetDataContract(memberValue.GetType());
                        if (member.MemberType.GetTypeInfo().IsInterface)
                        {
                            XmlObjectSerializerWriteContextComplexJson.VerifyObjectCompatibilityWithInterface(memberValueContract, memberValue, member.MemberType);
                        }
                        context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, memberValueContract, context, true, member.MemberTypeContract.UnderlyingType.TypeHandle);
                        context.PopKnownTypes(dataContract);
                    }
                }
            }
        }
Example #46
0
        protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] memberNames)
        {
            int memberCount = (classContract.BaseContract == null) ? 0 :
                              ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, memberNames);

            childElementIndex += memberCount;

            context.IncrementItemCount(classContract.Members.Count);
            for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
            {
                DataMember member     = classContract.Members[i];
                Type       memberType = member.MemberType;
                if (member.IsGetOnlyCollection)
                {
                    context.StoreIsGetOnlyCollection();
                }
                else
                {
                    context.ResetIsGetOnlyCollection();
                }


                bool   shouldWriteValue = true;
                object memberValue      = null;
                if (!member.EmitDefaultValue)
                {
                    memberValue = ReflectionGetMemberValue(obj, member);
                    object defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType);
                    if ((memberValue == null && defaultValue == null) ||
                        (memberValue != null && memberValue.Equals(defaultValue)))
                    {
                        shouldWriteValue = false;

                        if (member.IsRequired)
                        {
                            XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(member.Name, classContract.UnderlyingType);
                        }
                    }
                }

                if (shouldWriteValue)
                {
                    if (memberValue == null)
                    {
                        memberValue = ReflectionGetMemberValue(obj, member);
                    }
                    bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]);
                    PrimitiveDataContract primitiveContract = member.MemberPrimitiveContract;
                    if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null /*ns*/, primitiveContract))
                    {
                        // Note: DataContractSerializer has member-conflict logic here to deal with the schema export
                        //       requirement that the same member can't be of two different types.
                        if (requiresNameAttribute)
                        {
                            XmlObjectSerializerWriteContextComplexJson.WriteJsonNameWithMapping(xmlWriter, memberNames, i + childElementIndex);
                        }
                        else
                        {
                            ReflectionWriteStartElement(xmlWriter, memberNames[i + childElementIndex]);
                        }

                        ReflectionWriteValue(xmlWriter, context, memberType, memberValue, false /*writeXsiType*/, primitiveContractForParamType: null);
                        ReflectionWriteEndElement(xmlWriter);
                    }

                    if (classContract.HasExtensionData)
                    {
                        context.WriteExtensionData(xmlWriter, ((IExtensibleDataObject)obj).ExtensionData, memberCount);
                    }
                }
            }

            return(memberCount);
        }
        internal object ConvertDataContractToObject(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle)
        {
            if (context != null)
            {
                context.OnHandleReference(null /*XmlWriter*/, value, true); //  canContainReferences
            }
            try
            {
                if (contract is ObjectDataContract)
                {
                    Type valueType = value.GetType();
                    if (valueType != Globals.TypeOfObject)
                    {
                        return(ConvertDataContractToObject(value, DataContract.GetDataContract(valueType), context, true, contract.UnderlyingType.TypeHandle));
                    }
                    else
                    {
                        return(value);
                    }
                }
                else if (contract is TimeSpanDataContract)
                {
                    return(XmlConvert.ToString((TimeSpan)value));
                }
                else if (contract is QNameDataContract)
                {
                    XmlQualifiedName qname = (XmlQualifiedName)value;
                    return((qname.IsEmpty) ? string.Empty : (qname.Name + ":" + qname.Namespace));
                }
                else if (contract is PrimitiveDataContract)
                {
                    return(value);
                }
                else if (contract is CollectionDataContract)
                {
                    CollectionDataContract collectionContract = contract as CollectionDataContract;

                    switch (collectionContract.Kind)
                    {
                    case CollectionKind.GenericDictionary:
                    case CollectionKind.Dictionary:
                        return(DataContractToObjectConverter.ConvertGenericDictionaryToArray(this, (IEnumerable)value, collectionContract, context, writeServerType));

                    default:
                        return(DataContractToObjectConverter.ConvertGenericListToArray(this, (IEnumerable)value, collectionContract, context, writeServerType));
                    }
                }
                else if (contract is ClassDataContract)
                {
                    ClassDataContract classContract = contract as ClassDataContract;

                    if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType))
                    {
                        return(ConvertScriptObjectToObject(value));
                    }

                    return(DataContractToObjectConverter.ConvertClassDataContractToDictionary(this, (ClassDataContract)contract, value, context, writeServerType));
                }
                else if (contract is EnumDataContract)
                {
                    if (((EnumDataContract)contract).IsULong)
                    {
                        return(Convert.ToUInt64(value, null));
                    }
                    else
                    {
                        return(Convert.ToInt64(value, null));
                    }
                }
                else if (contract is XmlDataContract)
                {
                    DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList));
                    MemoryStream           memoryStream           = new MemoryStream();
                    dataContractSerializer.WriteObject(memoryStream, value);
                    memoryStream.Position = 0;
                    return(new StreamReader(memoryStream, Encoding.UTF8).ReadToEnd());
                }
            }
            finally
            {
                if (context != null)
                {
                    context.OnEndHandleReference(null /*XmlWriter*/, value, true); //  canContainReferences
                }
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownDataContract, contract.Name)));
        }
        public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract)
        {
            JsonWriterDelegator jsonWriter = xmlWriter as JsonWriterDelegator;
            if (jsonWriter == null)
            {
                throw new ArgumentException(nameof(xmlWriter));
            }

            XmlDictionaryString itemName = context.CollectionItemName;

            if (collectionContract.Kind == CollectionKind.Array)
            {
                context.IncrementArrayCount(jsonWriter, (Array)obj);
                Type itemType = collectionContract.ItemType;
                if (!ReflectionTryWritePrimitiveArray(jsonWriter, obj, collectionContract.UnderlyingType, itemType, itemName))
                {
                    ReflectionWriteArrayAttribute(jsonWriter);

                    Array array = (Array)obj;
                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                    for (int i = 0; i < array.Length; ++i)
                    {
                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
                        _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, itemType, array.GetValue(i), false, primitiveContract);
                        _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                    }
                }
            }
            else
            {
                collectionContract.IncrementCollectionCount(jsonWriter, obj, context);

                Type enumeratorReturnType;
                IEnumerator enumerator = collectionContract.GetEnumeratorForCollection(obj, out enumeratorReturnType);

                bool canWriteSimpleDictionary = collectionContract.Kind == CollectionKind.GenericDictionary
                                             || collectionContract.Kind == CollectionKind.Dictionary;

                bool useSimpleDictionaryFormat = context.UseSimpleDictionaryFormat;

                if (canWriteSimpleDictionary && useSimpleDictionaryFormat)
                {
                    ReflectionWriteObjectAttribute(jsonWriter);

                    while (enumerator.MoveNext())
                    {
                        object current = enumerator.Current;
                        object key = ((IKeyValue)current).Key;
                        object value = ((IKeyValue)current).Value;
                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString());
                        _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, value.GetType(), value, false, primitiveContractForParamType: null);
                        _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                    }
                }
                else
                {
                    ReflectionWriteArrayAttribute(jsonWriter);

                    PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(enumeratorReturnType);
                    if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject)
                    {
                        while (enumerator.MoveNext())
                        {
                            object current = enumerator.Current;
                            context.IncrementItemCount(1);
                            primitiveContractForType.WriteXmlElement(jsonWriter, current, context, itemName, null /*namespace*/);
                        }
                    }
                    else
                    {
                        bool isDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary;
                        while (enumerator.MoveNext())
                        {
                            object current = enumerator.Current;
                            context.IncrementItemCount(1);
                            _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
                            if (isDictionary)
                            {
                                var itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);
                                var jsonDataContract = JsonDataContract.GetJsonDataContract(itemContract);

                                jsonDataContract.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle);
                            }
                            else
                            {
                                _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, enumeratorReturnType, current, false, primitiveContractForParamType: null);
                            }

                            _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                        }
                    }
                }
            }
        }
Example #49
0
 public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[] memberNames)
 {
     _reflectionClassWriter.ReflectionWriteClass(xmlWriter, obj, context, classContract, memberNames);
 }
 public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
 {
     context.IsGetOnlyCollection = false;
     this.JsonFormatWriterDelegate(jsonWriter, obj, context, this.TraditionalCollectionDataContract);
 }
Example #51
0
        public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract)
        {
            JsonWriterDelegator jsonWriter = xmlWriter as JsonWriterDelegator;

            if (jsonWriter == null)
            {
                throw new ArgumentException(nameof(xmlWriter));
            }

            XmlDictionaryString itemName = context.CollectionItemName;

            if (collectionContract.Kind == CollectionKind.Array)
            {
                context.IncrementArrayCount(jsonWriter, (Array)obj);
                Type itemType = collectionContract.ItemType;
                if (!ReflectionTryWritePrimitiveArray(jsonWriter, obj, collectionContract.UnderlyingType, itemType, itemName))
                {
                    ReflectionWriteArrayAttribute(jsonWriter);

                    Array array = (Array)obj;
                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                    for (int i = 0; i < array.Length; ++i)
                    {
                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
                        _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, itemType, array.GetValue(i), false, primitiveContract);
                        _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                    }
                }
            }
            else
            {
                collectionContract.IncrementCollectionCount(jsonWriter, obj, context);

                IEnumerator enumerator = collectionContract.GetEnumeratorForCollection(obj);

                bool canWriteSimpleDictionary = collectionContract.Kind == CollectionKind.GenericDictionary ||
                                                collectionContract.Kind == CollectionKind.Dictionary;

                bool useSimpleDictionaryFormat = context.UseSimpleDictionaryFormat;

                if (canWriteSimpleDictionary && useSimpleDictionaryFormat)
                {
                    ReflectionWriteObjectAttribute(jsonWriter);
                    Type[] itemTypeGenericArguments = collectionContract.ItemType.GetGenericArguments();
                    Type   dictionaryValueType      = itemTypeGenericArguments.Length == 2 ? itemTypeGenericArguments[1] : null;

                    while (enumerator.MoveNext())
                    {
                        object current = enumerator.Current;
                        object key     = ((IKeyValue)current).Key;
                        object value   = ((IKeyValue)current).Value;
                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString());
                        _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, dictionaryValueType ?? value.GetType(), value, false, primitiveContractForParamType: null);
                        _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                    }
                }
                else
                {
                    ReflectionWriteArrayAttribute(jsonWriter);

                    PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType);
                    if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject)
                    {
                        while (enumerator.MoveNext())
                        {
                            object current = enumerator.Current;
                            context.IncrementItemCount(1);
                            primitiveContractForType.WriteXmlElement(jsonWriter, current, context, itemName, null /*namespace*/);
                        }
                    }
                    else
                    {
                        Type elementType  = collectionContract.GetCollectionElementType();
                        bool isDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary;

                        DataContract     itemContract     = null;
                        JsonDataContract jsonDataContract = null;
                        if (isDictionary)
                        {
                            itemContract     = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);
                            jsonDataContract = JsonDataContract.GetJsonDataContract(itemContract);
                        }

                        while (enumerator.MoveNext())
                        {
                            object current = enumerator.Current;
                            context.IncrementItemCount(1);
                            _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
                            if (isDictionary)
                            {
                                jsonDataContract.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle);
                            }
                            else
                            {
                                _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, elementType, current, false, primitiveContractForParamType: null);
                            }

                            _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                        }
                    }
                }
            }
        }
 public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[] memberNames)
 {
     _reflectionClassWriter.ReflectionWriteClass(xmlWriter, obj, context, classContract, memberNames);
 }