Imported Upstream version 4.6.0.125

Former-commit-id: a2155e9bd80020e49e72e86c44da02a8ac0e57a4
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2016-08-03 10:59:49 +00:00
parent a569aebcfd
commit e79aa3c0ed
17047 changed files with 3137615 additions and 392334 deletions

View File

@@ -0,0 +1,60 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
class ByteArrayHelperWithString : ArrayHelper<string, byte>
{
static public readonly ByteArrayHelperWithString Instance = new ByteArrayHelperWithString();
internal void WriteArray(XmlWriter writer, byte[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
writer.WriteAttributeString(string.Empty, JsonGlobals.typeString, string.Empty, JsonGlobals.arrayString);
for (int i = 0; i < count; i++)
{
writer.WriteStartElement(JsonGlobals.itemString, string.Empty);
writer.WriteAttributeString(string.Empty, JsonGlobals.typeString, string.Empty, JsonGlobals.numberString);
writer.WriteValue((int)array[offset + i]);
writer.WriteEndElement();
}
}
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, byte[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
int actual = 0;
while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
{
array[offset + actual] = ToByte(reader.ReadElementContentAsInt());
actual++;
}
return actual;
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, byte[] array, int offset, int count)
{
WriteArray(writer, array, offset, count);
}
void ThrowConversionException(string value, string type)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidConversion, value, type)));
}
byte ToByte(int value)
{
if (value < byte.MinValue || value > byte.MaxValue)
{
ThrowConversionException(value.ToString(System.Globalization.NumberFormatInfo.CurrentInfo), "Byte");
}
return (byte)value;
}
}
}

View File

@@ -0,0 +1,73 @@
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.Runtime.Serialization.Json
{
using System.Collections.Generic;
using System.Xml;
/// <summary>
/// Dummy documentation
/// </summary>
public class DataContractJsonSerializerSettings
{
private int maxItemsInObjectGraph = int.MaxValue;
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public string RootName { get; set; }
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public IEnumerable<Type> KnownTypes { get; set; }
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public int MaxItemsInObjectGraph
{
get
{
return this.maxItemsInObjectGraph;
}
set
{
this.maxItemsInObjectGraph = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether Dummy documentation
/// </summary>
public bool IgnoreExtensionDataObject { get; set; }
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public IDataContractSurrogate DataContractSurrogate { get; set; }
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public EmitTypeInformation EmitTypeInformation { get; set; }
/// <summary>
/// Gets or sets Dummy documentation
/// </summary>
public DateTimeFormat DateTimeFormat { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Dummy documentation
/// </summary>
public bool SerializeReadOnlyTypes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Dummy documentation
/// </summary>
public bool UseSimpleDictionaryFormat { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.IO;
using System.Text;
using System.Xml;
using System.Runtime.CompilerServices;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public interface IXmlJsonReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose);
void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose);
}
}

View File

@@ -0,0 +1,16 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.IO;
using System.Text;
using System.Runtime.CompilerServices;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public interface IXmlJsonWriterInitializer
{
void SetOutput(Stream stream, Encoding encoding, bool ownsStream);
}
}

View File

@@ -0,0 +1,33 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Xml;
class JsonByteArrayDataContract : JsonDataContract
{
public JsonByteArrayDataContract(ByteArrayDataContract traditionalByteArrayDataContract)
: base(traditionalByteArrayDataContract)
{
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
if (context == null)
{
return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsBase64();
}
else
{
return HandleReadValue(jsonReader.ReadElementContentAsBase64(), context);
}
}
}
}

View File

@@ -0,0 +1,190 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Threading;
using System.Xml;
using System.Diagnostics;
using System.ServiceModel;
using System.Collections.Generic;
using System.Security;
class JsonClassDataContract : JsonDataContract
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
JsonClassDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
public JsonClassDataContract(ClassDataContract traditionalDataContract)
: base(new JsonClassDataContractCriticalHelper(traditionalDataContract))
{
this.helper = base.Helper as JsonClassDataContractCriticalHelper;
}
internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonFormatReaderDelegate property.",
Safe = "JsonFormatReaderDelegate only needs to be protected for write.")]
[SecuritySafeCritical]
get
{
if (helper.JsonFormatReaderDelegate == null)
{
lock (this)
{
if (helper.JsonFormatReaderDelegate == null)
{
if (TraditionalClassDataContract.IsReadOnlyContract)
{
DataContract.ThrowInvalidDataContractException(TraditionalClassDataContract.DeserializationExceptionMessage, null /*type*/);
}
JsonFormatClassReaderDelegate tempDelegate = new JsonFormatReaderGenerator().GenerateClassReader(TraditionalClassDataContract);
Thread.MemoryBarrier();
helper.JsonFormatReaderDelegate = tempDelegate;
}
}
}
return helper.JsonFormatReaderDelegate;
}
}
internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonFormatWriterDelegate property.",
Safe = "JsonFormatWriterDelegate only needs to be protected for write.")]
[SecuritySafeCritical]
get
{
if (helper.JsonFormatWriterDelegate == null)
{
lock (this)
{
if (helper.JsonFormatWriterDelegate == null)
{
JsonFormatClassWriterDelegate tempDelegate = new JsonFormatWriterGenerator().GenerateClassWriter(TraditionalClassDataContract);
Thread.MemoryBarrier();
helper.JsonFormatWriterDelegate = tempDelegate;
}
}
}
return helper.JsonFormatWriterDelegate;
}
}
internal XmlDictionaryString[] MemberNames
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical MemberNames property.",
Safe = "MemberNames only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.MemberNames; }
}
internal override string TypeName
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical TypeName property.",
Safe = "TypeName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.TypeName; }
}
ClassDataContract TraditionalClassDataContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical TraditionalClassDataContract property.",
Safe = "TraditionalClassDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.TraditionalClassDataContract; }
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
jsonReader.Read();
object o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, MemberNames);
jsonReader.ReadEndElement();
return o;
}
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);
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
+ "Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
#endif
class JsonClassDataContractCriticalHelper : JsonDataContractCriticalHelper
{
JsonFormatClassReaderDelegate jsonFormatReaderDelegate;
JsonFormatClassWriterDelegate jsonFormatWriterDelegate;
XmlDictionaryString[] memberNames;
ClassDataContract traditionalClassDataContract;
string typeName;
public JsonClassDataContractCriticalHelper(ClassDataContract traditionalDataContract)
: base(traditionalDataContract)
{
this.typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
this.traditionalClassDataContract = traditionalDataContract;
CopyMembersAndCheckDuplicateNames();
}
internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate
{
get { return this.jsonFormatReaderDelegate; }
set { this.jsonFormatReaderDelegate = value; }
}
internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate
{
get { return this.jsonFormatWriterDelegate; }
set { this.jsonFormatWriterDelegate = value; }
}
internal XmlDictionaryString[] MemberNames
{
get { return this.memberNames; }
}
internal ClassDataContract TraditionalClassDataContract
{
get { return this.traditionalClassDataContract; }
}
void CopyMembersAndCheckDuplicateNames()
{
if (traditionalClassDataContract.MemberNames != null)
{
int memberCount = traditionalClassDataContract.MemberNames.Length;
Dictionary<string, object> memberTable = new Dictionary<string, object>(memberCount);
XmlDictionaryString[] decodedMemberNames = new XmlDictionaryString[memberCount];
for (int i = 0; i < memberCount; i++)
{
if (memberTable.ContainsKey(traditionalClassDataContract.MemberNames[i].Value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.JsonDuplicateMemberNames,
DataContract.GetClrTypeFullName(traditionalClassDataContract.UnderlyingType), traditionalClassDataContract.MemberNames[i].Value)));
}
else
{
memberTable.Add(traditionalClassDataContract.MemberNames[i].Value, null);
decodedMemberNames[i] = DataContractJsonSerializer.ConvertXmlNameToJsonName(traditionalClassDataContract.MemberNames[i]);
}
}
this.memberNames = decodedMemberNames;
}
}
}
}
}

View File

@@ -0,0 +1,187 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Threading;
using System.Xml;
using System.Security;
class JsonCollectionDataContract : JsonDataContract
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
JsonCollectionDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
public JsonCollectionDataContract(CollectionDataContract traditionalDataContract)
: base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract))
{
this.helper = base.Helper as JsonCollectionDataContractCriticalHelper;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonFormatReaderDelegate property.",
Safe = "JsonFormatReaderDelegate only needs to be protected for write.")]
[SecuritySafeCritical]
get
{
if (helper.JsonFormatReaderDelegate == null)
{
lock (this)
{
if (helper.JsonFormatReaderDelegate == null)
{
if (TraditionalCollectionDataContract.IsReadOnlyContract)
{
DataContract.ThrowInvalidDataContractException(TraditionalCollectionDataContract.DeserializationExceptionMessage, null /*type*/);
}
JsonFormatCollectionReaderDelegate tempDelegate = new JsonFormatReaderGenerator().GenerateCollectionReader(TraditionalCollectionDataContract);
Thread.MemoryBarrier();
helper.JsonFormatReaderDelegate = tempDelegate;
}
}
}
return helper.JsonFormatReaderDelegate;
}
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonFormatGetOnlyReaderDelegate property.",
Safe = "JsonFormatGetOnlyReaderDelegate only needs to be protected for write; initialized in getter if null.")]
[SecuritySafeCritical]
get
{
if (helper.JsonFormatGetOnlyReaderDelegate == null)
{
lock (this)
{
if (helper.JsonFormatGetOnlyReaderDelegate == null)
{
CollectionKind kind = this.TraditionalCollectionDataContract.Kind;
if (this.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GetOnlyCollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(this.TraditionalDataContract.UnderlyingType))));
}
if (TraditionalCollectionDataContract.IsReadOnlyContract)
{
DataContract.ThrowInvalidDataContractException(TraditionalCollectionDataContract.DeserializationExceptionMessage, null /*type*/);
}
JsonFormatGetOnlyCollectionReaderDelegate tempDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract);
Thread.MemoryBarrier();
helper.JsonFormatGetOnlyReaderDelegate = tempDelegate;
}
}
}
return helper.JsonFormatGetOnlyReaderDelegate;
}
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonFormatWriterDelegate property.",
Safe = "JsonFormatWriterDelegate only needs to be protected for write.")]
[SecuritySafeCritical]
get
{
if (helper.JsonFormatWriterDelegate == null)
{
lock (this)
{
if (helper.JsonFormatWriterDelegate == null)
{
JsonFormatCollectionWriterDelegate tempDelegate = new JsonFormatWriterGenerator().GenerateCollectionWriter(TraditionalCollectionDataContract);
Thread.MemoryBarrier();
helper.JsonFormatWriterDelegate = tempDelegate;
}
}
}
return helper.JsonFormatWriterDelegate;
}
}
CollectionDataContract TraditionalCollectionDataContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical TraditionalCollectionDataContract property.",
Safe = "TraditionalCollectionDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.TraditionalCollectionDataContract; }
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
jsonReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
JsonFormatGetOnlyReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
else
{
o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract);
}
jsonReader.ReadEndElement();
return o;
}
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);
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
+ "Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
#endif
class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper
{
JsonFormatCollectionReaderDelegate jsonFormatReaderDelegate;
JsonFormatGetOnlyCollectionReaderDelegate jsonFormatGetOnlyReaderDelegate;
JsonFormatCollectionWriterDelegate jsonFormatWriterDelegate;
CollectionDataContract traditionalCollectionDataContract;
public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract)
: base(traditionalDataContract)
{
this.traditionalCollectionDataContract = traditionalDataContract;
}
internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
{
get { return this.jsonFormatReaderDelegate; }
set { this.jsonFormatReaderDelegate = value; }
}
internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
{
get { return this.jsonFormatGetOnlyReaderDelegate; }
set { this.jsonFormatGetOnlyReaderDelegate = value; }
}
internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
{
get { return this.jsonFormatWriterDelegate; }
set { this.jsonFormatWriterDelegate = value; }
}
internal CollectionDataContract TraditionalCollectionDataContract
{
get { return this.traditionalCollectionDataContract; }
}
}
}
}

View File

@@ -0,0 +1,345 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.Reflection;
using System.ServiceModel;
using System.Xml;
#if USE_REFEMIT
public class JsonDataContract
#else
class JsonDataContract
#endif
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
JsonDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
protected JsonDataContract(DataContract traditionalDataContract)
{
this.helper = new JsonDataContractCriticalHelper(traditionalDataContract);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
protected JsonDataContract(JsonDataContractCriticalHelper helper)
{
this.helper = helper;
}
internal virtual string TypeName
{
get { return null; }
}
protected JsonDataContractCriticalHelper Helper
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
get { return helper; }
}
protected DataContract TraditionalDataContract
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical TraditionalDataContract from the helper.",
Safe = "TraditionalDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.TraditionalDataContract; }
}
Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical KnownDataContracts from the helper.",
Safe = "KnownDataContracts only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.KnownDataContracts; }
}
[Fx.Tag.SecurityNote(Critical = "Fetches the critical JsonDataContract from the helper.",
Safe = "JsonDataContract only needs to be protected for write.")]
[SecuritySafeCritical]
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
}
public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
PushKnownDataContracts(context);
object deserializedObject = ReadJsonValueCore(jsonReader, context);
PopKnownDataContracts(context);
return deserializedObject;
}
public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
return TraditionalDataContract.ReadXmlValue(jsonReader, context);
}
public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
PushKnownDataContracts(context);
WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
PopKnownDataContracts(context);
}
public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
}
protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context)
{
context.AddNewObject(obj);
return obj;
}
protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader)
{
while (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString))
{
reader.Skip();
reader.MoveToElement();
return true;
}
reader.MoveToElement();
return false;
}
protected void PopKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Pop();
}
}
protected void PushKnownDataContracts(XmlObjectSerializerContext context)
{
if (KnownDataContracts != null)
{
context.scopedKnownTypes.Push(KnownDataContracts);
}
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
+ "Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
#endif
#if USE_REFEMIT
public class JsonDataContractCriticalHelper
#else
internal class JsonDataContractCriticalHelper
#endif
{
static object cacheLock = new object();
static object createDataContractLock = new object();
static JsonDataContract[] dataContractCache = new JsonDataContract[32];
static int dataContractID = 0;
static TypeHandleRef typeHandleRef = new TypeHandleRef();
static Dictionary<TypeHandleRef, IntRef> typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
Dictionary<XmlQualifiedName, DataContract> knownDataContracts;
DataContract traditionalDataContract;
string typeName;
internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
{
this.traditionalDataContract = traditionalDataContract;
AddCollectionItemContractsToKnownDataContracts();
this.typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
}
internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts
{
get { return this.knownDataContracts; }
}
internal DataContract TraditionalDataContract
{
get { return this.traditionalDataContract; }
}
internal virtual string TypeName
{
get { return this.typeName; }
}
public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
{
int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle);
JsonDataContract dataContract = dataContractCache[id];
if (dataContract == null)
{
dataContract = CreateJsonDataContract(id, traditionalDataContract);
dataContractCache[id] = dataContract;
}
return dataContract;
}
internal static int GetId(RuntimeTypeHandle typeHandle)
{
lock (cacheLock)
{
IntRef id;
typeHandleRef.Value = typeHandle;
if (!typeToIDCache.TryGetValue(typeHandleRef, out id))
{
int value = dataContractID++;
if (value >= dataContractCache.Length)
{
int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
if (newSize <= value)
{
Fx.Assert("DataContract cache overflow");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.DataContractCacheOverflow)));
}
Array.Resize<JsonDataContract>(ref dataContractCache, newSize);
}
id = new IntRef(value);
try
{
typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
}
}
return id.Value;
}
}
static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
{
lock (createDataContractLock)
{
JsonDataContract dataContract = dataContractCache[id];
if (dataContract == null)
{
Type traditionalDataContractType = traditionalDataContract.GetType();
if (traditionalDataContractType == typeof(ObjectDataContract))
{
dataContract = new JsonObjectDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(StringDataContract))
{
dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(UriDataContract))
{
dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(QNameDataContract))
{
dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ByteArrayDataContract))
{
dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
}
else if (traditionalDataContract.IsPrimitive ||
traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(ClassDataContract))
{
dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(EnumDataContract))
{
dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
}
else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
(traditionalDataContractType == typeof(SpecialTypeDataContract)))
{
dataContract = new JsonDataContract(traditionalDataContract);
}
else if (traditionalDataContractType == typeof(CollectionDataContract))
{
dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
}
else if (traditionalDataContractType == typeof(XmlDataContract))
{
dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("traditionalDataContract",
SR.GetString(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType));
}
}
return dataContract;
}
}
void AddCollectionItemContractsToKnownDataContracts()
{
if (traditionalDataContract.KnownDataContracts != null)
{
foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in traditionalDataContract.KnownDataContracts)
{
if (!object.ReferenceEquals(knownDataContract, null))
{
CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
while (collectionDataContract != null)
{
DataContract itemContract = collectionDataContract.ItemContract;
if (knownDataContracts == null)
{
knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>();
}
if (!knownDataContracts.ContainsKey(itemContract.StableName))
{
knownDataContracts.Add(itemContract.StableName, itemContract);
}
if (collectionDataContract.ItemType.IsGenericType
&& collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>))
{
DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments()));
if (!knownDataContracts.ContainsKey(itemDataContract.StableName))
{
knownDataContracts.Add(itemDataContract.StableName, itemDataContract);
}
}
if (!(itemContract is CollectionDataContract))
{
break;
}
collectionDataContract = itemContract as CollectionDataContract;
}
}
}
}
}
}
}
}

View File

@@ -0,0 +1,88 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Xml;
using System.Security;
class JsonEnumDataContract : JsonDataContract
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ "Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
JsonEnumDataContractCriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
public JsonEnumDataContract(EnumDataContract traditionalDataContract)
: base(new JsonEnumDataContractCriticalHelper(traditionalDataContract))
{
this.helper = base.Helper as JsonEnumDataContractCriticalHelper;
}
public bool IsULong
{
[Fx.Tag.SecurityNote(Critical = "Fetches the critical IsULong property.",
Safe = "IsULong only needs to be protected for write.")]
[SecuritySafeCritical]
get { return this.helper.IsULong; }
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
object enumValue;
if (IsULong)
{
enumValue = Enum.ToObject(TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsUnsignedLong());
}
else
{
enumValue = Enum.ToObject(TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsLong());
}
if (context != null)
{
context.AddNewObject(enumValue);
}
return enumValue;
}
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));
}
}
[Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
+ "Since the data is cached statically, we lock down access to it.")]
#if !NO_SECURITY_ATTRIBUTES
#pragma warning disable 618 // have not moved to the v4 security model yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
#endif
class JsonEnumDataContractCriticalHelper : JsonDataContractCriticalHelper
{
bool isULong;
public JsonEnumDataContractCriticalHelper(EnumDataContract traditionalEnumDataContract)
: base(traditionalEnumDataContract)
{
isULong = traditionalEnumDataContract.IsULong;
}
public bool IsULong
{
get { return this.isULong; }
}
}
}
}

View File

@@ -0,0 +1,84 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Runtime.Serialization;
using System.Xml;
using System.Security;
using System.Reflection;
static class JsonGlobals
{
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly int DataContractXsdBaseNamespaceLength = Globals.DataContractXsdBaseNamespace.Length;
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly XmlDictionaryString dDictionaryString = new XmlDictionary().Add("d");
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly char[] floatingPointCharacters = new char[] { '.', 'e' };
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly XmlDictionaryString itemDictionaryString = new XmlDictionary().Add("item");
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly XmlDictionaryString rootDictionaryString = new XmlDictionary().Add("root");
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Static fields are marked SecurityCritical or readonly to prevent"
+ " data from being modified or leaked to other components in appdomain.")]
public static readonly long unixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
public const string applicationJsonMediaType = "application/json";
public const string arrayString = "array";
public const string booleanString = "boolean";
public const string CacheControlString = "Cache-Control";
public const byte CollectionByte = (byte)CollectionChar;
public const char CollectionChar = '[';
public const string DateTimeEndGuardReader = ")/";
public const string DateTimeEndGuardWriter = ")\\/";
public const string DateTimeStartGuardReader = "/Date(";
public const string DateTimeStartGuardWriter = "\\/Date(";
public const string dString = "d";
public const byte EndCollectionByte = (byte)EndCollectionChar;
public const char EndCollectionChar = ']';
public const byte EndObjectByte = (byte)EndObjectChar;
public const char EndObjectChar = '}';
public const string ExpiresString = "Expires";
public const string IfModifiedSinceString = "If-Modified-Since";
public const string itemString = "item";
public const string jsonerrorString = "jsonerror";
public const string KeyString = "Key";
public const string LastModifiedString = "Last-Modified";
public const int maxScopeSize = 25;
public const byte MemberSeparatorByte = (byte)MemberSeparatorChar;
public const char MemberSeparatorChar = ',';
public const byte NameValueSeparatorByte = (byte)NameValueSeparatorChar;
public const char NameValueSeparatorChar = ':';
public const string NameValueSeparatorString = ":";
public const string nullString = "null";
public const string numberString = "number";
public const byte ObjectByte = (byte)ObjectChar;
public const char ObjectChar = '{';
public const string objectString = "object";
public const string publicString = "public";
public const byte QuoteByte = (byte)QuoteChar;
public const char QuoteChar = '"';
public const string rootString = "root";
public const string serverTypeString = "__type";
public const string stringString = "string";
public const string textJsonMediaType = "text/json";
public const string trueString = "true";
public const string typeString = "type";
public const string ValueString = "Value";
public const char WhitespaceChar = ' ';
public const string xmlnsPrefix = "xmlns";
public const string xmlPrefix = "xml";
}
}

View File

@@ -0,0 +1,17 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
enum JsonNodeType
{
None,
Object,
Element,
EndElement,
QuotedText,
StandaloneText,
Collection
}
}

View File

@@ -0,0 +1,116 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Xml;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Globalization;
class JsonObjectDataContract : JsonDataContract
{
public JsonObjectDataContract(DataContract traditionalDataContract)
: base(traditionalDataContract)
{
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
object obj;
string contentMode = jsonReader.GetAttribute(JsonGlobals.typeString);
switch (contentMode)
{
case JsonGlobals.nullString:
jsonReader.Skip();
obj = null;
break;
case JsonGlobals.booleanString:
obj = jsonReader.ReadElementContentAsBoolean();
break;
case JsonGlobals.stringString:
case null:
obj = jsonReader.ReadElementContentAsString();
break;
case JsonGlobals.numberString:
obj = ParseJsonNumber(jsonReader.ReadElementContentAsString());
break;
case JsonGlobals.objectString:
jsonReader.Skip();
obj = new object();
break;
case JsonGlobals.arrayString:
// Read as object array
return DataContractJsonSerializer.ReadJsonValue(DataContract.GetDataContract(Globals.TypeOfObjectArray), jsonReader, context);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.JsonUnexpectedAttributeValue, contentMode)));
}
if (context != null)
{
context.AddNewObject(obj);
}
return obj;
}
public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
{
jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
}
internal static object ParseJsonNumber(string value, out TypeCode objectTypeCode)
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.XmlInvalidConversion, value, Globals.TypeOfInt)));
}
if (value.IndexOfAny(JsonGlobals.floatingPointCharacters) == -1)
{
int intValue;
if (Int32.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out intValue))
{
objectTypeCode = TypeCode.Int32;
return intValue;
}
long longValue;
if (Int64.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out longValue))
{
objectTypeCode = TypeCode.Int64;
return longValue;
}
}
decimal decimalValue;
if (Decimal.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out decimalValue))
{
objectTypeCode = TypeCode.Decimal;
//check for decimal underflow
if (decimalValue == Decimal.Zero)
{
double doubleValue = XmlConverter.ToDouble(value);
if (doubleValue != 0.0)
{
objectTypeCode = TypeCode.Double;
return doubleValue;
}
}
return decimalValue;
}
objectTypeCode = TypeCode.Double;
return XmlConverter.ToDouble(value);
}
static object ParseJsonNumber(string value)
{
TypeCode unusedTypeCode;
return ParseJsonNumber(value, out unusedTypeCode);
}
}
}

View File

@@ -0,0 +1,32 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Xml;
class JsonQNameDataContract : JsonDataContract
{
public JsonQNameDataContract(QNameDataContract traditionalQNameDataContract)
: base(traditionalQNameDataContract)
{
}
public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
{
if (context == null)
{
return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsQName();
}
else
{
return HandleReadValue(jsonReader.ReadElementContentAsQName(), context);
}
}
}
}

View File

@@ -0,0 +1,370 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System.Xml;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Globalization;
#if USE_REFEMIT
public class JsonReaderDelegator : XmlReaderDelegator
#else
internal class JsonReaderDelegator : XmlReaderDelegator
#endif
{
DateTimeFormat dateTimeFormat;
DateTimeArrayJsonHelperWithString dateTimeArrayHelper;
public JsonReaderDelegator(XmlReader reader)
: base(reader)
{
}
public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
: this(reader)
{
this.dateTimeFormat = dateTimeFormat;
}
internal XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
if (this.dictionaryReader == null)
{
return null;
}
else
{
return dictionaryReader.Quotas;
}
}
}
DateTimeArrayJsonHelperWithString DateTimeArrayHelper
{
get
{
if (dateTimeArrayHelper == null)
{
dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(this.dateTimeFormat);
}
return dateTimeArrayHelper;
}
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override char ReadContentAsChar()
{
return XmlConvert.ToChar(ReadContentAsString());
}
internal override XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
#if USE_REFEMIT
public override char ReadElementContentAsChar()
#else
internal override char ReadElementContentAsChar()
#endif
{
return XmlConvert.ToChar(ReadElementContentAsString());
}
#if USE_REFEMIT
public override byte[] ReadContentAsBase64()
#else
internal override byte[] ReadContentAsBase64()
#endif
{
if (isEndOfEmptyElement)
return new byte[0];
byte[] buffer;
if (dictionaryReader == null)
{
XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength);
}
else
{
buffer = ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, JsonGlobals.itemString, string.Empty, dictionaryReader.Quotas.MaxArrayLength);
}
return buffer;
}
#if USE_REFEMIT
public override byte[] ReadElementContentAsBase64()
#else
internal override byte[] ReadElementContentAsBase64()
#endif
{
if (isEndOfEmptyElement)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.XmlStartElementExpected, "EndElement")));
}
bool isEmptyElement = reader.IsStartElement() && reader.IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
reader.Read();
buffer = new byte[0];
}
else
{
reader.ReadStartElement();
buffer = ReadContentAsBase64();
reader.ReadEndElement();
}
return buffer;
}
internal override DateTime ReadContentAsDateTime()
{
return ParseJsonDate(ReadContentAsString(), this.dateTimeFormat);
}
internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat)
{
if (dateTimeFormat == null)
{
return ParseJsonDateInDefaultFormat(originalDateTimeValue);
}
else
{
return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles);
}
}
internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue)
{
// Dates are represented in JSON as "\/Date(number of ticks)\/".
// The number of ticks is the number of milliseconds since January 1, 1970.
string dateTimeValue;
if (!string.IsNullOrEmpty(originalDateTimeValue))
{
dateTimeValue = originalDateTimeValue.Trim();
}
else
{
dateTimeValue = originalDateTimeValue;
}
if (string.IsNullOrEmpty(dateTimeValue) ||
!dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) ||
!dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new FormatException(SR.GetString(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter)));
}
string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
long millisecondsSinceUnixEpoch;
DateTimeKind dateTimeKind = DateTimeKind.Utc;
int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);
if (indexOfTimeZoneOffset == -1)
{
indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
}
if (indexOfTimeZoneOffset != -1)
{
dateTimeKind = DateTimeKind.Local;
ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset);
}
try
{
millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, CultureInfo.InvariantCulture);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception));
}
// Convert from # millseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;
try
{
DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
switch (dateTimeKind)
{
case DateTimeKind.Local:
return dateTime.ToLocalTime();
case DateTimeKind.Unspecified:
return DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
case DateTimeKind.Utc:
default:
return dateTime;
}
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception));
}
}
#if USE_REFEMIT
public override DateTime ReadElementContentAsDateTime()
#else
internal override DateTime ReadElementContentAsDateTime()
#endif
{
return ParseJsonDate(ReadElementContentAsString(), this.dateTimeFormat);
}
internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context,
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if ((dictionaryReader == null) || (arrayLength != -1))
{
array = null;
return false;
}
array = this.DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
return true;
}
class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime>
{
DateTimeFormat dateTimeFormat;
public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
{
this.dateTimeFormat = dateTimeFormat;
}
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
int actual = 0;
while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
{
array[offset + actual] = JsonReaderDelegator.ParseJsonDate(reader.ReadElementContentAsString(), this.dateTimeFormat);
actual++;
}
return actual;
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal override ulong ReadContentAsUnsignedLong()
{
string value = reader.ReadContentAsString();
if (value == null || value.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.GetString(System.Runtime.Serialization.SR.XmlInvalidConversion, value, "UInt64"))));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
#if USE_REFEMIT
[CLSCompliant(false)]
public override UInt64 ReadElementContentAsUnsignedLong()
#else
internal override UInt64 ReadElementContentAsUnsignedLong()
#endif
{
if (isEndOfEmptyElement)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.XmlStartElementExpected, "EndElement")));
}
string value = reader.ReadElementContentAsString();
if (value == null || value.Length == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, System.Runtime.Serialization.SR.GetString(System.Runtime.Serialization.SR.XmlInvalidConversion, value, "UInt64"))));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception));
}
}
}
}

View File

@@ -0,0 +1,82 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.ServiceModel;
using System.Runtime.Serialization.Json;
using System.Runtime.CompilerServices;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public static class JsonReaderWriterFactory
{
const string DefaultIndentChars = " ";
public static XmlDictionaryReader CreateJsonReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateJsonReader(stream, null, quotas, null);
}
public static XmlDictionaryReader CreateJsonReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
}
return CreateJsonReader(buffer, 0, buffer.Length, null, quotas, null);
}
public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
XmlJsonReader reader = new XmlJsonReader();
reader.SetInput(stream, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateJsonReader(buffer, offset, count, null, quotas, null);
}
public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
XmlJsonReader reader = new XmlJsonReader();
reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryWriter CreateJsonWriter(Stream stream)
{
return CreateJsonWriter(stream, Encoding.UTF8, true);
}
public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding)
{
return CreateJsonWriter(stream, encoding, true);
}
public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream)
{
return CreateJsonWriter(stream, encoding, ownsStream, false);
}
public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent)
{
return CreateJsonWriter(stream, encoding, ownsStream, indent, JsonReaderWriterFactory.DefaultIndentChars);
}
public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)
{
XmlJsonWriter writer = new XmlJsonWriter(indent, indentChars);
writer.SetOutput(stream, encoding, ownsStream);
return writer;
}
}
}

Some files were not shown because too many files have changed in this diff Show More